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/dio/http_utils.dart';
import 'package:special_equipment_flutter/model/app_roles.dart';
import 'package:special_equipment_flutter/model/unit_rigister_bo.dart';
import 'package:special_equipment_flutter/utils/storage_util.dart';
import 'package:special_equipment_flutter/utils/string_utils.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';

import '../../../model/user_list.dart';

///用户设置：新建、修改
class UserSettingsPage extends StatefulWidget {
  ///type=1:新建、type=2:修改
  var arguments = Get.arguments;

  UserSettingsPage({super.key});

  @override
  State<UserSettingsPage> createState() => _UserSettingsPageState();
}

class _UserSettingsPageState extends State<UserSettingsPage> {
  TextEditingController? unitText = TextEditingController();
  FocusNode? unitFocusNode = FocusNode();
  TextEditingController? nameText = TextEditingController();
  FocusNode? nameFocusNode = FocusNode();
  TextEditingController? loginNameText = TextEditingController();
  FocusNode? loginNameFocusNode = FocusNode();
  TextEditingController? passwordText = TextEditingController();
  TextEditingController? okPasswordText = TextEditingController();
  FocusNode? passwordFocusNode = FocusNode();
  FocusNode? okPasswordFocusNode = FocusNode();
  TextEditingController? moblieText = TextEditingController();
  FocusNode? moblieFocusNode = FocusNode();

  List<Data> newList = [];

  ///type=1:新建、type=2:修改、type=3:查看
  var type = '';
  RowUserLists? editList;

  @override
  void initState() {
    super.initState();
    type = widget.arguments['type'];
    unitText!.text = StorageUtil.getInstance().getOfficeName();
    if (type == '2') {
      editList = null;
      editList = widget.arguments['item'];
      nameText!.text = editList!.name!;
      loginNameText!.text = editList!.loginName!;
      passwordText!.text = '';
      okPasswordText!.text = '';
      moblieText!.text = editList!.mobile!;
      // HttpUtils.getAppUser(context, editList!.id).then((value) {
      //   if (value != null) {
      //     AppRoles appRoles = value;
      //     setState(() {
      //       newList.addAll(appRoles.data!);
      //     });
      //   }
      // });
    } else {
      getData();
      // nameText!.text = '老刘刘';
      // loginNameText!.text = 'laoliuliu';
      // passwordText!.text = 'Aa123456.';
      // okPasswordText!.text = 'Aa123456.';
      // moblieText!.text = '15201506337';
    }
  }

  getData() async {
    ///新建获取角色
    HttpUtils.getAppRoles(context).then((value) {
      if (value != null) {
        AppRoles appRoles = value;
        setState(() {
          newList.addAll(appRoles.data!);
        });
      }
    });
  }

  @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)
        ],
      ),
    );
  }

  String roleNames() {
    String result = "";
    var arrayList = editList!.userRoleList!;
    for (int i = 0; i < arrayList.length; i++) {
      if (i != arrayList.length - 1) {
        result += ("${arrayList[i].name!},");
      } else {
        result += arrayList[i].name!;
      }
    }
    return result;
  }

  dynamic isItemRoleNames(String roleNames) {
    if (roleNames.contains('公司账户')) {
      return true;
    } else {
      return false;
    }
  }

  ///用户信息
  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>[
              Column(
                children: [
                  const SizedBox(height: 5),
                  Container(
                      margin: const EdgeInsets.only(left: 5, right: 0),
                      child: const Row(children: [
                        Text('归属单位',
                            style:
                                TextStyle(fontSize: 14, color: Colors.black)),
                        Text('*',
                            style: TextStyle(fontSize: 14, color: Colors.red)),
                      ])),
                  const SizedBox(height: 5),
                  CustomTextField(
                      enabled: false,
                      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)),
                      ])),
                      Text('*',
                          style: TextStyle(fontSize: 14, color: Colors.red)),
                    ],
                  ),
                  const SizedBox(height: 5),
                  CustomTextField(
                      enabled: true,
                      readOnly: false,
                      hintText: '请填写您的姓名',
                      controller: nameText,
                      // isNoChinese: true,
                      focusNode: nameFocusNode),
                  const SizedBox(height: 10),
                  const Row(children: [
                    Icon(Icons.drive_file_rename_outline_rounded,
                        color: ColorConst.orangeColor, size: 15),
                    Text('登录名'),
                    Text('*',
                        style: TextStyle(fontSize: 14, color: Colors.red)),
                  ]),
                  const SizedBox(height: 5),
                  CustomTextField(
                      enabled: type == '1' ? true : false,
                      readOnly: false,
                      hintText: '请填写登录名（建议手机号码）',
                      controller: loginNameText,
                      maxLength: 20,
                      focusNode: loginNameFocusNode,
                      isNoChinese: true),
                  Container(
                    width: 1080,
                    margin: const EdgeInsets.only(left: 5, right: 5, top: 5),
                    padding: const EdgeInsets.only(
                        left: 5, right: 5, top: 3, bottom: 3),
                    decoration: BoxDecoration(
                      color: Colors.orange[50],
                      borderRadius: const BorderRadius.only(
                          topLeft: Radius.circular(5),
                          topRight: Radius.circular(5),
                          bottomLeft: Radius.circular(5),
                          bottomRight: Radius.circular(5)),
                    ),
                    child: Text(
                      softWrap: true,
                      type == '1' ? '建议手机号码' : '登录名不可修改',
                      style:
                          const TextStyle(color: Colors.orange, fontSize: 12),
                    ),
                  ),
                  const SizedBox(height: 10),
                  const Row(children: [
                    Icon(Icons.drive_file_rename_outline_rounded,
                        color: ColorConst.orangeColor, size: 15),
                    Text('密码'),
                    Text('*',
                        style: TextStyle(fontSize: 14, color: Colors.red)),
                  ]),
                  const SizedBox(height: 5),
                  CustomTextField(
                      enabled: true,
                      readOnly: false,
                      hintText: '请填写密码',
                      obscureText: true,
                      controller: passwordText,
                      focusNode: passwordFocusNode,
                      isNoChinese: true),
                  Container(
                    margin: const EdgeInsets.only(left: 5, right: 5, top: 5),
                    padding: const EdgeInsets.only(
                        left: 5, right: 5, top: 3, bottom: 3),
                    decoration: BoxDecoration(
                      color: Colors.orange[50],
                      borderRadius: const BorderRadius.only(
                          topLeft: Radius.circular(5),
                          topRight: Radius.circular(5),
                          bottomLeft: Radius.circular(5),
                          bottomRight: Radius.circular(5)),
                    ),
                    child: const Text(
                      softWrap: true,
                      '密码至少包含以下 3 种类别：大写字母、小写字母、数字、特殊符号、8-20位',
                      style: TextStyle(color: Colors.orange, fontSize: 12),
                    ),
                  ),
                  const SizedBox(height: 8),
                  const Row(children: [
                    Icon(Icons.drive_file_rename_outline_rounded,
                        color: ColorConst.orangeColor, size: 15),
                    Text('确认密码'),
                    Text('*',
                        style: TextStyle(fontSize: 14, color: Colors.red)),
                  ]),
                  const SizedBox(height: 5),
                  CustomTextField(
                      enabled: true,
                      readOnly: false,
                      hintText: '请填写确认密码',
                      obscureText: true,
                      controller: okPasswordText,
                      focusNode: okPasswordFocusNode,
                      isNoChinese: true),
                  const SizedBox(height: 8),
                  const Row(children: [
                    Icon(Icons.drive_file_rename_outline_rounded,
                        color: ColorConst.orangeColor, size: 15),
                    Text('手机号码'),
                    Text('*',
                        style: TextStyle(fontSize: 14, color: Colors.red)),
                  ]),
                  const SizedBox(height: 5),
                  CustomTextField(
                      enabled: true,
                      readOnly: false,
                      textInputType: TextInputType.phone,
                      hintText: '请填写手机号码',
                      maxLength: 11,
                      controller: moblieText,
                      focusNode: moblieFocusNode),
                  const SizedBox(height: 10),
                  const Row(children: [
                    Icon(Icons.drive_file_rename_outline_rounded,
                        color: ColorConst.orangeColor, size: 15),
                    Text('用户身份'),
                    Text('*',
                        style: TextStyle(fontSize: 14, color: Colors.red)),
                  ]),

                  if (type == '2') ...[
                    ///修改
                    buildEditListView(),
                  ] else ...[
                    ///新建
                    buildAddListView(),
                  ]

                  //
                  //         // GridViewAQZJList(
                  //         //     equipmentSYBoList:
                  //         //         allRolesList[index].officeDtoSYList,
                  //         //     equipmentSCBoList:
                  //         //         allRolesList[index].officeDtoSCList,
                  //         //     isVisbliy: allRolesList[index].isChecked)
                ],
              )
            ],
          ),
        ],
      ),
    );
  }

  ///用户新建
  ListView buildAddListView() {
    return ListView.separated(
      shrinkWrap: true,
      padding: const EdgeInsets.only(top: 0, bottom: 0),
      physics: const NeverScrollableScrollPhysics(),
      itemBuilder: (BuildContext context, int index) {
        return Column(
          children: [
            GestureDetector(
              onTap: () {
                setState(() {
                  if (newList[index].name == '公司账户') {
                    newList[index].check = !newList[index].check!;
                  } else {
                    newList[index].check = !newList[index].check!;
                  }

                  ///如果取消身份勾选，将当前身份下的已选中设备全部取消勾选
                  if (!newList[index].check!) {
                    for (var item in newList[index].userDtoList!) {
                      item.check = false;
                    }
                  }
                });
              },
              child: Padding(
                padding: const EdgeInsets.only(
                    left: 0, top: 10, bottom: 0, right: 10),
                child: Row(
                  children: <Widget>[
                    Container(
                      margin: const EdgeInsets.only(left: 0),
                      width: 21,
                      height: 21,
                      child: Transform.scale(
                        scale: 0.8,
                        child: Checkbox(
                            value: newList[index].name == '公司账户'
                                ? false
                                : newList[index].check!,
                            // 指定复选框的状态
                            onChanged: newList[index].name == '公司账户'
                                ? null
                                : (value) {
                                    setState(() {
                                      newList[index].check =
                                          value!; // 更新 isChecked 的状态值
                                    });
                                  },
                            side: MaterialStateBorderSide.resolveWith(
                              (Set<MaterialState> states) {
                                //修改默认时边框颜色为绿色
                                return newList[index].name == '公司账户'
                                    ? const BorderSide(
                                        width: 2, color: Colors.black12)
                                    : null;
                              },
                            )),
                      ),
                    ),
                    Text(newList[index].name!, // 设置外层角色文本内容
                        style: TextStyle(
                            fontSize: 14,
                            color: newList[index].name == '公司账户'
                                ? Colors.grey[400]
                                : Colors.black54,
                            fontWeight: FontWeight.bold)),
                  ],
                ),
              ),
            ),

            if (newList[index].check! &&
                newList[index].userDtoList!.isNotEmpty) ...[
              Container(
                margin: const EdgeInsets.only(top: 5),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(5.0),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    if (newSyList(index)!.isNotEmpty) ...[
                      Container(
                          margin: const EdgeInsets.only(
                              left: 10, right: 10, top: 5),
                          child: const Text('使用单位',
                              style: TextStyle(fontWeight: FontWeight.bold))),
                      GridView.builder(
                        itemCount: newSyList(index) != null
                            ? newSyList(index)!.length
                            : 0,
                        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 subIndex) {
                          return GestureDetector(
                            // 点击每个Grid Item时切换选中状态
                            onTap: () {
                              setState(() {
                                newSyList(index)![subIndex].check =
                                    !newSyList(index)![subIndex].check!;
                              });
                            },
                            child: newSyList(index)![subIndex].check!
                                ? Stack(
                                    children: [
                                      Container(
                                        decoration: BoxDecoration(
                                          color: Colors.blue[100],
                                          borderRadius:
                                              BorderRadius.circular(3),
                                        ),
                                        alignment: Alignment.center,
                                        child: Text(
                                          newSyList(index)![subIndex].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(
                                      newSyList(index)![subIndex].name!,
                                      style: const TextStyle(
                                          fontSize: 12, color: Colors.black),
                                    ),
                                  ),
                            // child: Container(
                            //   decoration: BoxDecoration(
                            //     color: newSyList(index)![subIndex].check!
                            //         ? Colors.blue[50]
                            //         : Colors.transparent,
                            //     border: Border.all(
                            //         color: newSyList(index)![subIndex].check!
                            //             ? Colors.blue
                            //             : ColorConst.greyD2Color,
                            //         width: 1),
                            //     borderRadius: BorderRadius.circular(3),
                            //   ),
                            //   alignment: Alignment.center,
                            //   child: Text(
                            //     newSyList(index)![subIndex].name!,
                            //     style: TextStyle(
                            //         fontSize: 12,
                            //         color: newSyList(index)![subIndex].check!
                            //             ? Colors.blue
                            //             : Colors.black),
                            //   ),
                            // ),
                          );
                        },
                      ),
                    ],
                    if (newScList(index)!.isNotEmpty) ...[
                      Container(
                          margin: const EdgeInsets.only(
                              left: 10, right: 10, top: 5),
                          child: const Text('生产单位',
                              style: TextStyle(fontWeight: FontWeight.bold))),
                      GridView.builder(
                        itemCount: newScList(index) != null
                            ? newScList(index)!.length
                            : 0,
                        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 subIndex) {
                          return GestureDetector(
                            // 点击每个Grid Item时切换选中状态
                            onTap: () {
                              setState(() {
                                newScList(index)![subIndex].check =
                                    !newScList(index)![subIndex].check!;
                              });
                            },
                            child: newScList(index)![subIndex].check!
                                ? Stack(
                                    children: [
                                      Container(
                                        decoration: BoxDecoration(
                                          color: Colors.orange[100],
                                          borderRadius:
                                              BorderRadius.circular(3),
                                        ),
                                        alignment: Alignment.center,
                                        child: Text(
                                          newScList(index)![subIndex].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(
                                      newScList(index)![subIndex].name!,
                                      style: const TextStyle(
                                          fontSize: 12, color: Colors.black),
                                    ),
                                  ),
                            // child: Container(
                            //   decoration: BoxDecoration(
                            //     color: newScList(index)![subIndex].check!
                            //         ? Colors.orange[50]
                            //         : Colors.transparent,
                            //     border: Border.all(
                            //         color: newScList(index)![subIndex].check!
                            //             ? Colors.orange
                            //             : ColorConst.greyD2Color,
                            //         width: 1),
                            //     borderRadius: BorderRadius.circular(3),
                            //   ),
                            //   alignment: Alignment.center,
                            //   child: Text(
                            //     newScList(index)![subIndex].name!,
                            //     style: TextStyle(
                            //         fontSize: 12,
                            //         color: newScList(index)![subIndex].check!
                            //             ? Colors.orange
                            //             : Colors.black),
                            //   ),
                            // ),
                          );
                        },
                      ),
                    ]
                  ],
                ),
              ),
            ],

            // GridViewAQZJList(
            //     equipmentSYBoList:
            //         allRolesList[index].officeDtoSYList,
            //     equipmentSCBoList:
            //         allRolesList[index].officeDtoSCList,
            //     isVisbliy: allRolesList[index].isChecked)
          ],
        );
      },
      itemCount: newList.length,
      separatorBuilder: (BuildContext context, int index) {
        return const SizedBox(
          height: 0,
        );
      },
    );
  }

  ///用户修改
  ListView buildEditListView() {
    return ListView.separated(
      shrinkWrap: true,
      padding: const EdgeInsets.only(top: 0, bottom: 0),
      physics: const NeverScrollableScrollPhysics(),
      itemBuilder: (BuildContext context, int index) {
        return Column(
          children: [
            GestureDetector(
              onTap: () {
                setState(() {
                  if (!roleNames().contains('公司账户')) {
                    if (editList!.roleDtoList![index].name == '公司账户') {
                      editList!.roleDtoList![index].check = false;
                    } else {
                      editList!.roleDtoList![index].check =
                          !editList!.roleDtoList![index].check!;
                    }

                    ///如果取消身份勾选，将当前身份下的已选中设备全部取消勾选
                    if (!editList!.roleDtoList![index].check!) {
                      for (var item
                          in editList!.roleDtoList![index].userDtoList!) {
                        item.check = false;
                      }
                    }
                  }
                });
              },
              child: Padding(
                padding: const EdgeInsets.only(
                    left: 0, top: 10, bottom: 0, right: 10),
                child: Row(
                  children: <Widget>[
                    if (roleNames().contains('公司账户')) ...[
                      Container(
                        margin: const EdgeInsets.only(left: 0),
                        width: 21,
                        height: 21,
                        child: Transform.scale(
                          scale: 0.8,
                          child: Checkbox(
                              value:
                                  editList!.roleDtoList![index].name == '公司账户'
                                      ? true
                                      : false,
                              // 指定复选框的状态
                              onChanged: null,
                              side: MaterialStateBorderSide.resolveWith(
                                (Set<MaterialState> states) {
                                  //修改默认时边框颜色为绿色
                                  return const BorderSide(
                                      width: 2, color: Colors.black12);
                                },
                              )),
                        ),
                      ),
                      Text(editList!.roleDtoList![index].name!, // 设置外层角色文本内容
                          style: TextStyle(
                              fontSize: 14,
                              color:
                                  editList!.roleDtoList![index].name == '公司账户'
                                      ? Colors.black54
                                      : Colors.grey[400],
                              fontWeight: FontWeight.bold)),
                    ] else ...[
                      Container(
                        margin: const EdgeInsets.only(left: 0),
                        width: 21,
                        height: 21,
                        child: Transform.scale(
                          scale: 0.8,
                          child: Checkbox(
                              value:
                                  editList!.roleDtoList![index].name == '公司账户'
                                      ? false
                                      : editList!.roleDtoList![index].check!,
                              // 指定复选框的状态
                              onChanged: editList!.roleDtoList![index].name ==
                                      '公司账户'
                                  ? null
                                  : (value) {
                                      setState(() {
                                        editList!.roleDtoList![index].check =
                                            value!; // 更新 isChecked 的状态值
                                      });
                                    },
                              side: MaterialStateBorderSide.resolveWith(
                                (Set<MaterialState> states) {
                                  //修改默认时边框颜色为绿色
                                  return editList!.roleDtoList![index].name ==
                                          '公司账户'
                                      ? const BorderSide(
                                          width: 2, color: Colors.black12)
                                      : null;
                                },
                              )),
                        ),
                      ),
                      Text(editList!.roleDtoList![index].name!, // 设置外层角色文本内容
                          style: TextStyle(
                              fontSize: 14,
                              color:
                                  editList!.roleDtoList![index].name == '公司账户'
                                      ? Colors.grey[400]
                                      : Colors.black54,
                              fontWeight: FontWeight.bold)),
                    ],
                  ],
                ),
              ),
            ),
            if (editList!.roleDtoList![index].check! &&
                editList!.roleDtoList![index].userDtoList!.isNotEmpty) ...[
              Container(
                margin: const EdgeInsets.only(top: 10),
                padding: const EdgeInsets.only(top: 5),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(5.0),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    if (userDtoSyList(index)!.isNotEmpty) ...[
                      Container(
                          margin: const EdgeInsets.only(left: 10, right: 10),
                          child: const Text('使用单位',
                              style: TextStyle(fontWeight: FontWeight.bold))),
                      GridView.builder(
                        itemCount: userDtoSyList(index) != null
                            ? userDtoSyList(index)!.length
                            : 0,
                        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 subIndex) {
                          return GestureDetector(
                            // 点击每个Grid Item时切换选中状态
                            onTap: () {
                              setState(() {
                                userDtoSyList(index)![subIndex].check =
                                    !userDtoSyList(index)![subIndex].check!;
                              });
                            },
                            child: userDtoSyList(index)![subIndex].check!
                                ? Stack(
                                    children: [
                                      Container(
                                        decoration: BoxDecoration(
                                          color: Colors.blue[100],
                                          borderRadius:
                                              BorderRadius.circular(3),
                                        ),
                                        alignment: Alignment.center,
                                        child: Text(
                                          userDtoSyList(index)![subIndex].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(
                                      userDtoSyList(index)![subIndex].name!,
                                      style: const TextStyle(
                                          fontSize: 12, color: Colors.black),
                                    ),
                                  ),
                          );
                        },
                      ),
                    ],
                    if (userDtoScList(index)!.isNotEmpty) ...[
                      Container(
                          margin: const EdgeInsets.only(left: 10, right: 10),
                          child: const Text('生产单位',
                              style: TextStyle(fontWeight: FontWeight.bold))),
                      GridView.builder(
                        itemCount: userDtoScList(index) != null
                            ? userDtoScList(index)!.length
                            : 0,
                        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 subIndex) {
                          return GestureDetector(
                            // 点击每个Grid Item时切换选中状态
                            onTap: () {
                              setState(() {
                                userDtoScList(index)![subIndex].check =
                                    !userDtoScList(index)![subIndex].check!;
                              });
                            },
                            child: userDtoScList(index)![subIndex].check!
                                ? Stack(
                                    children: [
                                      Container(
                                        decoration: BoxDecoration(
                                          color: Colors.orange[100],
                                          borderRadius:
                                              BorderRadius.circular(3),
                                        ),
                                        alignment: Alignment.center,
                                        child: Text(
                                          userDtoScList(index)![subIndex].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(
                                      userDtoScList(index)![subIndex].name!,
                                      style: const TextStyle(
                                          fontSize: 12, color: Colors.black),
                                    ),
                                  ),
                          );
                        },
                      ),
                    ],
                  ],
                ),
              ),
            ],
          ],
        );
      },
      itemCount: editList!.roleDtoList!.length,
      separatorBuilder: (BuildContext context, int index) {
        return const SizedBox(
          height: 0,
        );
      },
    );
  }

  List<UserDtoLists>? userDtoSyList(int index) {
    List<UserDtoLists>? userDtoList = [];
    for (var syItem in editList!.roleDtoList![index].userDtoList!) {
      if (syItem.unitType == '1') {
        userDtoList.add(syItem);
      }
    }
    return userDtoList;
  }

  List<UserDtoLists>? userDtoScList(int index) {
    List<UserDtoLists>? userDtoList = [];
    for (var syItem in editList!.roleDtoList![index].userDtoList!) {
      if (syItem.unitType == '2') {
        userDtoList.add(syItem);
      }
    }
    return userDtoList;
  }

  List<UserNewDtoList>? newSyList(int index) {
    List<UserNewDtoList>? userDtoList = [];
    for (var syItem in newList[index].userDtoList!) {
      if (syItem.unitType == '1') {
        userDtoList.add(syItem);
      }
    }
    return userDtoList;
  }

  List<UserNewDtoList>? newScList(int index) {
    List<UserNewDtoList>? userDtoList = [];
    for (var syItem in newList[index].userDtoList!) {
      if (syItem.unitType == '2') {
        userDtoList.add(syItem);
      }
    }
    return userDtoList;
  }

  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: Text(
                    titleText()!,
                    style: const 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)),
                  )),
              Text(
                subTitleText()!,
                style: const TextStyle(fontSize: 12, color: Colors.white),
              ),
            ],
          ),
        ],
      ),
    );
  }

  String? titleText() {
    if (type == '1') {
      return '新建用户';
    } else {
      return '修改用户';
    }
  }

  String? subTitleText() {
    if (type == '1') {
      return '我们将根据您填写的内容来为您【新建用户】';
    } else {
      return '我们将根据您填写的内容来为您【修改用户】';
    }
  }

  ///提交任务
  Container buildSubmit() {
    return Container(
        margin: const EdgeInsets.only(top: 10, bottom: 10),
        child: GradientButton(
            tapCallback: () {
              if (nameText!.text.isEmpty) {
                nameFocusNode!.requestFocus();
                ToastUtils.showCenter('请填写姓名');
                return;
              }
              if (loginNameText!.text.isEmpty) {
                loginNameFocusNode!.requestFocus();
                ToastUtils.showCenter('请填写登录名');
                return;
              }
              if (!StringUtils.isValidLoginName(loginNameText!.text)) {
                loginNameFocusNode!.requestFocus();
                ToastUtils.showCenter('登录名支持 11位手机号码 或 6-20位数字+字母组合');
                return;
              }

              if (type == '1') {
                if (passwordText!.text.isEmpty) {
                  passwordFocusNode!.requestFocus();
                  ToastUtils.showCenter('请填写密码');
                  return;
                }
                if (!StringUtils.isValidPassword(passwordText!.text)) {
                  passwordFocusNode!.requestFocus();
                  ToastUtils.showCenter(
                      '密码至少包含以下 3 种类别：大写字母、小写字母、数字、特殊符号、8-20位');
                  return;
                }
                if (okPasswordText!.text.isEmpty) {
                  okPasswordFocusNode!.requestFocus();
                  ToastUtils.showCenter('请填写确认密码');
                  return;
                }
                if (passwordText!.text != okPasswordText!.text) {
                  ToastUtils.showCenter('两次密码不一致，请重新输入');
                  return;
                }
              } else {
                if (passwordText!.text.isNotEmpty) {
                  if (!StringUtils.isValidPassword(passwordText!.text)) {
                    passwordFocusNode!.requestFocus();
                    ToastUtils.showCenter(
                        '密码至少包含以下 3 种类别：大写字母、小写字母、数字、特殊符号、8-20位');
                    return;
                  }
                  if (okPasswordText!.text.isEmpty) {
                    okPasswordFocusNode!.requestFocus();
                    ToastUtils.showCenter('请填写确认密码');
                    return;
                  }
                  if (passwordText!.text != okPasswordText!.text) {
                    ToastUtils.showCenter('两次密码不一致，请重新输入');
                    return;
                  }
                }
              }

              if (moblieText!.text.isEmpty) {
                moblieFocusNode!.requestFocus();
                ToastUtils.showCenter('请填写手机号码');
                return;
              }

              ///新建
              if (type == '1') {
                //判断至少选中一个【用户身份】
                bool isChecked = false;
                for (var item in newList) {
                  if (item.check!) {
                    isChecked = true;
                    break;
                  }
                }
                if (!isChecked) {
                  ToastUtils.showCenter('请选择用户身份');
                  return;
                }

                for (var allItem in newList) {
                  var userDtoLists = allItem.userDtoList!;
                  if (userDtoLists.isNotEmpty) {
                    if (allItem.check!) {
                      bool isDevice = false;
                      for (var scItem in userDtoLists) {
                        if (scItem.check!) {
                          isDevice = true;
                          break;
                        }
                      }
                      if (!isDevice) {
                        ToastUtils.showCenter('请选择【${allItem.name}】需要负责的设备/类型');
                        return;
                      }
                    }
                  }
                }

                UnitRigisterBo? user = UnitRigisterBo();
                user.name = nameText!.text; //姓名
                user.loginName = loginNameText!.text; //登录名
                user.password = okPasswordText!.text; //密码
                user.newPassword = okPasswordText!.text; //密码
                user.mobile = moblieText!.text; //手机号码
                //选中角色需要提交的内容
                List<UserRoleList>? roleLists = [];
                roleLists.clear();
                //选中设备需要提交的内容
                List<UserDtoList>? userDtoList = [];
                userDtoList.clear();

                for (var allItem in newList) {
                  if (allItem.check!) {
                    UserRoleList role = UserRoleList();
                    role.id = allItem.roleId!;
                    roleLists.add(role);

                    var userLists = allItem.userDtoList!;
                    if (userLists.isNotEmpty) {
                      //使用单位：设备
                      for (var item in userLists) {
                        if (item.check!) {
                          UserDtoList userDto = UserDtoList();
                          userDto.roleId = allItem.roleId;
                          userDto.deviceTypeId = item.deviceTypeId;
                          userDtoList.add(userDto);
                        }
                      }
                    }
                  }
                }
                user.userRoleList = roleLists; //角色赋值
                user.userDtoList = userDtoList; //设备赋值
                print(jsonEncode(user));
                HttpUtils.getUserSaveApp(context, user).then((value) {
                  if (value == null) {
                    return;
                  }
                  if (mounted) {
                    setState(() {
                      Get.back(result: true);
                    });
                  }
                });
              } else {
                ///修改
                //判断至少选中一个【用户身份】
                bool isUser = false;
                List<RoleDtoLists>? roleDtoList = editList!.roleDtoList;
                for (var item in roleDtoList!) {
                  if (item.check!) {
                    isUser = true;
                    break;
                  }
                }
                if (!isUser) {
                  ToastUtils.showCenter('请选择用户身份');
                  return;
                }
                for (var allItem in roleDtoList) {
                  var userDtoLists = allItem.userDtoList!;
                  if (userDtoLists.isNotEmpty) {
                    if (allItem.check!) {
                      bool isDevice = false;
                      for (var userItem in userDtoLists) {
                        if (userItem.check!) {
                          isDevice = true;
                          break;
                        }
                      }
                      if (!isDevice) {
                        ToastUtils.showCenter('请选择【${allItem.name}】需要负责的设备/类型');
                        return;
                      }
                    }
                  }
                }

                UnitRigisterBo? user = UnitRigisterBo();
                user.id = editList!.id;
                user.name = nameText!.text; //姓名
                user.oldLoginName = loginNameText!.text; //姓名
                user.loginName = loginNameText!.text; //登录名
                user.newPassword = okPasswordText!.text; //密码
                user.mobile = moblieText!.text; //手机号码
                //选中角色需要提交的内容
                List<UserRoleList>? roleLists = [];
                roleLists.clear();
                //选中设备需要提交的内容
                List<UserDtoList>? userDtoList = [];
                userDtoList.clear();

                for (var allItem in roleDtoList) {
                  if (allItem.check!) {
                    UserRoleList role = UserRoleList();
                    role.id = allItem.roleId!;
                    roleLists.add(role);

                    var userDtoLists = allItem.userDtoList!;
                    if (userDtoLists.isNotEmpty) {
                      //使用单位：设备
                      for (var deviceItem in userDtoLists) {
                        if (deviceItem.check!) {
                          UserDtoList userDto = UserDtoList();
                          userDto.roleId = allItem.roleId;
                          userDto.deviceTypeId = deviceItem.deviceTypeId;
                          userDtoList.add(userDto);
                        }
                      }
                    }
                  }
                }
                user.userRoleList = roleLists; //角色赋值
                user.userDtoList = userDtoList; //设备赋值
                print(jsonEncode(user));
                HttpUtils.getUserSaveApp(context, user).then((value) {
                  if (value == null) {
                    return;
                  }
                  if (mounted) {
                    setState(() {
                      ToastUtils.showCenter('提交成功');
                      Get.back(result: true);
                    });
                  }
                });
              }
            },
            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),
            )));
  }
}
