import 'dart:convert';
import 'dart:math';

import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/common/common.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/res/colors.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/bbs_content.dart';
import 'package:liftmanager/widgets/click_item.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/widgets/text_field_item.dart';
import 'package:provider/provider.dart';

class Kaipiao extends StatefulWidget {
  Kaipiao(this.ids, this.price);

  final String ids;
  final String price;
  @override
  State<StatefulWidget> createState() {
    return KaipiaoState();
  }
}

class KaipiaoState extends State<Kaipiao> with AutomaticKeepAliveClientMixin {
  UserProvider provider = UserProvider();
  FocusNode blankNode = FocusNode();
  /**
   * 发票类型
   */
  bool isTi = true;
  int indexNow = 2;
  int piaoType = 1;
  String checkFalse = "tab_first/check_false";
  String checkTrue = "tab_first/check_true";
  String desc = "普通发票为电子发票，可支持报销入账";
  int piaotouId;
  dynamic touObj = {
    "piaotouStr": "请选择发票抬头",
    "enterpriseNumber": "--",
    "gmfDz": "--",
    "gmfDh": "--",
    "gmfYh": "--",
    "gmfZh": "--",
  };

  var piaoObj = {
    "receiveTicket": "请输入",
    "receiveMebile": "请输入",
    "receiveAddress": "请输入",
    "gmfZh": "请输入",
  };

  GlobalKey _formKey = new GlobalKey<FormState>();

  TextEditingController _receiveTicketController = new TextEditingController();
  TextEditingController _receiveMebileController = new TextEditingController();
  TextEditingController _receiveAddressController = new TextEditingController();

  TextEditingController _emailController = new TextEditingController();
  String touChiose = "";
  List<String> touListChiose = ['tou1', 'tou2'];
  @override
  void initState() {
    // TODO: implement initState

    super.initState();

    getList(2);

    FastNotification.addListener("piaoTou", (piaoTouObj) {
      print(piaoTouObj);
      print(333);
      setState(() {
        touObj["piaotouStr"] = piaoTouObj.name;
        touObj["enterpriseNumber"] = piaoTouObj.enterpriseNumber;
        touObj["gmfDz"] = piaoTouObj.gmfDz;
        touObj["gmfDh"] = piaoTouObj.gmfDh;
        touObj["gmfYh"] = piaoTouObj.gmfYh;
        touObj["gmfZh"] = piaoTouObj.gmfZh;
        piaotouId = piaoTouObj.id;
      });
    });
  }

  Future getList(type) async {
    await NewApiService().getPiaoTouListPage(1, 10, null, 1, onSuccess: (res) {
      print(JsonEncoder().convert(res.records));
      if (res.records.length > 0 && res.records[0].type == type) {
        touObj["piaotouStr"] = res.records[0].name;
        touObj["enterpriseNumber"] = res.records[0].enterpriseNumber;
        touObj["gmfDz"] = res.records[0].gmfDz;
        touObj["gmfDh"] = res.records[0].gmfDh;
        touObj["gmfYh"] = res.records[0].gmfYh;
        touObj["gmfZh"] = res.records[0].gmfZh;
        piaotouId = res.records[0].id;
      } else {
        touObj = {
          "piaotouStr": "请选择发票抬头",
          "enterpriseNumber": "--",
          "gmfDz": "--",
          "gmfDh": "--",
          "gmfYh": "--",
          "gmfZh": "--",
        };
      }
      print(12345689);
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  randomInt(int min, int max) {
    return new Random().nextInt(max) % (max - min + 1) + min;
  }

  void applyInvoice() {
    if ((_formKey.currentState as FormState).validate()) {
      List<String> ids = widget.ids.split(',');
      List<dynamic> invoiceItem = [];
      for (var i = 0; i < ids.length; i++) {
        if (ids[i] != null && ids[i] != "") {
          invoiceItem.add({"id": int.parse(ids[i])});
        }
      }

      dynamic invoiceInfo = {
        "type": indexNow == 1 ? 1 : 2,
        "invoiceType": piaoType == 1 ? 1 : 2,
        "gmfMc": "咨询服务费",
        // "gmfNsrsbm": _taxidController.text,
        // "gmfYh": _bankController.text,
        // "gmfZh": _bankAccountController.text,
        // "gmfDz": _addressController.text,
        // "gmfDh": _telController.text,
        "email": _emailController.text,
        "hjje": double.parse(widget.price),
        "invoiceItem": invoiceItem,
        "userId": int.parse(FlutterStars.SpUtil.getString(Constant.userId)),
        "userInvoiceId": piaotouId,
        "receiveTicket": _receiveTicketController.text,
        "receiveMebile": _receiveMebileController.text,
        "receiveAddress": _receiveAddressController.text,
      };
      NewApiService().applyInvoice(invoiceInfo, onSuccess: (res) {
        toasts("发票申请成功");
        isTi = true;
        // NavigatorUtils.goBackWithParams(context, true);
        String initThisStringPiao = randomInt(1111, 9999).toString() +
            DateTime.now().millisecondsSinceEpoch.toString();
        FastNotification.push("initThisPiao", initThisStringPiao);
        Navigator.pop(context);
        setState(() {});
      }, onError: (code, msg) {
        isTi = true;
        toasts(msg);
      });
    }
  }

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

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;

    titleWidget(title) {
      return Container(
          width: width,
          padding: EdgeInsets.only(
              // left: ScreenUtil().setWidth(15),
              right: ScreenUtil().setWidth(15),
              top: ScreenUtil().setWidth(10),
              bottom: ScreenUtil().setWidth(10)),
          color: Color(0xffF9F9F9),
          child: Row(
            children: [
              Container(
                height: 18,
                width: 2,
                color: Colours.blue_app_main,
              ),
              SizedBox(
                width: 13,
              ),
              Text(
                title,
                textAlign: TextAlign.left,
                style: TextStyle(
                  // fontSize:ScreenUtil().setSp(14),
                  color: Color(0xff333333),
                ),
              ),
            ],
          ));
    }

    return
        // Center(child:new Text("个人中心"));
        ChangeNotifierProvider<UserProvider>(
      create: (_) => provider,
      child: Scaffold(
        resizeToAvoidBottomPadding: false,
        appBar: MyAppBar(
          centerTitle: "开具发票",
        ),
        body: GestureDetector(
          onTap: () {
            // 点击空白页面关闭键盘
            FocusScope.of(context).requestFocus(blankNode);
          },
          child: Consumer<UserProvider>(
            builder: (_, provider, __) {
              return Stack(
                children: <Widget>[
                  ListView(
                    padding: EdgeInsets.all(0.0),
                    children: <Widget>[
                      Form(
                        key: _formKey,
                        child: Column(
                          children: <Widget>[
                            titleWidget('发票种类'),
                            Container(
                              padding: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(15),
                                  right: ScreenUtil().setWidth(5),
                                  top: ScreenUtil().setWidth(10),
                                  bottom: ScreenUtil().setWidth(10)),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Row(
                                        children: <Widget>[
                                          GestureDetector(
                                              onTap: () {
                                                setState(() {
                                                  desc = "普通发票为电子发票，可支持报销入账";
                                                  piaoType = 1;
                                                  piaotouId = null;
                                                  // touObj = {
                                                  //   "piaotouStr": "请选择发票抬头",
                                                  //   "enterpriseNumber": "--",
                                                  //   "gmfDz": "--",
                                                  //   "gmfDh": "--",
                                                  //   "gmfYh": "--",
                                                  //   "gmfZh": "--",
                                                  // };
                                                  getList(2);
                                                });
                                              },
                                              child: Container(
                                                padding: EdgeInsets.only(
                                                    left: ScreenUtil()
                                                        .setWidth(10),
                                                    right: ScreenUtil()
                                                        .setWidth(10),
                                                    top: 3,
                                                    bottom: 3),
                                                decoration: BoxDecoration(
                                                    border: Border.all(
                                                        width: 1,
                                                        color: piaoType == 1
                                                            ? Color(0xff1B87F6)
                                                            : Color(
                                                                0xffdddddd)),
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            5)),
                                                child: Text(
                                                  "电子发票",
                                                  textAlign: TextAlign.center,
                                                  style: TextStyle(
                                                    fontSize:
                                                        ScreenUtil().setSp(14),
                                                    color: piaoType == 1
                                                        ? Color(0xff1B87F6)
                                                        : Color(0xff666666),
                                                  ),
                                                ),
                                              )),
                                          SizedBox(
                                            width: 10,
                                          ),
                                          GestureDetector(
                                              onTap: () {
                                                setState(() {
                                                  desc =
                                                      "增值税发票为纸质发票，邮寄信息详见收票人信息";
                                                  piaoType = 2;
                                                  indexNow = 2;
                                                  piaotouId = null;
                                                  // touObj = {
                                                  //   "piaotouStr": "请选择发票抬头",
                                                  //   "enterpriseNumber": "--",
                                                  //   "gmfDz": "--",
                                                  //   "gmfDh": "--",
                                                  //   "gmfYh": "--",
                                                  //   "gmfZh": "--",
                                                  // };
                                                  getList(2);
                                                });
                                              },
                                              child: Container(
                                                padding: EdgeInsets.only(
                                                    left: ScreenUtil()
                                                        .setWidth(10),
                                                    right: ScreenUtil()
                                                        .setWidth(10),
                                                    top: 3,
                                                    bottom: 3),
                                                decoration: BoxDecoration(
                                                    border: Border.all(
                                                        width: 1,
                                                        color: piaoType == 2
                                                            ? Color(0xff1B87F6)
                                                            : Color(
                                                                0xffdddddd)),
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            5)),
                                                child: Text(
                                                  "专用发票",
                                                  textAlign: TextAlign.center,
                                                  style: TextStyle(
                                                    fontSize:
                                                        ScreenUtil().setSp(14),
                                                    color: piaoType == 2
                                                        ? Color(0xff1B87F6)
                                                        : Color(0xff666666),
                                                  ),
                                                ),
                                              )),
                                        ],
                                      ),
                                      SizedBox(height: 5),
                                      Text(
                                        "($desc)",
                                        textAlign: TextAlign.left,
                                        style: TextStyle(
                                          fontSize: ScreenUtil().setSp(12),
                                          color: Color(0xff999999),
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                            titleWidget('发票详情'),
                            piaoType != 2
                                ? Container(
                                    decoration: BoxDecoration(
                                      border: Border(
                                        bottom: BorderSide(
                                            width: 1, color: Color(0xfff5f5f5)),
                                      ),
                                    ),
                                    padding: EdgeInsets.only(
                                        left: ScreenUtil().setWidth(15),
                                        right: ScreenUtil().setWidth(15)),
                                    height: 50,
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: <Widget>[
                                        Text(
                                          "发票类型",
                                          style: TextStyle(
                                              // color:Color(0xff999999),
                                              // fontSize:ScreenUtil().setSp(14)
                                              ),
                                          textAlign: TextAlign.start,
                                        ),
                                        Row(
                                          children: <Widget>[
                                            GestureDetector(
                                              child: Container(
                                                // padding: EdgeInsets.only(top:10,left:5,right:5,bottom:10),
                                                child: Row(
                                                  children: <Widget>[
                                                    LoadAssetImage(
                                                      // image: AssetImage(i['img']),
                                                      indexNow == 2
                                                          ? checkTrue
                                                          : checkFalse,
                                                      width: ScreenUtil()
                                                          .setWidth(16),
                                                      height: ScreenUtil()
                                                          .setWidth(16),
                                                      // alignment: Alignment.centerLeft,
                                                    ),
                                                    Container(
                                                        width: 5, child: null),
                                                    Text(
                                                      "企业单位",
                                                      style: TextStyle(
                                                          // color:Color(0xff000000),
                                                          // fontSize:ScreenUtil().setSp(14)
                                                          ),
                                                      textAlign:
                                                          TextAlign.start,
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              onTap: () {
                                                setState(() {
                                                  indexNow = 2;
                                                  piaotouId = null;
                                                  // touObj = {
                                                  //   "piaotouStr": "请选择发票抬头",
                                                  //   "enterpriseNumber": "--",
                                                  //   "gmfDz": "--",
                                                  //   "gmfDh": "--",
                                                  //   "gmfYh": "--",
                                                  //   "gmfZh": "--",
                                                  // };
                                                  getList(2);
                                                });
                                                print(indexNow);
                                              },
                                            ),
                                            Container(width: 15, child: null),
                                            GestureDetector(
                                              child: Container(
                                                // padding: EdgeInsets.only(top:10,left:5,right:5,bottom:10),
                                                child: Row(
                                                  children: <Widget>[
                                                    LoadAssetImage(
                                                      // image: AssetImage(i['img']),
                                                      indexNow == 1
                                                          ? checkTrue
                                                          : checkFalse,
                                                      width: ScreenUtil()
                                                          .setWidth(16),
                                                      height: ScreenUtil()
                                                          .setWidth(16),
                                                      // alignment: Alignment.centerLeft,
                                                    ),
                                                    Container(
                                                        width: 5, child: null),
                                                    Text(
                                                      "个人",
                                                      style: TextStyle(
                                                          // color:Colors.black,
                                                          // fontSize:ScreenUtil().setSp(14)
                                                          ),
                                                      textAlign:
                                                          TextAlign.start,
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              onTap: () {
                                                setState(() {
                                                  indexNow = 1;
                                                  piaotouId = null;
                                                  // touObj = {
                                                  //   "piaotouStr": "请选择发票抬头",
                                                  //   "enterpriseNumber": "--",
                                                  //   "gmfDz": "--",
                                                  //   "gmfDh": "--",
                                                  //   "gmfYh": "--",
                                                  //   "gmfZh": "--",
                                                  // };
                                                  getList(1);
                                                });
                                                print(indexNow);
                                              },
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  )
                                : Container(child: null),
                            // TextFieldItem(
                            //   title: "发票抬头",
                            //   content: "",
                            //   controller: _nameController,
                            //   hintText: "请选择发票抬头",
                            //   onChanged: (res) {
                            //     //            setState(() {});
                            //   },
                            // ),
                            ClickItem(
                              title: "发票抬头",
                              content: touObj["piaotouStr"],
                              isMust: true,
                              onTap: () {
                                String type;
                                if (indexNow == 1) {
                                  type = "1";
                                } else {
                                  type = "2";
                                }
                                NavigatorUtils.push(context,
                                    "${WodeRouter.piaotou}?checkTou=checkTou&type=$type");
                              },
                            ),
                            indexNow == 2
                                ? ClickItem(
                                    title: "企业税号",
                                    content: touObj["enterpriseNumber"],
                                  )
                                : Container(child: null),
                            indexNow == 2
                                ? ClickItem(
                                    title: "注册地址",
                                    content: touObj["gmfDz"],
                                  )
                                : Container(child: null),
                            indexNow == 2
                                ? ClickItem(
                                    title: "注册电话",
                                    content: touObj["gmfDh"],
                                  )
                                : Container(child: null),
                            indexNow == 2
                                ? ClickItem(
                                    title: "开户银行",
                                    content: touObj["gmfYh"],
                                  )
                                : Container(child: null),
                            indexNow == 2
                                ? ClickItem(
                                    title: "银行账户",
                                    content: touObj["gmfZh"],
                                  )
                                : Container(child: null),

                            Heng(
                              left: "发票内容",
                              right: "咨询服务费",
                              leftColor: 0xff666666,
                              rightColor: 0xff000000,
                            ),
                            Heng(
                              left: "发票金额",
                              right:
                                  "${double.parse(widget.price).toStringAsFixed(2).toString()}元",
                              leftColor: 0xff999999,
                              rightColor: 0xff333333,
                            ),
                            piaoType != 2
                                ? Column(
                                    children: <Widget>[
                                      titleWidget('接收方式'),
                                      TextFieldItem(
                                        title: "电子邮箱",
                                        content: "",
                                        isMust: true,
                                        controller: _emailController,
                                        hintText: "请输入电子邮箱",
                                        onChanged: (res) {
                                          //            setState(() {});
                                        },
                                      ),
                                    ],
                                  )
                                : Container(child: null),
                            piaoType == 2
                                ? Column(
                                    children: <Widget>[
                                      titleWidget('收票人信息'),
                                      TextFieldItem(
                                        title: "收票人",
                                        isMust: true,
                                        content: "",
                                        controller: _receiveTicketController,
                                        hintText: "请输入收票人姓名",
                                        onChanged: (res) {},
                                      ),
                                      TextFieldItem(
                                        title: "收票人电话",
                                        isMust: true,
                                        content: "",
                                        controller: _receiveMebileController,
                                        hintText: "请输入收票人电话",
                                        keyboardType: TextInputType.phone,
                                        onChanged: (res) {},
                                      ),
                                      TextFieldItem(
                                        title: "收票人地址",
                                        isMust: true,
                                        content: "",
                                        controller: _receiveAddressController,
                                        hintText: "请输入收票人地址",
                                        onChanged: (res) {},
                                      ),
                                    ],
                                  )
                                : Container(child: null),
                            SizedBox(height: ScreenUtil().setWidth(80))
                          ],
                        ),
                      ),
                    ],
                  ),
                  Positioned(
                    bottom: 0,
                    left: 0,
                    child: Container(
                      width: width,
                      padding: EdgeInsets.only(
                          top: ScreenUtil().setWidth(15),
                          bottom: ScreenUtil().setWidth(15),
                          left: ScreenUtil().setWidth(25),
                          right: ScreenUtil().setWidth(25)),
                      color: ThemeUtils.getDialogTextFieldColor(context),
                      child: Container(
                        height: ScreenUtil().setWidth(44),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(
                                ScreenUtil().setWidth(22)),
                            color: Colours.blue_app_main),
                        child: FlatButton(
                          // padding: EdgeInsets.all(15.0),
                          child: Text("提交"),
                          textColor: Colors.white,
                          // textColor: Colors.white,
                          onPressed: () {
                            if (!isTi) {
                              toasts("提交中。。。");
                              return;
                            }
                            isTi = false;
                            // Navigator.pop(context);
                            print(_emailController.text);
                            print(555);
                            RegExp exp = RegExp(r'^1[34578]\d{9}$');
                            RegExp expEmail = RegExp(
                                r"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
                            if (piaotouId == null) {
                              toasts("请选择发票抬头");
                              return;
                            }
                            if (piaoType == 1 &&
                                (_emailController.text == null ||
                                    _emailController.text.trim() == '')) {
                              toasts("请输入电子邮箱");
                              return;
                            }
                            if (piaoType == 2 &&
                                (_receiveTicketController.text == null ||
                                    _receiveTicketController.text.trim() ==
                                        '')) {
                              toasts("请输入收票人");
                              return;
                            }
                            if (piaoType == 2 &&
                                (_receiveMebileController.text == null ||
                                    _receiveMebileController.text.trim() ==
                                        '')) {
                              toasts("请输入收票人电话");
                              return;
                            }
                            if (piaoType == 2 &&
                                (_receiveAddressController.text == null ||
                                    _receiveAddressController.text.trim() ==
                                        '')) {
                              toasts("请输入收票人地址");
                              return;
                            }
                            if (piaoType == 2 &&
                                !exp.hasMatch(_receiveMebileController.text)) {
                              toasts("请输入正确的收票人电话");
                              return;
                            }
                            if (piaoType == 1 &&
                                !expEmail.hasMatch(_emailController.text)) {
                              toasts("请输入正确的邮箱");
                              return;
                            }
                            applyInvoice();
                          },
                        ),
                      ),
                    ),
                  )
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
