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/device_bo.dart';
import 'package:special_equipment_flutter/model/device_list_bo.dart';
import 'package:special_equipment_flutter/model/sy_device_list_bo.dart';
import 'package:special_equipment_flutter/model/user_list.dart';
import 'package:special_equipment_flutter/ui/common/data.dart';
import 'package:special_equipment_flutter/utils/storage_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 EquipmentSettingsPage extends StatefulWidget {
  ///type=1:新建、type=2:修改、type=3:查看
  var arguments = Get.arguments;

  EquipmentSettingsPage({super.key});

  @override
  State<EquipmentSettingsPage> createState() => _EquipmentSettingsPageState();
}

class _EquipmentSettingsPageState extends State<EquipmentSettingsPage> {
  TextEditingController? unitText = TextEditingController();
  FocusNode? unitFocusNode = FocusNode();
  TextEditingController? typeText = TextEditingController();
  FocusNode? typeFocusNode = FocusNode();
  TextEditingController? nameText = TextEditingController();
  FocusNode? nameFocusNode = FocusNode();
  TextEditingController? codeText = TextEditingController();
  FocusNode? codeFocusNode = FocusNode();
  TextEditingController? personText = TextEditingController();
  FocusNode? personFocusNode = FocusNode();
  TextEditingController? addressText = TextEditingController();
  FocusNode? addressFocusNode = FocusNode();

  ///type=1:新建、type=2:修改、type=3:查看
  var type = '';
  List<Data> equipmentSYBoList = [];
  List<RowUserLists> userList = [];
  RowLists? listItem;
  String? deviceId = '', personId = '', id = '';

  @override
  void initState() {
    super.initState();
    type = widget.arguments['type'];

    ///修改 2  查看 3
    if (type == '2' || type == '3') {
      listItem = widget.arguments['listItem'];
      //设备类型
      typeText!.text = listItem!.deviceType!.name!;
      nameText!.text = listItem!.name!;
      codeText!.text = listItem!.code!;
      personText!.text = listItem!.user!.name!;
      addressText!.text = listItem!.address!;
      deviceId = listItem!.deviceType!.id;
      personId = listItem!.user!.id!;
      id = listItem!.id!;
    }
    unitText!.text = StorageUtil.getInstance().getOfficeName();
    getDeviceData();
  }

  getDeviceData() async {
    ///使用单位
    HttpUtils.doDeviceList(context, '1', '1', onSuccess: (value) {
      DeviceListBo deviceListBo = value;
      if (mounted) {
        setState(() {
          equipmentSYBoList.addAll(deviceListBo.data!);
        });
      }
    });
    // HttpUtils.getSCDeviceList(context, '1', '1').then((value) {
    //   ScDeviceListBo listBo = value;
    //   if (mounted) {
    //     setState(() {
    //       equipmentSYBoList.addAll(listBo.body!.data!);
    //     });
    //   }
    // });
    HttpUtils.getUserList(context, '1').then((value) {
      UserList listBo = value;
      if (mounted) {
        setState(() {
          userList.addAll(listBo.rows!);
        });
      }
    });
  }

  @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(),
                      if (type != '3') ...[
                        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>[
              Column(
                children: [
                  const SizedBox(height: 5),
                  TitleWidget(
                      type: type,
                      image1: null,
                      image2: Icons.location_city,
                      title: '所属单位',
                      subText: '*'),
                  const SizedBox(height: 5),
                  CustomTextField(
                      enabled: false,
                      readOnly: false,
                      hintText: '',
                      controller: unitText,
                      focusNode: unitFocusNode),
                  const SizedBox(height: 10),
                  TitleWidget(
                      type: type,
                      image1: Icons.touch_app,
                      image2: Icons.account_balance_wallet_rounded,
                      title: '设备类型',
                      subText: '*'),
                  const SizedBox(height: 5),
                  CustomTextField(
                    enabled: type == '3' ? false : true,
                    readOnly: type == '3' ? false : true,
                    hintText: type == '3' ? '' : '请选择设备类型',
                    controller: typeText,
                    focusNode: typeFocusNode,
                    onTop: () {
                      buildTypeShowDialog();
                    },
                  ),
                  const SizedBox(height: 10),
                  Row(children: [
                    Icon(
                        type == '3'
                            ? Icons.contact_page
                            : Icons.drive_file_rename_outline_rounded,
                        color: ColorConst.orangeColor,
                        size: 15),
                    const Text('设备名称'),
                    const Text('*',
                        style: TextStyle(fontSize: 14, color: Colors.red)),
                  ]),
                  const SizedBox(height: 5),
                  CustomTextField(
                      enabled: type == '3' ? false : true,
                      readOnly: false,
                      hintText: type == '3' ? '' : '请填写设备名称',
                      controller: nameText,
                      focusNode: nameFocusNode),
                  const SizedBox(height: 10),
                  Row(children: [
                    Icon(
                        type == '3'
                            ? Icons.pin
                            : Icons.drive_file_rename_outline_rounded,
                        color: ColorConst.orangeColor,
                        size: 15),
                    const Text("内部编码"),
                    const Text('*',
                        style: TextStyle(fontSize: 14, color: Colors.red)),
                  ]),
                  const SizedBox(height: 5),
                  CustomTextField(
                      enabled: type == '3' ? false : true,
                      readOnly: false,
                      hintText: type == '3' ? '' : '请填写内部编码',
                      controller: codeText,
                      focusNode: codeFocusNode,
                      isNoChinese: true),
                  const SizedBox(height: 8),
                  Row(children: [
                    Icon(type == '3' ? Icons.assignment_ind : Icons.touch_app,
                        color: ColorConst.orangeColor, size: 15),
                    const Text('设备负责人'),
                    const Text('*',
                        style: TextStyle(fontSize: 14, color: Colors.red)),
                  ]),
                  const SizedBox(height: 5),
                  CustomTextField(
                    enabled: type == '3' ? false : true,
                    readOnly: type == '3' ? false : true,
                    hintText: type == '3' ? '' : '请选择设备负责人',
                    controller: personText,
                    focusNode: personFocusNode,
                    isNoChinese: true,
                    onTop: () {
                      buildPersionShowDialog();
                    },
                  ),
                  const SizedBox(height: 8),
                  Row(children: [
                    Icon(
                        type == '3'
                            ? Icons.location_on_rounded
                            : Icons.drive_file_rename_outline_rounded,
                        color: ColorConst.orangeColor,
                        size: 15),
                    const Text('设备地址')
                  ]),
                  const SizedBox(height: 5),
                  CustomTextField(
                      enabled: type == '3' ? false : true,
                      readOnly: false,
                      hintText: type == '3' ? '' : '请填写设备地址详细地址',
                      controller: addressText,
                      focusNode: addressFocusNode),
                ],
              )
            ],
          ),
        ],
      ),
    );
  }

  ///设备负责人选择
  Future<dynamic> buildPersionShowDialog() {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('设备负责人列表'),
          content: SizedBox(
            height: 150,
            width: double.maxFinite,
            child: ListView.separated(
              padding: const EdgeInsets.only(top: 0, left: 0, bottom: 0),
              shrinkWrap: true,
              itemCount: userList.length,
              itemBuilder: (BuildContext context, int index) {
                return SizedBox(
                  height: 40,
                  child: TextButton(
                    child: Text(
                      userList[index].name!,
                      style: const TextStyle(color: Colors.black, fontSize: 14),
                    ),
                    onPressed: () {
                      personText!.text = userList[index].name!;
                      personId = userList[index].id;
                      Navigator.of(context).pop();
                    },
                  ),
                );
              },
              separatorBuilder: (BuildContext context, int index) {
                return Divider(color: Colors.grey[30], height: 1);
              },
            ),
          ),
        );
      },
    );
  }

  ///设备类型选择
  Future<dynamic> buildTypeShowDialog() {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('设备列表'),
          content: SizedBox(
            height: 150,
            width: double.maxFinite,
            child: ListView.separated(
              padding: const EdgeInsets.only(top: 0, left: 0, bottom: 0),
              shrinkWrap: true,
              itemCount: equipmentSYBoList.length,
              itemBuilder: (BuildContext context, int index) {
                return SizedBox(
                  height: 40,
                  child: TextButton(
                    child: Text(
                      equipmentSYBoList[index].name!,
                      style: const TextStyle(color: Colors.black, fontSize: 14),
                    ),
                    onPressed: () {
                      typeText!.text = equipmentSYBoList[index].name!;
                      deviceId = equipmentSYBoList[index].deviceTypeId;
                      Navigator.of(context).pop();
                    },
                  ),
                );
              },
              separatorBuilder: (BuildContext context, int index) {
                return Divider(color: Colors.grey[300], height: 1);
              },
            ),
          ),
        );
      },
    );
  }

  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 if (type == '2') {
      return '修改设备';
    } else {
      return '查看设备';
    }
  }

  String? subTitleText() {
    if (type == '1') {
      return '我们将根据您填写的内容来为您【新建设备】';
    } else if (type == '2') {
      return '我们将根据您填写的内容来为您【修改设备】';
    } else {
      return '以下为您的设备信息';
    }
  }

  ///提交任务
  Container buildSubmit() {
    return Container(
        margin: const EdgeInsets.only(top: 10, bottom: 10),
        child: GradientButton(
            tapCallback: () {
              if (typeText!.text.isEmpty) {
                typeFocusNode!.requestFocus();
                ToastUtils.showCenter('请选中设备类型');
                return;
              }
              if (nameText!.text.isEmpty) {
                nameFocusNode!.requestFocus();
                ToastUtils.showCenter('请填写设备名称');
                return;
              }
              if (codeText!.text.isEmpty) {
                codeFocusNode!.requestFocus();
                ToastUtils.showCenter('请填写内部编码');
                return;
              }
              if (personText!.text.isEmpty) {
                personFocusNode!.requestFocus();
                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() {
    DeviceBo deviceBo = DeviceBo();
    DeviceTypes deviceType = DeviceTypes();
    deviceType.id = deviceId;
    deviceBo.deviceType = deviceType;
    Users user = Users();
    user.id = personId;
    if (type == '2') {
      deviceBo.id = id;
    }
    deviceBo.user = user;
    deviceBo.name = nameText!.text;
    deviceBo.code = codeText!.text;
    deviceBo.address = addressText!.text;
    print(jsonEncode(deviceBo));

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