import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:special_equipment_flutter/common/color_const.dart';
import 'package:special_equipment_flutter/common/route_string.dart';
import 'package:special_equipment_flutter/dio/http_utils.dart';
import 'package:special_equipment_flutter/model/equipment_bo.dart';
import 'package:special_equipment_flutter/model/office_device.dart';
import 'package:special_equipment_flutter/model/unit_bo.dart';
import 'package:special_equipment_flutter/utils/log_util.dart';
import 'package:special_equipment_flutter/utils/toast_utils.dart';
import 'package:special_equipment_flutter/widgets/custom_button.dart';
import 'package:special_equipment_flutter/widgets/custom_textfield.dart';

///单位设置
class UnitSettingsPage extends StatefulWidget {
  const UnitSettingsPage({super.key});

  @override
  State<UnitSettingsPage> createState() => _UnitSettingsPageState();
}

class _UnitSettingsPageState extends State<UnitSettingsPage> {
  TextEditingController? unitText = TextEditingController();
  FocusNode? unitFocusNode = FocusNode();
  TextEditingController? codeText = TextEditingController();
  FocusNode? codeFocusNode = FocusNode();
  TextEditingController? areaText = TextEditingController();
  FocusNode? areaFocusNode = FocusNode();
  TextEditingController? addressText = TextEditingController();
  FocusNode? addressFocusNode = FocusNode();
  bool _isCheckedSY = false, _isCheckedSC = false;
  var addressId = '', addressName = '', officeType = '';

  List<Rows> equipmentSYBoList = [];
  List<Rows> equipmentSCBoList = [];
  OfficeDevice? officeDevice;

  @override
  void initState() {
    super.initState();
    // unitText!.text = '盈中技术有限公司';
    // codeText!.text = '91140105672322918R (1-1)';
    // addressText!.text = '平阳景园南门 1 号楼';
    getData();
  }

  getData() async {
    HttpUtils.getOfficeDevice(context).then((value) {
      if (value != null) {
        OfficeDevice officeDeviceItem = value;
        setState(() {
          officeDevice = officeDeviceItem;
          unitText!.text = officeDeviceItem.office!.name!;
          codeText!.text = officeDeviceItem.office!.code!;
          areaText!.text = officeDeviceItem.office!.area!.name!;
          addressText!.text = officeDeviceItem.office!.address!;
          addressId = officeDeviceItem.office!.area!.id!;
          officeType = officeDeviceItem.office!.type!;
          var type = officeDeviceItem.office!.type!.split(',');
          var item0 = type[0];
          if (type.length == 2) {
            _isCheckedSY = true;
            _isCheckedSC = true;
          } else {
            if (item0 == '1') {
              _isCheckedSY = true;
            }
            if (item0 == '2') {
              _isCheckedSC = true;
            }
          }
          HttpUtils.getDeviceData(context, '1').then((value) {
            if (value != null) {
              EquipmentBo equipmentBo = value;
              setState(() {
                equipmentSYBoList.addAll(equipmentBo.rows!);
                for (var allItem in equipmentSYBoList) {
                  allItem.deviceTypeId = allItem.id;
                  allItem.id = '';
                }
                if (_isCheckedSY) {
                  var selectList = officeDevice!.office!.officeDtoList;
                  for (var selectItem in selectList!) {
                    for (var allItem in equipmentSYBoList) {
                      //选中的设备/类型
                      if (selectItem.deviceTypeId == allItem.deviceTypeId) {
                        allItem.isChecked = true;
                        allItem.deviceTypeId = selectItem.deviceTypeId;
                        allItem.id = selectItem.id;
                      }
                    }
                  }
                }
              });
            }
          });
          HttpUtils.getDeviceData(context, '2').then((value) {
            if (value != null) {
              EquipmentBo equipmentBo = value;
              setState(() {
                equipmentSCBoList.addAll(equipmentBo.rows!);
                for (var allItem in equipmentSCBoList) {
                  allItem.deviceTypeId = allItem.id;
                  allItem.id = '';
                }
                if (_isCheckedSC) {
                  var selectList = officeDevice!.office!.officeDtoList;
                  for (var selectItem in selectList!) {
                    for (var allItem in equipmentSCBoList) {
                      //选中的设备/类型
                      if (selectItem.deviceTypeId == allItem.deviceTypeId) {
                        allItem.isChecked = true;
                        allItem.deviceTypeId = selectItem.deviceTypeId;
                        allItem.id = selectItem.id;
                      }
                    }
                  }
                }
              });
            }
          });
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      body: Stack(
        children: [
          Image.asset('assets/home/rigister_bg.png'),
          Container(
            margin:
                const EdgeInsets.only(left: 15, top: 130, right: 15, bottom: 0),
            decoration: const BoxDecoration(
              color: ColorConst.whiteColor,
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: CustomScrollView(
              primary: false,
              shrinkWrap: true,
              slivers: <Widget>[
                SliverToBoxAdapter(
                  child: Column(
                    children: [
                      buildUnitInformation(),
                      buildSubmit(),
                      const SizedBox(height: 30)
                    ],
                  ),
                ),
              ],
            ),
          ),
          buildTopTitle(context)
        ],
      ),
    );
  }

  ///单位信息
  Container buildUnitInformation() {
    return Container(
      margin: const EdgeInsets.only(left: 10, top: 20, right: 10, bottom: 30),
      child: Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              const Row(children: [
                Icon(Icons.drive_file_rename_outline_rounded,
                    color: ColorConst.orangeColor, size: 15),
                Text('单位名称',
                    style: TextStyle(fontSize: 14, color: Colors.black))
              ]),
              const SizedBox(height: 5),
              CustomTextField(
                  enabled: true,
                  readOnly: false,
                  hintText: '请填写单位名称',
                  controller: unitText,
                  focusNode: unitFocusNode),
              const SizedBox(height: 10),
              const Row(
                children: [
                  Icon(Icons.drive_file_rename_outline_rounded,
                      color: ColorConst.orangeColor, size: 15),
                  Text.rich(TextSpan(children: [
                    TextSpan(text: '统一社会信用代码', style: TextStyle(fontSize: 14)),
                  ])),
                ],
              ),
              const SizedBox(height: 5),
              CustomTextField(
                  enabled: true,
                  readOnly: false,
                  hintText: '请填写统一社会信用代码',
                  controller: codeText,
                  // isNoChinese: true,
                  focusNode: codeFocusNode),
              const SizedBox(height: 10),
              const Row(children: [
                Icon(Icons.touch_app, color: ColorConst.orangeColor, size: 15),
                Text('归属区域', style: TextStyle(fontSize: 14))
              ]),
              const SizedBox(height: 5),
              CustomTextField(
                  enabled: true,
                  readOnly: true,
                  hintText: '请选择归属区域',
                  controller: areaText,
                  focusNode: areaFocusNode,
                  onTop: () {
                    Get.toNamed(RouteString.ADDRESS)?.then((map) {
                      if (map != null) {
                        addressId = map['id'];
                        addressName = map['address'];
                        print(jsonEncode(map));
                        setState(() {
                          areaText!.text = addressName;
                        });
                      }
                    });
                  }),
              const SizedBox(height: 10),
              const Row(children: [
                Icon(Icons.drive_file_rename_outline_rounded,
                    color: ColorConst.orangeColor, size: 15),
                Text('详细地址', style: TextStyle(fontSize: 14))
              ]),
              const SizedBox(height: 5),
              CustomTextField(
                  enabled: true,
                  readOnly: false,
                  hintText: '请填写详细地址',
                  controller: addressText,
                  focusNode: addressFocusNode),
              const SizedBox(height: 10),
              const Row(children: [
                Icon(Icons.touch_app, color: ColorConst.orangeColor, size: 15),
                Text('单位类型')
              ]),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        _isCheckedSY = !_isCheckedSY;
                      });
                    },
                    child: Padding(
                      padding: const EdgeInsets.only(
                          left: 0, top: 10, bottom: 10, right: 10),
                      child: Row(
                        children: <Widget>[
                          Container(
                            margin: const EdgeInsets.only(left: 5),
                            width: 25,
                            height: 25,
                            child: Transform.scale(
                              scale: 0.8,
                              child: Checkbox(
                                value: _isCheckedSY, // 指定复选框的状态
                                onChanged: (value) {
                                  setState(() {
                                    _isCheckedSY = value!; // 更新 isChecked 的状态值
                                  });
                                },
                              ),
                            ),
                          ),
                          const Text('使用单位',
                              style: TextStyle(
                                  fontSize: 13,
                                  color: Colors.black54,
                                  fontWeight: FontWeight.bold)),
                        ],
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        _isCheckedSC = !_isCheckedSC;
                      });
                    },
                    child: Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Row(
                        children: <Widget>[
                          Container(
                            margin: const EdgeInsets.only(left: 25),
                            width: 25,
                            height: 25,
                            child: Transform.scale(
                              scale: 0.8,
                              child: Checkbox(
                                value: _isCheckedSC, // 指定复选框的状态
                                onChanged: (value) {
                                  setState(() {
                                    _isCheckedSC = value!; // 更新 isChecked 的状态值
                                  });
                                },
                              ),
                            ),
                          ),
                          const Text(
                            '生产单位',
                            style: TextStyle(
                                fontSize: 13,
                                color: Colors.black54,
                                fontWeight: FontWeight.bold), // 设置文本样式
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              if (_isCheckedSY) ...[
                Container(
                  padding: const EdgeInsets.only(top: 5),
                  margin: const EdgeInsets.only(top: 0),
                  decoration: BoxDecoration(
                    color: Colors.grey[100],
                    borderRadius: BorderRadius.circular(5.0),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                          margin: const EdgeInsets.only(left: 10, right: 10),
                          child: const Text('使用单位',
                              style: TextStyle(
                                  fontSize: 14,
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold))),
                      GridView.builder(
                        itemCount: equipmentSYBoList.length,
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        padding: const EdgeInsets.only(
                            top: 10, left: 5, right: 5, bottom: 10),
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 3, // 每行显示的列数
                                crossAxisSpacing: 3.0, // 列之间的间距
                                childAspectRatio: 2 / 0.5,
                                mainAxisSpacing: 8.0 // 行之间的间距
                                ),
                        itemBuilder: (BuildContext context, int index) {
                          return GestureDetector(
                            // 点击每个Grid Item时切换选中状态
                            onTap: () {
                              setState(() {
                                equipmentSYBoList[index].isChecked =
                                    !equipmentSYBoList[index].isChecked!;
                              });
                            },
                            child: equipmentSYBoList[index].isChecked!
                                ? Stack(
                                    children: [
                                      Container(
                                        decoration: BoxDecoration(
                                          color: Colors.blue[100],
                                          borderRadius:
                                              BorderRadius.circular(3),
                                        ),
                                        alignment: Alignment.center,
                                        child: Text(
                                          equipmentSYBoList[index].name!,
                                          style: const TextStyle(
                                              fontSize: 12, color: Colors.blue),
                                        ),
                                      ),
                                      Positioned(
                                        bottom: 0,
                                        right: 0,
                                        child: Image.asset(
                                            'assets/home/select_check_blue.png',
                                            height: 15,
                                            width: 15),
                                      )
                                    ],
                                  )
                                : Container(
                                    decoration: BoxDecoration(
                                      color: Colors.transparent,
                                      border: Border.all(
                                          color: ColorConst.greyD2Color,
                                          width: 0.7),
                                      borderRadius: BorderRadius.circular(3),
                                    ),
                                    alignment: Alignment.center,
                                    child: Text(
                                      equipmentSYBoList[index].name!,
                                      style: const TextStyle(
                                          fontSize: 12, color: Colors.black),
                                    ),
                                  ),

                            // child: Container(
                            //   decoration: BoxDecoration(
                            //     color: equipmentSYBoList[index].isChecked!
                            //         ? Colors.blue[50]
                            //         : Colors.transparent,
                            //     border: Border.all(
                            //         color: equipmentSYBoList[index].isChecked!
                            //             ? Colors.blue
                            //             : ColorConst.greyD2Color,
                            //         width: 1),
                            //     borderRadius: BorderRadius.circular(3),
                            //   ),
                            //   alignment: Alignment.center,
                            //   child: Text(
                            //     equipmentSYBoList[index].name!,
                            //     style: TextStyle(
                            //         fontSize: 12,
                            //         color: equipmentSYBoList[index].isChecked!
                            //             ? Colors.blue
                            //             : Colors.black),
                            //   ),
                            // ),
                          );
                        },
                      ),
                    ],
                  ),
                )
              ],
              if (_isCheckedSC) ...[
                Container(
                  padding: const EdgeInsets.only(top: 5),
                  margin: const EdgeInsets.only(top: 10),
                  decoration: BoxDecoration(
                    color: Colors.grey[100],
                    borderRadius: BorderRadius.circular(5.0),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                          margin: const EdgeInsets.only(left: 10, right: 10),
                          child: const Text('生产单位',
                              style: TextStyle(
                                  fontSize: 14,
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold))),
                      GridView.builder(
                        itemCount: equipmentSCBoList.length,
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        padding: const EdgeInsets.only(
                            top: 10, left: 5, right: 5, bottom: 10),
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 3, // 每行显示的列数
                                crossAxisSpacing: 2, // 列之间的间距
                                childAspectRatio: 2 / 0.5,
                                mainAxisSpacing: 8.0 // 行之间的间距
                                ),
                        itemBuilder: (BuildContext context, int index) {
                          return GestureDetector(
                            // 点击每个Grid Item时切换选中状态
                            onTap: () {
                              setState(() {
                                equipmentSCBoList[index].isChecked =
                                    !equipmentSCBoList[index].isChecked!;
                              });
                            },

                            child: equipmentSCBoList[index].isChecked!
                                ? Stack(
                                    children: [
                                      Container(
                                        decoration: BoxDecoration(
                                          color: Colors.orange[100],
                                          borderRadius:
                                              BorderRadius.circular(3),
                                        ),
                                        alignment: Alignment.center,
                                        child: Text(
                                          equipmentSCBoList[index].name!,
                                          style: TextStyle(
                                              fontSize: 12,
                                              color: Colors.orange[900]),
                                        ),
                                      ),
                                      Positioned(
                                        bottom: 0,
                                        right: 0,
                                        child: Image.asset(
                                            'assets/home/select_check_orange.png',
                                            height: 15,
                                            width: 15),
                                      )
                                    ],
                                  )
                                : Container(
                                    decoration: BoxDecoration(
                                      color: Colors.transparent,
                                      border: Border.all(
                                          color: ColorConst.greyD2Color,
                                          width: 0.7),
                                      borderRadius: BorderRadius.circular(3),
                                    ),
                                    alignment: Alignment.center,
                                    child: Text(
                                      equipmentSCBoList[index].name!,
                                      style: const TextStyle(
                                          fontSize: 12, color: Colors.black),
                                    ),
                                  ),

                            // child: Container(
                            //   decoration: BoxDecoration(
                            //     color: equipmentSCBoList[index].isChecked!
                            //         ? Colors.orange[50]
                            //         : Colors.transparent,
                            //     border: Border.all(
                            //         color: equipmentSCBoList[index].isChecked!
                            //             ? Colors.orange
                            //             : ColorConst.greyD2Color,
                            //         width: 1),
                            //     borderRadius: BorderRadius.circular(3),
                            //   ),
                            //   alignment: Alignment.center,
                            //   child: Text(
                            //     equipmentSCBoList[index].name!,
                            //     style: TextStyle(
                            //         fontSize: 12,
                            //         color: equipmentSCBoList[index].isChecked!
                            //             ? Colors.orange
                            //             : Colors.black),
                            //   ),
                            // ),
                          );
                        },
                      ),
                    ],
                  ),
                )
              ]
              // EquipmentGridViewList(
              //     equipmentSYBoList: equipmentSYBoList,
              //     equipmentSCBoList: equipmentSCBoList,
              //     isSYVisbliy: _isCheckedSY,
              //     isSCVisbliy: _isCheckedSC)
            ],
          )
        ],
      ),
    );
  }

  Container buildTopTitle(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(top: 50),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          IconButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            icon: const Icon(Icons.arrow_back, color: Colors.white),
            iconSize: 30,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                  margin: const EdgeInsets.only(top: 5),
                  child: const Text(
                    '单位设置',
                    style: TextStyle(
                        fontSize: 23,
                        color: Colors.white,
                        fontWeight: FontWeight.bold),
                  )),
              Container(
                  height: 3,
                  width: 50,
                  alignment: Alignment.topLeft,
                  margin: const EdgeInsets.only(top: 3, bottom: 3),
                  decoration: const BoxDecoration(
                    color: Colors.white54,
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                  )),
              const Text(
                '我们将根据您填写的内容来为您【设置单位】',
                style: TextStyle(fontSize: 12, color: Colors.white),
              ),
            ],
          ),
        ],
      ),
    );
  }

  ///下一步按钮
  Container buildSubmit() {
    return Container(
        margin: const EdgeInsets.only(top: 10, bottom: 10),
        child: GradientButton(
            tapCallback: () {
              if (unitText!.text.isEmpty) {
                unitFocusNode!.requestFocus();
                ToastUtils.showCenter('请填写单位名称');
                return;
              }
              if (codeText!.text.isEmpty) {
                codeFocusNode!.requestFocus();
                ToastUtils.showCenter('请填写统一社会信用代码');
                return;
              }
              if (areaText!.text.isEmpty) {
                areaFocusNode!.requestFocus();
                ToastUtils.showCenter('请选择归属区域');
                return;
              }
              if (addressText!.text.isEmpty) {
                addressFocusNode!.requestFocus();
                ToastUtils.showCenter('请填写详细地址');
                return;
              }
              if (!_isCheckedSY && !_isCheckedSC) {
                ToastUtils.showCenter('请选择您的单位类型');
                return;
              }
              if (_isCheckedSY) {
                bool isEquipmentSYBoList = false;
                for (var item in equipmentSYBoList) {
                  if (item.isChecked!) {
                    isEquipmentSYBoList = true;
                    break;
                  }
                }
                if (!isEquipmentSYBoList) {
                  ToastUtils.showCenter('（使用单位）请选择设备');
                  return;
                }
              }
              if (_isCheckedSC) {
                bool isEquipmentSCBoList = false;
                for (var item in equipmentSCBoList) {
                  if (item.isChecked!) {
                    isEquipmentSCBoList = true;
                    break;
                  }
                }
                if (!isEquipmentSCBoList) {
                  ToastUtils.showCenter('（生产单位）请选择设备');
                  return;
                }
              }
              submitData();
            },
            width: 200,
            height: 40,
            borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(10),
                topRight: Radius.circular(20),
                bottomLeft: Radius.circular(20),
                bottomRight: Radius.circular(10)),
            disable: false,
            colors: const [ColorConst.blueColor, ColorConst.blue1Color],
            child: const Text(
              "提交",
              style: TextStyle(fontSize: 14, color: ColorConst.whiteColor),
            )));
  }

  void submitData() {
    UnitBo user = UnitBo();
    UnitArea area = UnitArea();
    user.id = officeDevice!.office!.id!;
    //单位名称
    user.name = unitText!.text;
    //统一社会信用代码
    user.code = codeText!.text;
    //详细地址
    user.address = addressText!.text;
    //归属区域
    area.id = addressId;
    user.area = area;

    List<OfficeDtoUnitList>? officeDtoList = [];
    officeDtoList.clear();

    ///同时选中使用单位、生产单位
    if (_isCheckedSY && _isCheckedSC) {
      officeType = '1,2';
      //将选中的使用单位设备放到集合内
      for (var item in equipmentSYBoList) {
        if (item.isChecked!) {
          OfficeDtoUnitList officeDto = OfficeDtoUnitList();
          officeDto.id = item.id;
          officeDto.unitType = item.unitType;
          officeDto.deviceTypeId = item.deviceTypeId;
          officeDtoList.add(officeDto);
        }
      }
      //将选中的生产单位设备放到集合内
      for (var item in equipmentSCBoList) {
        if (item.isChecked!) {
          OfficeDtoUnitList officeDto = OfficeDtoUnitList();
          officeDto.id = item.id;
          officeDto.unitType = item.unitType;
          officeDto.deviceTypeId = item.deviceTypeId;
          officeDtoList.add(officeDto);
        }
      }
    } else {
      ///只选择了使用单位
      if (_isCheckedSY) {
        officeType = '1';
        //将选中的使用单位设备放到集合内
        for (var item in equipmentSYBoList) {
          if (item.isChecked!) {
            OfficeDtoUnitList officeDto = OfficeDtoUnitList();
            officeDto.id = item.id;
            officeDto.unitType = item.unitType;
            officeDto.deviceTypeId = item.deviceTypeId;
            officeDtoList.add(officeDto);
          }
        }
      }

      ///只选择了生产单位
      if (_isCheckedSC) {
        officeType = '2';
        //将选中的生产单位设备放到集合内
        for (var item in equipmentSCBoList) {
          if (item.isChecked!) {
            OfficeDtoUnitList officeDto = OfficeDtoUnitList();
            officeDto.id = item.id;
            officeDto.unitType = item.unitType;
            officeDto.deviceTypeId = item.deviceTypeId;
            officeDtoList.add(officeDto);
          }
        }
      }
    }
    //单位类型
    user.type = officeType;
    user.officeDtoList = officeDtoList;

    printLog(jsonEncode(user));
    HttpUtils.getUnitSaveApp(context, user).then((value) {
      if (value == null) {
        return;
      }
      if (mounted) {
        setState(() {
          ToastUtils.showCenter('提交成功');
          Get.back(result: true);
        });
      }
    });
  }
}
