user_model.dart 14.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:one_key/constant/constant.dart';
import 'package:one_key/constant/error.dart';
import 'package:one_key/models/pull_marketing_by_uid_model.dart';
import 'package:one_key/models/user.dart';
import 'package:one_key/net/base_resp.dart';
import 'package:one_key/net/dio_util.dart';
import 'package:one_key/net/http_url.dart';
import 'package:one_key/provider/table_manager_model.dart';
import 'package:one_key/res/colors.dart';
import 'package:one_key/route/navigator_util.dart';
import 'package:one_key/utils/utils.dart';
import 'package:one_key/widgets/MyDivider.dart';
import 'package:one_key/widgets/loading.dart';
import 'package:one_key/widgets/v_empty_view.dart';
import 'package:provider/provider.dart';
import 'package:tpns_flutter_plugin/tpns_flutter_plugin.dart';

import '../app.dart';
import '../models/set_xuan_tai_model.dart';
import '../utils/screen_util.dart';

class UserModel with ChangeNotifier {
  String _registrationId; //极光推送registrationId
  // String token; //信鸽推送token

  // String tokenLoginOut; //信鸽推送token+前缀
  List<PullMarketingByUidSunModel> pullMarketingByUidSunModel;
  // bool accountLogin = false;

  List<Setmeal> justSelData = [];
  bool downLoading = false;

  // User get user => _user;
  User get user {
    User _user;
    if (App.sp.containsKey('user')) {
      String s = App.sp.getString('user');
      _user = User.fromJson(json.decode(s));
    }
    return _user;
  }

  set registrationId(String registrationId) => _registrationId = registrationId;

  String get registrationId => _registrationId;

  // String get token => _token;

  // String get tokenLoginOut => _tokenLoginOut;

  // set token(String value) {
  //   _token = value;
  // }

  // set tokenLoginOut(String value) {
  //   tokenLoginOut = value;
  // }

  /// 初始化 User
  // void initUser() {
  //   if (App.sp.containsKey('user')) {
  //     String s = App.sp.getString('user');
  //     _user = User.fromJson(json.decode(s));
  //   }
  // }

  /// 登录
  Future<String> login(BuildContext context, Map<String, String> params,
      {bool acclogin = false}) async {
    BaseResp<List> baseResp = await DioUtil()
        .request<List>(context, Method.get, HttpUrl.app_user_login,
            data: params)
        .catchError((error) {
      print(error.toString());
    });
    if (baseResp.code != Constant.status_success) {
      Utils.showToast('用户名密码错误,请重新输入');

      return '';
      // return baseResp.msg ?? '用户名密码错误,请重新输入';
    } else {
      if (acclogin) {
        App.sp.setBool("accountLogin", true);
      } else {
        App.sp.setBool("accountLogin", false);
      }
      Map<String, dynamic> seller = baseResp.data[0]["seller"];
      Map<String, dynamic> user = baseResp.data[0]["user"];
      Map<String, dynamic> userMap = {
        "openid": user['id'],
        "account": user['account'],
        "role_name": user['role_name'],
        "sellerid": seller['id'],
        "sellerimage": seller['seller_image'],
        "sellercode": params['seller_code'],
        "sellername": seller['sellername'],
        "sellerphone": seller['seller_tel'],
        "sellerAddr": '',
        "scatter": 0,
        "room": 0,
        "cassette": 0,
        "morning": "",
        "noon": "",
        "night": "",
        'userphone': user['phone'],
        'token': baseResp.data[0]["token"]['token'],
        'nickname': user['nick_name'],
        'edate': seller['edate']
      };
      await saveUserInfo(User.fromJson(userMap));

      return getSellerInfo(
          context,
          {"seller_id": seller['id'], "seller_openid": seller['openid']},
          userMap);
    }
  }

//  获取推送失败的营销消息
  Future pullMarketingByUid(BuildContext context,
      {bool showLoading = false}) async {
    Map<String, String> params = {
      "uid": Provider.of<UserModel>(context, listen: false).user.openid,
    };
    BaseResp<dynamic> baseResp = await DioUtil()
        .request<dynamic>(context, Method.get, HttpUrl.pull_marketing_by_uid,
            data: params, showLoading: showLoading)
        .catchError((error) {
      print(error.toString());
      if (error is MyError) {}
    });
    if (baseResp != null && baseResp.code == Constant.status_success) {
      pullMarketingByUidSunModel =
          PullMarketingByUidModel.fromJson(baseResp.responseData).data;
      if (pullMarketingByUidSunModel != null &&
          pullMarketingByUidSunModel.length > 0) {
        String id = '';
        for (PullMarketingByUidSunModel item in pullMarketingByUidSunModel) {
          id += '${item.id},';
        }
        if (id.length > 0) {
          if (id.endsWith(',')) {
            id = id.substring(0, id.length - 1);
          }
        }
        print(id);

        setPullMarketingByid(context, id);
      }
    } else {
      if (baseResp != null) {
        Utils.showToast(baseResp.msg ?? "");
      }
    }
  }

  //  修改拉取后消息的状态
  Future<bool> setPullMarketingByid(BuildContext context, String id,
      {bool showLoading = false}) async {
    Map<String, String> params = {
      "id": id,
    };
    BaseResp<dynamic> baseResp = await DioUtil()
        .request<dynamic>(context, Method.get, HttpUrl.set_pull_marketing_by_id,
            data: params, showLoading: showLoading)
        .catchError((error) {
      print(error.toString());
      if (error is MyError) {}
    });
    if (baseResp != null && baseResp.code == Constant.status_success) {
      if (baseResp.responseData['data'] != null &&
          baseResp.responseData['data'] == 1) {
        return true;
      }
      return false;
    } else {
      if (baseResp != null) {
        Utils.showToast(baseResp.msg ?? "");
      }
      return false;
    }
  }

  ///获取商家信息
  Future<String> getSellerInfo(BuildContext context, Map<String, String> params,
      Map<String, dynamic> userMap) async {
    BaseResp<Map<String, dynamic>> baseResp = await DioUtil()
        .request<Map<String, dynamic>>(context, Method.get, HttpUrl.sellerinfo,
            data: params)
        .catchError((error) {
      print(error.toString());
    });
    if (baseResp.code != Constant.status_success) {
      return baseResp.msg ?? '登录失败,请检查账号密码';
    } else {
      Map<String, dynamic> seller = baseResp.data['seller'];
      Map<String, dynamic> daily = baseResp.data["daily"];
      Map<String, dynamic> user = Map.of(userMap);
      user['sellerAddr'] = seller['real_address'] ?? seller['map_address'];
      user['scatter'] = baseResp.data['scatter'];
      user['room'] = baseResp.data['room'];
      user['cassette'] = baseResp.data['cassette'];
      user['morning'] = daily['morning'];
      user['noon'] = daily['noon'];
      user['night'] = daily['night'];

      await saveUserInfo(User.fromJson(user));
      App.sp.setBool("isLogin", true);
      App.sp.setString("is_call_tel", seller['is_call_tel'].toString());
      pullMarketingByUid(context);
      NavigatorUtil.goHomePage(context);
      return null;
    }
  }

  //   //判断微信登录成功APP用户是否绑定微信小程序,绑定返回绑定的微信小程序openid,否则返回null
  // Future<String> getMiniProgramOpenid(BuildContext context, Map req) async {
  //   try {
  //     BaseResp<dynamic> baseResp = await DioUtil().request<dynamic>(
  //         context, Method.get, HttpUrl.get_mini_openid,
  //         data: req, showLoading: true);
  //     if (baseResp == null) return null;
  //     if (baseResp.code == Constant.status_success) {
  //       App.sp.setString("mini-openid", baseResp.data?.toString() ?? "");
  //       App.sp.setString("openid", baseResp.data?.toString() ?? "");
  //       // initPlatformState(context); //注册信鸽推送,绑定openid,token关系
  //       return baseResp.data?.toString();
  //     } else {
  //       App.sp.setString("mini-openid", "");
  //     }
  //   } catch (e) {
  //     print(e);
  //     Loading.hideLoading(context);
  //   }

  //   return null;
  // }

  ///初始化推送token
  userTokenInit(BuildContext context, Map<String, String> params) async {
    BaseResp<dynamic> baseResp = await DioUtil()
        .request<dynamic>(context, Method.get, HttpUrl.user_token_init,
            showLoading: false, data: params)
        .catchError((error) {
      print(error.toString());
    });
    if (baseResp != null && baseResp.code == Constant.status_success) {}
  }

  //退出登录弹框
  showLoginOutDialog(BuildContext pageContext) {
    showDialog(
        context: pageContext,
        builder: (context) {
          return Center(
            child: Card(
                margin: EdgeInsets.symmetric(horizontal: w(30)),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(
                        Radius.circular(ScreenUtil().setWidth(30)))), //设置圆角
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    VEmptyView(88),
                    Center(
                      child: Text(
                        "确定要退出登录吗?",
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(36),
                            color: MyColours.color_353535),
                      ),
                    ),
                    VEmptyView(66),
                    MyDivider(double.infinity, ScreenUtil().setWidth(1)),
                    Container(
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: GestureDetector(
                              onTap: () {
                                Navigator.of(context).pop();
                              },
                              child: Container(
                                  decoration: BoxDecoration(
                                      color: MyColours.color_ffffff,
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(
                                              ScreenUtil().setWidth(30)))),
                                  height: ScreenUtil().setWidth(94),
                                  alignment: Alignment.center,
                                  child: Text(
                                    "取消",
                                    style: TextStyle(
                                        fontSize: ScreenUtil().setSp(34),
                                        color: MyColours.color_777777),
                                    textAlign: TextAlign.center,
                                  )),
                            ),
                          ),
                          MyDivider(ScreenUtil().setWidth(1),
                              ScreenUtil().setWidth(94)),
                          Expanded(
                            child: GestureDetector(
                              onTap: () {
                                Navigator.of(context).pop();
                                loginOut(pageContext, {
                                  "seller_code": user.sellercode,
                                  "account": user.account
                                });
                              },
                              child: Container(
                                decoration: BoxDecoration(
                                    color: MyColours.color_ffffff,
                                    borderRadius: BorderRadius.all(
                                        Radius.circular(
                                            ScreenUtil().setWidth(30)))),
                                height: ScreenUtil().setWidth(94),
                                alignment: Alignment.center,
                                child: Text(
                                  "确定",
                                  style: TextStyle(
                                      fontSize: ScreenUtil().setSp(34),
                                      color: MyColours.color_2bb5b7),
                                  textAlign: TextAlign.center,
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                    )
                  ],
                )),
          );
        });
  }

  ///退出登录
  loginOut(BuildContext context, Map<String, String> params) async {
    params['token'] =
        Provider.of<UserModel>(context, listen: false).user.tokenLoginOut;
    print(params);
    BaseResp<int> baseResp = await DioUtil()
        .request<int>(context, Method.get, HttpUrl.login_out, data: params)
        .catchError((error) {
      print(error.toString());
    });
    if (baseResp.code != Constant.status_success) {
      Utils.showToast(baseResp.msg ?? "退出登录失败,请稍后重试");
    } else {
      if (Platform.isIOS) {
        XgFlutterPlugin().stopXg();
      }
      if (App.sp.containsKey('unionid')) {
        //微信登陆的时候,退出清空数据
        App.sp.remove('openid');
        App.sp.remove("unionid");
      }
      if (App.sp.containsKey('table_list')) {
        //退出清空桌位数据
        App.sp.remove('table_list');
      }
      if (App.sp.containsKey('specid')) {
        //退出清空销售计价
        App.sp.remove('specid');
        App.sp.remove('specs');
      }

      if (App.sp.containsKey('sellerEdate')) {
        //退出清空店铺过期数据缓存
        App.sp.remove('sellerEdate');
      }
      if (App.sp.containsKey('sellerEdateModule')) {
        //退出清空模块过期数据缓存
        App.sp.remove('sellerEdateModule');
      }

      App.sp.setBool("isLogin", false);
      // XgFlutterPlugin().stopXg();
      NavigatorUtil.goLoginPage(context);
    }
  }

  ///切换店铺时的退出登录
  Future<bool> loginOutOnly(
      BuildContext context, Map<String, String> params) async {
    params['token'] =
        Provider.of<UserModel>(context, listen: false).user.tokenLoginOut;
    print(params);
    BaseResp<int> baseResp = await DioUtil()
        .request<int>(context, Method.get, HttpUrl.login_out, data: params)
        .catchError((error) {
      print(error.toString());
    });
    if (baseResp.code != Constant.status_success) {
      Utils.showToast(baseResp.msg ?? "切换店铺失败,请稍后重试");
      return false;
    } else {
      // XgFlutterPlugin().stopXg();
      return true;
    }
  }

  /// 保存用户信息到 sp
  saveUserInfo(User user) {
    // _user = user;
    // notifyListeners();
    App.sp.setString('user', json.encode(user.toJson()));
  }
}