import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:liftmanager/internal/account/model/user_info_entity.dart';
import 'package:liftmanager/internal/account/provider/user_provider.dart';
import 'package:liftmanager/internal/wode/wode_router.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/image_utils.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/click_item.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/widgets/my_button.dart';
import 'package:provider/provider.dart';
import 'package:liftmanager/widgets/bbs_content.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/utils/utils.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/services.dart';
import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:liftmanager/utils/fast_notification.dart';
import 'dart:async';
import 'package:liftmanager/utils/theme_utils.dart';

class WodePage extends StatefulWidget {
  //1用户 2专家
  String type = "2";

  @override
  State<StatefulWidget> createState() {
    return WodePageState();
  }
}

class WodePageState extends State<WodePage> with AutomaticKeepAliveClientMixin {
  UserProvider provider = UserProvider();

  @override
  void initState() {
    super.initState();
    getUserInfo();
    getCoupon();

    FastNotification.addListener("initUserMoney", (initThisUserMoney) {
      if (mounted) {
        getCoupon();
        setState(() {
          
        });
      }
    });
    FastNotification.addListener("initUserInfomation", (initThisUserInfomation) {
      if (mounted) {
        getUserInfo();
        setState(() {
          
        });
      }
    });
  }
  String indexNow;
  final _cancelController = TextEditingController(text: "取消");
  Map<String, dynamic> detailOj = {
    "couponNum": 0,
    "balance": 0.0,
    "hongBaoNum": 0,
    "memberDays": "",
  };
  int isVip = 1;

  ///获取用户信息
  void getUserInfo() {
    ApiService(context: context).userInfo(
      onSuccess: (data) {
        setUser(data);
        print(data.showWhichName);
        indexNow = data.showWhichName.toString();
      },
      onError: (code, msg) {},
    );
  }

  Future scan() async {
    try {
      // 此处为扫码结果，barcode为二维码的内容
      String barcode = await BarcodeScanner.scan();
      print(barcode);
      // return;
      // print('扫码结果: ' + jsonDecode(barcode)["url"]);
      Uri u = Uri.parse(barcode);
      String id = u.queryParameters['id'];
      print('扫码结果: ' + id);
      // print('扫码结果: ' + jsonDecode(barcode)["userId"].toString());

      NewApiService().getUserRebates(id,
          onSuccess: (res) {
            toasts("你已成功接受${res!=null?res.toString():''}的邀请，立即成为会员！",timeInSecForIos:2);
            // toasts("您已成为${res!=null?res.toString():''}的下级用户");
        NavigatorUtils.push(context, "${WodeRouter.vip}?id=");
      }, onError: (code, msg) {
        toasts(msg);
      });
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.CameraAccessDenied) {
        // 未授予APP相机权限
        print('未授予APP相机权限');
      } else {
        // 扫码错误
        print('扫码错误: $e');
      }
    } on FormatException {
      // 进入扫码页面后未扫码就返回
      print('进入扫码页面后未扫码就返回');
    } catch (e) {
      // 扫码错误
      print('扫码错误: $e');
    }
  }

  Future getCoupon() async {
    await NewApiService().getUserCoupons(onSuccess: (res) {
      if (res != null) {
        detailOj["couponNum"] = res["couponNum"];
        detailOj["balance"] = res["balance"];
        detailOj["hongBaoNum"] = res["hongBaoNum"];
        detailOj["memberDays"] = res["memberDays"];
        isVip = res["isVip"];
        FlutterStars.SpUtil.putInt('isVip', isVip);
        
        setState(() {});

        print(6666544);
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  void setUser(UserInfoEntity user) {
    provider.setUser(user);
  }

  ///选择图片
  void selectPicker() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return SimpleDialog(
          title: Text("修改头像"),
          children: ["拍照", '从手机相册选择'].map((String value) {
            print("$value");
            return SimpleDialogOption(
              child: Text(
                "${value}",
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
              ),
              onPressed: () {
                _getImage(value == '拍照' ? 1 : 0);
                Navigator.of(context).pop();
              },
            );
          }).toList(),
        );
      },
    );
  }

  void _getImage(int key) async {
    try {
      var _imageFile = await ImagePicker.pickImage(
          source: key == 1 ? ImageSource.camera : ImageSource.gallery,
          maxWidth: 800,
          imageQuality: 95);
      if (_imageFile != null) {
        updateAvatar(_imageFile);
        setState(() {});
      }
    } catch (e) {
      toasts("没有权限，无法打开相册！");
    }
  }

  void updateAvatar(File imageFile) {
    List<File> list = [imageFile];
    ApiService(context: context).uploadMore(list, onSuccess: (imgs) {
      ApiService(context: context).modifyAvatar(imgs[0], onSuccess: (res) {
        if (res != null) {
          getUserInfo();
        }
      }, onError: (code, msg) {
        toasts(msg);
      });
    });
  }

  void _updateUserInfo(value) {
    ApiService(context: context).modifyName(value, onSuccess: (res) {
      if (res != null) {
        getUserInfo();
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  @override
  void dispose() {
    // provider.dispose();
    super.dispose();
  }

  static const OrderTypeList = [
    {
      "title": "待付款",
      "img": "wode/order_1",
    },
    {
      "title": "待确认",
      "img": "wode/order_3",
    },
    {
      "title": "待评价",
      "img": "wode/order_2",
    },
    {
      "title": "申诉",
      "img": "wode/order_4",
    },
  ];

  @override
  Widget build(BuildContext context) {
    return
        // Center(child:new Text("个人中心"));
        ChangeNotifierProvider<UserProvider>(
      create: (_) => provider,
      child: Scaffold(
        appBar: MyAppBar(
          // centerTitle: "个人中心",
          isBack: false,
          actions: <Widget>[
            IconButton(
              onPressed: () {
                NavigatorUtils.push(context, "${WodeRouter.settingPage}?indexNow=$indexNow");
              },
              icon: LoadAssetImage(
                "icon_setting",
                key: const Key('add'),
                width: ScreenUtil().setWidth(24),
                height: ScreenUtil().setWidth(24),
                color: Colors.white,
              ),
            )
          ],
        ),
        body: 
        RefreshIndicator(
        onRefresh:()async{
            setState(() {
              getUserInfo();
              getCoupon();
            });
          },
          child: Consumer<UserProvider>(
          builder: (_, provider, __) {
            return ListView(
              padding: EdgeInsets.all(0.0),
              children: <Widget>[
                Container(
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                      colors: [Color(0xFF00D9FF), Color(0xFF0287FF)],
                    ),
                  ),
                  height: ScreenUtil().setWidth(130),
                  child: Column(
                    children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          GestureDetector(
                            onTap: () {
                              NavigatorUtils.push(
                                  context, WodeRouter.personalPage);
                            },
                            child: Container(
                              padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(25),
                                bottom: ScreenUtil().setWidth(25),
                              ),
                              child: Row(
                                children: <Widget>[
                                  Container(
                                    padding: EdgeInsets.only(
                                      right: ScreenUtil().setWidth(10),
                                    ),
                                    child: 
                                    // CircleAvatar(
                                    //   radius: 24,
                                    //   backgroundColor: Colors.transparent,
                                    //   backgroundImage:
                                    //       ImageUtils.getImageProvider(
                                    //           provider.user?.avatarUrl),
                                    // ),
                                    ClipRRect(
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            ScreenUtil()
                                                                .setWidth(25)),
                                                    child: Container(
                                                      child: LoadNetworkImage(
                                                        provider.user?.avatarUrl,
                                                        // fit: BoxFit.fitWidth,
                                                        width: ScreenUtil()
                                                            .setWidth(50),
                                                        height: ScreenUtil()
                                                            .setWidth(50),
                                                      ),
                                                    ))
                                  ),
                                  Column(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Container(
                                        child: Text(
                                          provider.user?.showWhichName==1?(provider.user?.nickName ?? ""):(provider.user?.userName ?? ""),
                                          textAlign: TextAlign.left,
                                          style: TextStyle(
                                            fontSize: ScreenUtil().setSp(18),
                                            color: Color(0xffffffff),
                                          ),
                                        ),
                                      ),
                                      SizedBox(height: 3),
                                      Row(
                                        children: <Widget>[
                                          GestureDetector(
                                            onTap: () {
                                              // print(provider.user.userLevel);
                                              NavigatorUtils.push(context, "${WodeRouter.vip}?id=");
                                            },
                                            child: Container(
                                              padding: EdgeInsets.only(
                                                left: 6,
                                                right: 6,
                                                top: 2,
                                                bottom: 2,
                                              ),
                                              decoration: BoxDecoration(
                                                borderRadius:
                                                    BorderRadius.circular(10.0),
                                                color: Colors.white,
                                              ),
                                              child: Row(
                                                children: <Widget>[
                                                  Container(
                                                    child: LoadAssetImage(
                                                      // image: AssetImage(i['img']),
                                                      'wode/zuan',
                                                      height: ScreenUtil()
                                                          .setWidth(11),
                                                      width: ScreenUtil()
                                                          .setWidth(12),
                                                      fit: BoxFit.cover,
                                                      // alignment: Alignment.centerLeft,
                                                    ),
                                                  ),
                                                  SizedBox(width: 3),
                                                  Text(
                                                    provider.user
                                                            ?.userLevelName!=null&&provider.user
                                                            ?.userLevelName!='' ?provider.user
                                                            ?.userLevelName:
                                                        "成为会员",
                                                    textAlign: TextAlign.left,
                                                    style: TextStyle(
                                                      fontSize: ScreenUtil()
                                                          .setSp(11),
                                                      color: Color(0xff0288FF),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                          SizedBox(
                                            width: 10,
                                          ),
                                          Container(
                                            child: Text(
                                              detailOj["memberDays"] ?? "",
                                              textAlign: TextAlign.left,
                                              style: TextStyle(
                                                fontSize:
                                                    ScreenUtil().setSp(14),
                                                color: Color(0xffffffff),
                                              ),
                                            ),
                                          )
                                        ],
                                      )
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                      Container(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: <Widget>[
                            GestureDetector(
                              child: Container(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: <Widget>[
                                    Text(
                                      detailOj["balance"] != null
                                          ? detailOj["balance"].toString()
                                          : "0.0",
                                      textAlign: TextAlign.left,
                                      style: TextStyle(
                                        fontSize: ScreenUtil().setSp(18),
                                        color: Color(0xffffffff),
                                      ),
                                    ),
                                    Text(
                                      '我的钱包',
                                      textAlign: TextAlign.left,
                                      style: TextStyle(
                                        fontSize: ScreenUtil().setSp(15),
                                        color: Color(0xffffffff),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              onTap: () {
                                NavigatorUtils.push(
                                    context, WodeRouter.walletPage);
                              },
                            ),
                            GestureDetector(
                              child: Container(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: <Widget>[
                                    Text(
                                      detailOj["couponNum"] != null
                                          ? detailOj["couponNum"].toString()
                                          : "0",
                                      textAlign: TextAlign.left,
                                      style: TextStyle(
                                        fontSize: ScreenUtil().setSp(18),
                                        color: Color(0xffffffff),
                                      ),
                                    ),
                                    Text(
                                      '优惠券(张)',
                                      textAlign: TextAlign.left,
                                      style: TextStyle(
                                        fontSize: ScreenUtil().setSp(15),
                                        color: Color(0xffffffff),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              onTap: () {
                                NavigatorUtils.push(
                                    context, WodeRouter.couponPage);
                              },
                            ),
                            GestureDetector(
                              child: Container(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: <Widget>[
                                    Text(
                                      detailOj["hongBaoNum"] != null
                                          ? detailOj["hongBaoNum"].toString()
                                          : "0",
                                      textAlign: TextAlign.left,
                                      style: TextStyle(
                                        fontSize: ScreenUtil().setSp(18),
                                        color: Color(0xffffffff),
                                      ),
                                    ),
                                    Text(
                                      '红包(张)',
                                      textAlign: TextAlign.left,
                                      style: TextStyle(
                                        fontSize: ScreenUtil().setSp(15),
                                        color: Color(0xffffffff),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              onTap: () {
                                NavigatorUtils.push(
                                    context, WodeRouter.redbaoPage);
                              },
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                LableTitle(
                  title: "我的订单",
                  hasArrow: true,
                  isMore: false,
                  userTap: () {
                    NavigatorUtils.push(
                        context, "${WodeRouter.orderPage}?checkType=0");
                  },
                ),
                Container(
                  padding: EdgeInsets.only(
                    bottom: ScreenUtil().setWidth(5),
                    top: ScreenUtil().setWidth(5),
                  ),
                  child: OrderType(initList: OrderTypeList),
                ),
                Container(
                  color: ThemeUtils.getDialogTextFieldColor(context),
                  height: ScreenUtil().setWidth(5),
                ),
                Utils.getAuthByRouter("master_order", false)
                    ? ClickItem(
                        title: "我的接单",
                        hasPic: "wode/user_order",
                        content: "",
                        onTap: () {
                          NavigatorUtils.push(context,
                              "${WodeRouter.orderPageMaster}?checkType=0");
                        },
                      )
                    : Container(),
                Utils.getAuthByRouter("master_order", false)
                    ? Container(
                        color: ThemeUtils.getDialogTextFieldColor(context),
                        height: ScreenUtil().setWidth(5),
                      )
                    : Container(),
                ClickItem(
                  title: "我的视频",
                  hasPic: "wode/shipin",
                  content: "",
                  onTap: () {
                    NavigatorUtils.push(context, WodeRouter.myVideo);
                  },
                ),
                ClickItem(
                  title: "我的收藏",
                  hasPic: "wode/shoucang",
                  content: "",
                  onTap: () {
                    NavigatorUtils.push(context, WodeRouter.collectPage);
                  },
                ),
                ClickItem(
                  title: "消息中心",
                  hasPic: "wode/xiaoxi",
                  content: "",
                  onTap: () {
                    NavigatorUtils.push(context, WodeRouter.noticeList);
                  },
                ),
                ClickItem(
                  title: "发票中心",
                  hasPic: "wode/piao",
                  content: "",
                  onTap: () {
                    NavigatorUtils.push(context, WodeRouter.piaoCenter);
                  },
                ),
                ClickItem(
                  title: "扫一扫",
                  hasPic: "wode/qr",
                  content: "",
                  onTap: () {
                    scan();
                  },
                ),
                Utils.getAuthByRouter('punishment_record',false)?
                ClickItem(
                  title: "违规记录",
                  hasPic: "wode/wr",
                  content: "",
                  onTap: () {
                    NavigatorUtils.push(context, WodeRouter.errorRecordList);
                  },
                )
                :Container(child: null,),
              ],
            );
          },
        ),
        )
        ,
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class OrderType extends StatelessWidget {
  OrderType({Key key, this.initList}) : super(key: key);

  List<dynamic> initList;
  List<Widget> brandList(context) => initList.asMap().keys.map(
        (item) {
          double width = MediaQuery.of(context).size.width;

          return Container(
            // color:Colors.yellow,
            width: width / 4,
            child: FlatButton(
              padding: EdgeInsets.all(0),
              highlightColor: Colors.white,
              splashColor: Colors.white,
              child: Container(
                // width: 90,
                height: ScreenUtil().setWidth(80),
                // color: Colors.red,
                padding: EdgeInsets.only(
                    left: ScreenUtil().setWidth(10),
                    right: ScreenUtil().setWidth(10),
                    top: ScreenUtil().setWidth(10)),
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        // height: 70,
                        // color: Colors.red,
                        child: LoadAssetImage(
                          // image: AssetImage(i['img']),
                          initList[item]['img'],
                          width: ScreenUtil().setWidth(50),
                          height: ScreenUtil().setWidth(30),
                          // alignment: Alignment.centerLeft,
                        ),
                      ),
                      SizedBox(height: ScreenUtil().setWidth(10)),
                      Container(
                        child: Text(
                          initList[item]["title"],
                          style: TextStyle(
                              color: Color(0xff666666),
                              fontSize: ScreenUtil().setSp(15)),
                          textAlign: TextAlign.start,
                        ),
                      ),
                    ]),
              ),
              onPressed: () {
                int nums = item + 1;
                String index = nums.toString();
                NavigatorUtils.push(
                    context, "${WodeRouter.orderPage}?checkType=$index");
              },
            ),
          );
        },
      ).toList();

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(top: ScreenUtil().setWidth(5)),
      child: Wrap(
        // spacing: 26,
        alignment: WrapAlignment.spaceBetween,
        crossAxisAlignment: WrapCrossAlignment.center,
        children: brandList(context),
      ),
    );
  }
}
