import 'dart:math';

import 'package:flustars/flustars.dart' as flustars;
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/net/api_service.dart';
import 'package:liftmanager/res/resources.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/load_image.dart';
import 'package:liftmanager/widgets/text_field_item.dart';

class PiaotouEdit extends StatefulWidget {
  PiaotouEdit(this.type, this.id);

  final String type;
  final String id;
  @override
  State<StatefulWidget> createState() {
    return PiaotouEditState();
  }
}

class PiaotouEditState extends State<PiaotouEdit> {
  int indexNow = 2;
  String checkFalse = "tab_first/check_false";
  String checkTrue = "tab_first/check_true";
  String centerTitle;
  bool _hasData = false;

  final FocusNode blankNode = FocusNode();

  TextEditingController _nameController = new TextEditingController();
  TextEditingController _enterpriseNumberController =
      new TextEditingController();
  TextEditingController _gmfDzController = new TextEditingController();
  TextEditingController _gmfDhController = new TextEditingController();
  TextEditingController _gmfYhController = new TextEditingController();
  TextEditingController _gmfZhController = new TextEditingController();

  var piaoObj;

  @override
  void initState() {
    if (widget.type == "add") {
      centerTitle = "添加发票抬头";
    } else if (widget.type == "edit") {
      centerTitle = "编辑发票抬头";

      getTouDetail();
    }

    piaoObj = {
      "type": 2,
      "name": "",
      "enterpriseNumber": "",
      "gmfDz": "",
      "gmfDh": "",
      "gmfYh": "",
      "gmfZh": "",
      "isDefault": 0,
      "userId": int.parse(flustars.SpUtil.getString(Constant.userId))
    };

    super.initState();
  }

  Future getTouDetail() async {
    await NewApiService().getTouDetail(int.parse(widget.id), onSuccess: (res) {
      if (res != null) {
        _hasData = true;

        piaoObj["type"] = res.type;
        indexNow = piaoObj["type"];
        _nameController.text = res.name ?? "";
        _enterpriseNumberController.text = res.enterpriseNumber ?? "";
        _gmfDzController.text = res.gmfDz ?? "";
        _gmfDhController.text = res.gmfDh ?? "";
        _gmfYhController.text = res.gmfYh ?? "";
        _gmfZhController.text = res.gmfZh ?? "";
        piaoObj["isDefault"] = res.isDefault;
        // LogUtil.d(JsonEncoder(detailObj));
        // LogUtil.d(JsonEncoder().convert(detailObj));
        print(9999);
        setState(() {});
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future getTouDelete() async {
    await NewApiService().getTouDelete(int.parse(widget.id), onSuccess: (res) {
      toasts("删除成功");

      String initThisString = randomInt(1111, 9999).toString() +
          DateTime.now().millisecondsSinceEpoch.toString();
      FastNotification.push("initThis", initThisString);
      Navigator.of(context)..pop()..pop();
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

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

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: MyAppBar(
        centerTitle: centerTitle,
        actions: <Widget>[
          widget.type == "edit"
              ? FlatButton(
                  child: Text("删除"),
                  textColor: Colours.red,
                  highlightColor: Colors.transparent,
                  onPressed: () {
                    showAlert(
                        context,
                        "提示",
                        "确定要删除吗？",
                        "确定",
                        () {
                          Navigator.pop(context);
                          showLoading(context, "正在删除...");
                          getTouDelete();
                        },
                        txt2: "取消",
                        onPre2: () {
                          NavigatorUtils.goBack(context);
                        });
                  },
                )
              : Container(child: null)
        ],
      ),
      body: GestureDetector(
        onTap: () {
          // 点击空白页面关闭键盘
          FocusScope.of(context).requestFocus(blankNode);
        },
        child: Stack(children: <Widget>[
          Container(
              // padding: EdgeInsets.only(top:70),
              child: ListView(children: <Widget>[
            Container(
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(width: 1, color: Color(0xfff5f5f5)),
                  ),
                ),
                margin: EdgeInsets.only(
                    left: ScreenUtil().setWidth(15),
                    right: ScreenUtil().setWidth(15)),
                height: ScreenUtil().setWidth(60),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(
                        "发票类型",
                        style: TextStyle(
                            // color:Color(0xff000000),
                            // 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(20),
                                height: ScreenUtil().setWidth(20),
                                // 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;
                                _enterpriseNumberController.text = "";
                                _gmfDzController.text = "";
                                _gmfDhController.text = "";
                                _gmfYhController.text = "";
                                _gmfZhController.text = "";
                              });
                              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(20),
                                height: ScreenUtil().setWidth(20),
                                // 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;
                                _enterpriseNumberController.text = "";
                                _gmfDzController.text = "";
                                _gmfDhController.text = "";
                                _gmfYhController.text = "";
                                _gmfZhController.text = "";
                              });
                              print(indexNow);
                            },
                          ),
                        ],
                      ),
                    ])),
            TextFieldItem(
              title: "发票抬头",
              isMust: true,
              content: "",
              controller: _nameController,
              hintText: "请输入发票抬头",
              onChanged: (res) {},
            ),
            indexNow == 2
                ? TextFieldItem(
                    title: "企业税号",
                    isMust: true,
                    content: '',
                    controller: _enterpriseNumberController,
                    hintText: "请输入企业税号",
                    keyboardType: TextInputType.visiblePassword,
                    onChanged: (res) {},
                  )
                : Container(child: null),
            indexNow == 2
                ? TextFieldItem(
                    title: "注册地址",
                    isMust: true,
                    content: '',
                    controller: _gmfDzController,
                    hintText: "请输入注册地址",
                    onChanged: (res) {},
                  )
                : Container(child: null),
            indexNow == 2
                ? TextFieldItem(
                    title: "注册电话",
                    isMust: true,
                    content: '',
                    controller: _gmfDhController,
                    hintText: "请输入注册电话",
                    keyboardType: TextInputType.phone,
                    onChanged: (res) {},
                  )
                : Container(child: null),
            indexNow == 2
                ? TextFieldItem(
                    title: "开户银行",
                    isMust: true,
                    content: '',
                    controller: _gmfYhController,
                    hintText: "请输入开户银行",
                    onChanged: (res) {},
                  )
                : Container(child: null),
            indexNow == 2
                ? TextFieldItem(
                    title: "银行账号",
                    isMust: true,
                    content: '',
                    controller: _gmfZhController,
                    hintText: "银行账号",
                    keyboardType: TextInputType.number,
                    onChanged: (res) {},
                  )
                : Container(child: null),
            Container(
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(width: 1, color: Color(0xfff5f5f5)),
                  ),
                ),
                margin: EdgeInsets.only(
                    left: ScreenUtil().setWidth(15),
                    right: ScreenUtil().setWidth(15)),
                height: ScreenUtil().setWidth(60),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(
                        "是否默认",
                        style: TextStyle(
                            // color:Color(0xff000000),
                            // 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']),
                                piaoObj["isDefault"] == 0
                                    ? checkTrue
                                    : checkFalse,
                                width: ScreenUtil().setWidth(20),
                                height: ScreenUtil().setWidth(20),
                                // alignment: Alignment.centerLeft,
                              ),
                              Container(width: 5, child: null),
                              Text(
                                "否",
                                style: TextStyle(
                                    // color:Color(0xff000000),
                                    // fontSize:ScreenUtil().setSp(14)
                                    ),
                                textAlign: TextAlign.start,
                              ),
                            ])),
                            onTap: () {
                              setState(() {
                                piaoObj["isDefault"] = 0;
                              });
                              print(piaoObj["isDefault"]);
                            },
                          ),
                          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']),
                                piaoObj["isDefault"] == 1
                                    ? checkTrue
                                    : checkFalse,
                                width: ScreenUtil().setWidth(20),
                                height: ScreenUtil().setWidth(20),
                                // alignment: Alignment.centerLeft,
                              ),
                              Container(width: 5, child: null),
                              Text(
                                "是",
                                style: TextStyle(
                                    // color:Colors.black,
                                    // fontSize:ScreenUtil().setSp(14)
                                    ),
                                textAlign: TextAlign.start,
                              ),
                            ])),
                            onTap: () {
                              setState(() {
                                piaoObj["isDefault"] = 1;
                              });
                              print(piaoObj["isDefault"]);
                            },
                          ),
                        ],
                      ),
                    ])),
          ])),
          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: 44,
                  decoration: BoxDecoration(
                    color: Colours.blue_app_main,
                    borderRadius:
                        BorderRadius.circular(ScreenUtil().setWidth(22)),
                  ),
                  child: FlatButton(
                    // padding: EdgeInsets.all(15.0),
                    child: Text("保存"),
                    textColor: Colors.white,
                    // textColor: Colors.white,
                    onPressed: () {
                      piaoObj["type"] = indexNow;
                      RegExp exp = RegExp(r'^1[34578]\d{9}$');

                      piaoObj["name"] = _nameController.text ?? "";
                      piaoObj["enterpriseNumber"] =
                          _enterpriseNumberController.text ?? "";
                      piaoObj["gmfDz"] = _gmfDzController.text ?? "";
                      piaoObj["gmfDh"] = _gmfDhController.text ?? "";
                      piaoObj["gmfYh"] = _gmfYhController.text ?? "";
                      piaoObj["gmfZh"] = _gmfZhController.text ?? "";

                      if (piaoObj["name"] == null ||
                          piaoObj["name"].trim() == "") {
                        toasts("请输入发票抬头");
                        return;
                      }
                      if (indexNow == 2 &&
                          (piaoObj["enterpriseNumber"] == null ||
                              piaoObj["enterpriseNumber"].trim() == "")) {
                        toasts("请输入企业税号");
                        return;
                      }
                      if (indexNow == 2 &&
                          (piaoObj["gmfDz"] == null ||
                              piaoObj["gmfDz"].trim() == "")) {
                        toasts("请输入注册地址");
                        return;
                      }
                      if (indexNow == 2 &&
                          (piaoObj["gmfDh"] == null ||
                              piaoObj["gmfDh"].trim() == "")) {
                        toasts("请输入注册电话");
                        return;
                      }
                      if (indexNow == 2 &&
                          (piaoObj["gmfYh"] == null ||
                              piaoObj["gmfYh"].trim() == "")) {
                        toasts("请输入开户银行");
                        return;
                      }
                      if (indexNow == 2 &&
                          (piaoObj["gmfZh"] == null ||
                              piaoObj["gmfZh"].trim() == "")) {
                        toasts("请输入银行账号");
                        return;
                      }
                      if (indexNow == 2 && !exp.hasMatch(piaoObj["gmfDh"])) {
                        toasts("请输入正确的手机号");
                        return;
                      }
                      // addPiaoTouListPage
                      // Navigator.pop(context);
                      FocusScope.of(context).requestFocus(FocusNode());
                      showLoading(context, "正在保存...");

                      if (widget.type == "add") {
                        NewApiService().addPiaoTouListPage(piaoObj,
                            onSuccess: (res) {
                          dismissLoading(context);
                          toasts("保存成功");

                          String initThisString = randomInt(1111, 9999)
                                  .toString() +
                              DateTime.now().millisecondsSinceEpoch.toString();
                          FastNotification.push("initThis", initThisString);
                          Navigator.pop(context);
                          print(9999);
                        }, onError: (code, msg) {
                          dismissLoading(context);
                          toasts(msg);
                        });
                      } else if (widget.type == "edit") {
                        Map edit = {"id": widget.id};
                        edit.addAll(piaoObj);
                        print(edit);
                        print(868686);
                        NewApiService().editPiaoTouListPage(edit,
                            onSuccess: (res) {
                          dismissLoading(context);
                          toasts("保存成功");

                          String initThisString = randomInt(1111, 9999)
                                  .toString() +
                              DateTime.now().millisecondsSinceEpoch.toString();
                          FastNotification.push("initThis", initThisString);
                          Navigator.pop(context);
                          print(9999);
                        }, onError: (code, msg) {
                          dismissLoading(context);
                          toasts(msg);
                        });
                      }
                    },
                  ),
                ),
              ))
        ]),
      ),
    );
  }
}
