import 'dart:convert' as convert;
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:liftmanager/internal/maintenance/maintenance_router.dart';
import 'package:liftmanager/internal/repair/model/repair_fault_entity.dart';
import 'package:liftmanager/internal/repair/model/repair_list_entity.dart';
import 'package:liftmanager/internal/repair/repair_router.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/image_utils.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/click_item.dart';
import 'package:liftmanager/widgets/selected_image.dart';

class RepairSubmitPage extends StatefulWidget {
  RepairSubmitPage(this.item);

  final RepairItem item;

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

class RepairSubmitPageState extends State<RepairSubmitPage> {
  List<File> images = [];
  List<RepairFaultEntity> repairList = [];

  TextEditingController _controller = TextEditingController();

  String faultPart = "";
  String faultPartID = "";

  String faultReason = "";
  String faultReasonID = "";

  String faultHandle = "";
  String faultHandleID = "";

  String faultNature = "";
  String faultNatureID = "";

  String faultDuty = "";
  String faultDutyID = "";

  String erRecordImg = "";
  String recoveryDate = "";

  FocusNode _focusNode = FocusNode();

  Image mainSignImg = Image.asset(
    "assets/images/img_sign.png",
    width: 80,
    height: 80,
  );
  Image secondSign = Image.asset(
    "assets/images/img_sign.png",
    width: 80,
    height: 80,
  );
  var mainSignImgByte;
  var mainSignImgByte2;

  @override
  void initState() {
    super.initState();
    getFaultList();
  }

  ///获取急修原因列表
  void getFaultList() {
    ApiService(context: context).repairFaultTree(widget.item.liftCategory,
        onSuccess: (data) {
      repairList = data;
      setState(() {});
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  /// 选择时间
  Future<void> _selectTime() async {
    DatePicker.showDateTimePicker(context,
        showTitleActions: true, onChanged: (date) {}, onConfirm: (date) {
      recoveryDate = "${date.toString().split(".")[0]}";
      setState(() {});
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  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) {
        images.add(_imageFile);
        setState(() {});
      }
    } catch (e) {
      toasts("没有权限，无法打开相册！");
    }
  }

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

  var faultTitle = ["故障部位和现象", "故障原因", "故障处理", "故障性质", "故障责任"];

  ///点击故障
  _clickFault(int index) {
    if (repairList.length == 0) {
      toasts("正在获取故障数据...");
      return;
    }

    RepairFaultEntity obj;
    for (var i = 0; i < repairList.length; ++i) {
      RepairFaultEntity item = repairList[i];
      print(item.faultCategory);
      print(faultTitle[index]);
      if (item.faultCategory == faultTitle[index]) {
        obj = item;
      }
    }

    String jsonString = convert.jsonEncode(obj);
    NavigatorUtils.pushResult(context,
        "${RepairRouter.repairFaultPage}?title=${Uri.encodeComponent(faultTitle[index])}&item=${Uri.encodeComponent(jsonString)}",
        (result) {
      var res = result as Map<String, String>;
      res.forEach((k, v) {
        if (index == 0) {
          faultPart = faultPart + "${faultPart.length > 0 ? "," : ""}" + v;
          faultPartID =
              faultPartID + "${faultPartID.length > 0 ? "," : ""}" + k;
        } else if (index == 1) {
          faultReason =
              faultReason + "${faultReason.length > 0 ? "," : ""}" + v;
          faultReasonID =
              faultReasonID + "${faultReasonID.length > 0 ? "," : ""}" + k;
        } else if (index == 2) {
          faultHandle =
              faultHandle + "${faultHandle.length > 0 ? "," : ""}" + v;
          faultHandleID =
              faultHandleID + "${faultHandleID.length > 0 ? "," : ""}" + k;
        } else if (index == 3) {
          faultNature =
              faultNature + "${faultNature.length > 0 ? "," : ""}" + v;
          faultNatureID =
              faultNatureID + "${faultNatureID.length > 0 ? "," : ""}" + k;
        } else if (index == 4) {
          faultDuty = faultDuty + "${faultDuty.length > 0 ? "," : ""}" + v;
          faultDutyID =
              faultDutyID + "${faultDutyID.length > 0 ? "," : ""}" + k;
        }
        setState(() {});
      });
    });
  }

  _saveRepairOrder() async {
    if (mainSignImgByte == null) {
      toasts("请签名");
      return;
    }
    if (recoveryDate.length == 0) {
      toasts("请选择恢复时间");
      return;
    }
    if (images.length == 0) {
      toasts("请上传急修图片");
      return;
    }
    showLoading(context, "提交中...");

    List<File> signList = [];
    String file1 = await ImageUtils()
        .saveCacheImageFile(mainSignImgByte, "sign1_${widget.item.id}");
    signList.add(File(file1));
    String file2;
    if (mainSignImgByte2 != null) {
      file2 = await ImageUtils()
          .saveCacheImageFile(mainSignImgByte2, "sign2_${widget.item.id}");
      signList.add(File(file2));
    }

    ///上传急修图片
    ApiService(context: context).uploadMore(images,
        onSuccess: (List<String> data) {
      print(signList);

      ///上传签名图片
      ApiService(context: context).uploadMore(signList,
          onSuccess: (List<String> signData) {
        if (signData != null && signData.length > 0) {
          ApiService(context: context).repairSaveOrder(
              widget.item.id,
              recoveryDate,
              data,
              _controller.text.toString(),
              signData.length > 0 ? signData[0] : "",
              signData.length > 1 ? signData[1] : "",
              faultPartID,
              faultReasonID,
              faultHandleID,
              faultNatureID,
              faultDutyID, onSuccess: (data) {
            dismissLoading(context);
            if (data != null && data) {
              showAlert(context, "提示", "保存成功", "确定", () {
                NavigatorUtils.goBack(context);
                NavigatorUtils.goBackWithParams(context, true);
              });
            }
          }, onError: (code, msg) {
            dismissLoading(context);
            toasts(msg);
          });
        }
      }, onError: (code, msg) {
        toasts(msg);
        dismissLoading(context);
      });
    }, onError: (code, msg) {
      toasts(msg);
      dismissLoading(context);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        //resizeToAvoidBottomPadding: false,
        appBar: MyAppBar(
          centerTitle: "急修单",
          actions: <Widget>[
            FlatButton(
              child: Text("保存", key: const Key('actionName')),
              textColor: Colours.dark_text,
              highlightColor: Colors.transparent,
              onPressed: () {
                _saveRepairOrder();
              },
            )
          ],
        ),
        body: SafeArea(
          child: Container(
            color: ThemeUtils.getBackgroundColor(context),
            child: Column(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: defaultTargetPlatform == TargetPlatform.iOS
                      ? FormKeyboardActions(child: _buildBody())
                      : SingleChildScrollView(child: _buildBody()),
                ),
              ],
            ),
          ),
        ));
  }

  _buildBody() {
    return Padding(
        padding: EdgeInsets.only(bottom: 30),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <
            Widget>[
          ClickItem(
            title: "故障部位",
            hintText: "请选择",
            maxLines: 10,
            content: "${faultPart}",
            onTap: () {
              _clickFault(0);
            },
          ),
          ClickItem(
            title: "故障原因",
            hintText: "请选择",
            maxLines: 10,
            content: "${faultReason}",
            onTap: () {
              _clickFault(1);
            },
          ),
          ClickItem(
            title: "故障处理",
            hintText: "请选择",
            maxLines: 10,
            content: "${faultHandle}",
            onTap: () {
              _clickFault(2);
            },
          ),
          ClickItem(
            title: "故障性质",
            hintText: "请选择",
            maxLines: 10,
            content: "${faultNature}",
            onTap: () {
              _clickFault(3);
            },
          ),
          ClickItem(
            title: "故障责任",
            hintText: "请选择",
            maxLines: 10,
            content: "${faultDuty}",
            onTap: () {
              _clickFault(4);
            },
          ),
          SizedBox(
            height: 8,
          ),
          ClickItem(
            title: "现场情况描述",
            hintText: "",
          ),
          Container(
            color: ThemeUtils.getTabsBg(context),
            child: Padding(
              padding: const EdgeInsets.only(
                  top: 5, left: 15.0, right: 15.0, bottom: 8.0),
              child: TextField(
                  maxLength: 30,
                  maxLines: 3,

//                  autofocus: false,
                  focusNode: _focusNode,
                  controller: _controller,
//                    keyboardType: widget.keyboardType,
                  //style: TextStyles.textDark14,
                  decoration: InputDecoration(
                      hintText: "填写现场情况描述",
                      border: InputBorder.none,
                      hintStyle: TextStyles.textGray14)),
            ),
          ),
          SizedBox(
            height: 8,
          ),
          ClickItem(
            title: "恢复时间",
            hintText: "请选择",
            content: recoveryDate,
            onTap: () {
              if (_focusNode.hasFocus) {
                _focusNode.unfocus();
              }
              _selectTime();
            },
          ),
          SizedBox(
            height: 8,
          ),
          ClickItem(
            title: "上传修理图片",
            hintText: "",
          ),
          Container(
              color: ThemeUtils.getTabsBg(context),
              child: GridView.builder(
                shrinkWrap: true,
                padding: const EdgeInsets.fromLTRB(8.0, 12, 8.0, 12.0),
                physics: NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3, childAspectRatio: 1.18),
                itemCount: images.length >= 9 ? 9 : images.length + 1,
                itemBuilder: (_, index) {
                  return Stack(
                    children: <Widget>[
                      Center(
                        child: SelectedImage(
                            image: index < images.length ? images[index] : null,
                            onTap: () {
                              if (_focusNode.hasFocus) {
                                _focusNode.unfocus();
                              }
                              if (index < images.length) {
                                NavigatorUtils.pushResult(
                                    context,
                                    "${MaintenanceRouter.viewImage}?edit=1&img=" +
                                        Uri.encodeComponent(images[index].path),
                                    (res) {
                                  if (res != null) {
                                    images.removeAt(index);
                                    setState(() {});
                                  }
                                });
                              } else {
                                selectPicker();
                              }
                            }),
                      )
                    ],
                  );
                },
              )),
          SizedBox(
            height: 8,
          ),
          ClickItem(
            title: "负责人签名",
            hintText: "",
          ),
          Container(
              padding: EdgeInsets.all(15),
              color: ThemeUtils.getTabsBg(context),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  GestureDetector(
                      onTap: () {
                        if (_focusNode.hasFocus) {
                          _focusNode.unfocus();
                        }
                        NavigatorUtils.pushResult(
                            context, RepairRouter.repairSignaturePage,
                            (result) {
                          if (result != null) {
                            mainSignImgByte = result;
                            Image image = Image.memory(result);
                            setState(() {
                              mainSignImg = image;
                            });
                          }
                        });
                      },
                      child: Container(
                        color: ThemeUtils.getTabsBg(context),
                        alignment: Alignment.center,
                        child: Stack(
                          alignment: Alignment.center,
                          children: <Widget>[
                            Container(
                                width: 80, height: 80, child: mainSignImg),
                            Positioned(
                                child: Text(
                              "主要急修人员",
                              style: TextStyle(
                                  fontSize: 12, color: Colours.text_gray_c),
                            )),
                          ],
                        ),
                      )),
                  SizedBox(
                    width: 15,
                  ),
                  GestureDetector(
                      onTap: () {
                        if (_focusNode.hasFocus) {
                          _focusNode.unfocus();
                        }
                        NavigatorUtils.pushResult(
                            context, RepairRouter.repairSignaturePage,
                            (result) {
                          if (result != null) {
                            mainSignImgByte2 = result;
                            Image image = Image.memory(result);
                            setState(() {
                              secondSign = image;
                            });
//                                _saveFile(result,"sign2").then((res){
//                                  print(res);
//                                  secondSign = res;
//                                  setState(() {
//
//                                  });
//                                });
                          }
                        });
                      },
                      child: Container(
                        color: ThemeUtils.getTabsBg(context),
                        alignment: Alignment.center,
                        child: Stack(
                          alignment: Alignment.center,
                          children: <Widget>[
                            Positioned(
                                child: Text(
                              "次要急修人员",
                              style: TextStyle(
                                  fontSize: 12, color: Colours.text_gray_c),
                            )),
                            Container(width: 80, height: 80, child: secondSign),
                          ],
                        ),
                      ))
                ],
              ))
        ]));
  }
}
