import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:special_equipment_flutter/common/color_const.dart';
import 'package:special_equipment_flutter/common/edgeInsets_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/sy_device_list_bo.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/widgets/custom_button.dart';
import 'package:special_equipment_flutter/widgets/divider_custom.dart';
import 'package:special_equipment_flutter/widgets/emptyI_img_widget.dart';
import 'package:special_equipment_flutter/widgets/first_refresh_widget.dart';

import '../../common/data.dart';

///设备列表（使用单位）
class EquipmentListSYPage extends StatefulWidget {
  const EquipmentListSYPage({super.key});

  @override
  State<EquipmentListSYPage> createState() => _EquipmentListSYPageState();
}

class _EquipmentListSYPageState extends State<EquipmentListSYPage> {
  final EasyRefreshController _controller = EasyRefreshController();
  List<RowLists> list = [];

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

  void getData() {
    HttpUtils.getDeviceList(context, '1').then((value) {
      SyDeviceListBo listBo = value;
      if (mounted) {
        setState(() {
          list.clear();
          list.addAll(listBo.rows!);
          _controller.finishRefresh();
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          margin: const EdgeInsets.only(top: 20),
          child: EasyRefresh(
            firstRefresh: true,
            enableControlFinishRefresh: true,
            // enableControlFinishLoad: true,
            firstRefreshWidget: const FirstRefreshWidget(),
            emptyWidget: list.isEmpty
                ? EmptyImgWidget(
                    title: '暂无数据,点击刷新',
                    onTap: () {
                      getData();
                    })
                : null,
            controller: _controller,
            onRefresh: () async {
              // page = 1;
              getData();
            },
//                onLoad: () async {
//                  page++;
//                  getList();
//                },
            child: buildBody(),
          ),
        ),
        if (isUnitRoles(StorageUtil.getInstance().getRoleNames())!) ...[
          Positioned(
            right: 20,
            bottom: 50,
            child: Card(
                elevation: 5,
                shape: const RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(360)),
                ),
                margin: const EdgeInsets.only(top: 10, bottom: 10),
                child: GradientButton(
                    tapCallback: () {
                      Get.toNamed(RouteString.EQUIPMENT_SETTINGS,
                          arguments: {'type': '1'})?.then((value) {
                        if (value != null && value) {
                          getData();
                        }
                      });
                    },
                    width: 70,
                    height: 70,
                    borderRadius: const BorderRadius.all(Radius.circular(360)),
                    disable: false,
                    colors: const [
                      ColorConst.orangeColor,
                      ColorConst.orange2Color
                    ],
                    child: const Text(
                      "新建\n设备",
                      style:
                          TextStyle(fontSize: 16, color: ColorConst.whiteColor),
                    ))),
          ),
          Container(
            alignment: Alignment.centerLeft,
            height: 25,
            margin: const EdgeInsets.only(left: 10, right: 10, 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,
              '小提示：使用单位需要【新建设备】.',
              style: TextStyle(color: Colors.orange, fontSize: 14),
            ),
          ),
        ]
      ],
    );
  }

  ListView buildBody() {
    return ListView.separated(
      shrinkWrap: true,
      padding: const EdgeInsets.symmetric(
          horizontal: EdgeInsetsConst.padding_horizontal),
      physics: const NeverScrollableScrollPhysics(),
      itemBuilder: (BuildContext context, int index) {
        return buildItem(index, context);
      },
      itemCount: list.length,
      separatorBuilder: (BuildContext context, int index) {
        return const SizedBox(
          height: 0,
        );
      },
    );
  }

  GestureDetector buildItem(int index, BuildContext context) {
    return GestureDetector(
        onTap: () {
          Get.toNamed(RouteString.EQUIPMENT_SETTINGS,
              arguments: {'type': '3', 'listItem': list[index]})?.then((value) {
            if (value != null && value) {
              getData();
            }
          });
        },
        child: Card(
          elevation: 3,
          margin: const EdgeInsets.only(left: 0, right: 0, top: 15, bottom: 0),
          color: Colors.white,
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(5)),
          ),
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  children: [
                    Container(
                      // margin: const EdgeInsets.fromLTRB(0, 10, 0, 0),
                      padding: const EdgeInsets.fromLTRB(10, 1, 10, 2),
                      decoration: BoxDecoration(
                        color: typeColor(list[index].deviceType!.name!),
                        borderRadius: const BorderRadius.only(
                            topLeft: Radius.circular(10),
                            topRight: Radius.circular(3),
                            bottomLeft: Radius.circular(3),
                            bottomRight: Radius.circular(10)),
                      ),
                      child: Text(list[index].deviceType!.name!,
                          style: const TextStyle(
                              fontSize: 13, color: Colors.white)),
                    ),
                    Container(
                      margin: const EdgeInsets.only(left: 10),
                      child: Text(list[index].code!,
                          style: const TextStyle(
                              fontSize: 16,
                              color: Colors.black,
                              fontWeight: FontWeight.bold)),
                    )
                  ],
                ),
                DividerCustom(Colors.grey[400], 10, 0, 0, 0),
                Container(
                  margin: const EdgeInsets.only(top: 5),
                  child: Row(
                    children: [
                      Container(
                          margin: const EdgeInsets.only(top: 3, right: 2),
                          child: const Icon(Icons.chrome_reader_mode,
                              size: 14, color: Colors.black38)),
                      Text.rich(TextSpan(children: [
                        const TextSpan(
                            text: '设备名称：',
                            style:
                                TextStyle(fontSize: 13, color: Colors.black87)),
                        TextSpan(
                            text: list[index].name,
                            style: const TextStyle(
                                fontSize: 13, color: Colors.black54)),
                      ])),
                    ],
                  ),
                ),
                Container(
                  margin: const EdgeInsets.only(top: 5),
                  child: Row(
                    children: [
                      Container(
                          margin: const EdgeInsets.only(top: 3, right: 2),
                          child: const Icon(Icons.location_city,
                              size: 14, color: Colors.black38)),
                      Expanded(
                        child: Text.rich(TextSpan(children: [
                          const TextSpan(
                              text: '设备地址：',
                              style: TextStyle(
                                  fontSize: 13, color: Colors.black87)),
                          TextSpan(
                              text: list[index].address,
                              style: const TextStyle(
                                  fontSize: 13, color: Colors.black54)),
                        ])),
                      ),
                    ],
                  ),
                ),
                Container(
                  margin: const EdgeInsets.only(top: 5),
                  child: Row(
                    children: [
                      Container(
                          margin: const EdgeInsets.only(top: 3, right: 2),
                          child: const Icon(Icons.cloud_done,
                              size: 14, color: Colors.black38)),
                      Text.rich(TextSpan(children: [
                        const TextSpan(
                            text: '类型状态：',
                            style:
                                TextStyle(fontSize: 13, color: Colors.black87)),
                        TextSpan(
                            text: list[index].curType == '1' ? '停用' : '正常',
                            style: TextStyle(
                                fontSize: 13,
                                color: list[index].curType == '1'
                                    ? Colors.red
                                    : Colors.black54)),
                      ])),
                      const SizedBox(width: 10),
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            if (list[index].isChecked!) {
                              list[index].isChecked = false;
                            } else {
                              list[index].isChecked = true;
                            }
                          });
                        },
                        child: Text(
                          list[index].isChecked! ? '...收起' : '...展开',
                          style: const TextStyle(
                              fontSize: 16,
                              color: ColorConst.blueColor,
                              fontWeight: FontWeight.bold),
                        ),
                      )
                    ],
                  ),
                ),
                if (list[index].isChecked!) ...[
                  Container(
                    margin: const EdgeInsets.only(top: 5),
                    child: Row(
                      children: [
                        Container(
                            margin: const EdgeInsets.only(top: 3, right: 2),
                            child: const Icon(Icons.date_range,
                                size: 14, color: Colors.black38)),
                        Text.rich(TextSpan(children: [
                          const TextSpan(
                              text: '日管控初始时间：',
                              style: TextStyle(
                                  fontSize: 13, color: Colors.black87)),
                          TextSpan(
                              text: list[index].dayBeginDate,
                              style: TextStyle(
                                  fontSize: 13,
                                  color: list[index].curType == '1'
                                      ? Colors.red
                                      : Colors.black54)),
                        ])),
                      ],
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(top: 5),
                    child: Row(
                      children: [
                        Container(
                            margin: const EdgeInsets.only(top: 3, right: 2),
                            child: const Icon(Icons.date_range,
                                size: 14, color: Colors.black38)),
                        Text.rich(TextSpan(children: [
                          const TextSpan(
                              text: '周排查初始时间：',
                              style: TextStyle(
                                  fontSize: 13, color: Colors.black87)),
                          TextSpan(
                              text: list[index].weekBeginDate,
                              style: TextStyle(
                                  fontSize: 13,
                                  color: list[index].curType == '1'
                                      ? Colors.red
                                      : Colors.black54)),
                        ])),
                      ],
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(top: 5),
                    child: Row(
                      children: [
                        Container(
                            margin: const EdgeInsets.only(top: 3, right: 2),
                            child: const Icon(Icons.date_range,
                                size: 14, color: Colors.black38)),
                        Text.rich(TextSpan(children: [
                          const TextSpan(
                              text: '月调度初始时间：',
                              style: TextStyle(
                                  fontSize: 13, color: Colors.black87)),
                          TextSpan(
                              text: list[index].monthBeginDate,
                              style: TextStyle(
                                  fontSize: 13,
                                  color: list[index].curType == '1'
                                      ? Colors.red
                                      : Colors.black54)),
                        ])),
                      ],
                    ),
                  )
                ],
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Container(
                        margin: const EdgeInsets.only(top: 10, right: 20),
                        child: GradientButton(
                            tapCallback: () {
                              Get.dialog(AlertDialog(
                                title: const Text("提示"),
                                content: const Text("您确定要删除当前设备吗？"),
                                actionsPadding: const EdgeInsets.only(
                                    left: 0, top: 0, bottom: 10, right: 20),
                                contentPadding: const EdgeInsets.only(
                                    left: 20, top: 0, bottom: 10, right: 20),
                                titlePadding: const EdgeInsets.only(
                                    left: 20, top: 20, bottom: 10, right: 20),
                                shape: const RoundedRectangleBorder(
                                    // 这里设置shape属性
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(5.0))),
                                actions: <Widget>[
                                  TextButton(
                                    child: const Text("取消",
                                        style: TextStyle(fontSize: 16)),
                                    onPressed: () {
                                      Get.back();
                                    },
                                  ),
                                  TextButton(
                                    child: const Text("确定",
                                        style: TextStyle(fontSize: 16)),
                                    onPressed: () {
                                      UnitRigisterBo? user = UnitRigisterBo();
                                      user.id = list[index].id;
                                      HttpUtils.getDeviceDetele(context, user)
                                          .then((value) {
                                        if (value == null) {
                                          return;
                                        }
                                        if (mounted) {
                                          setState(() {
                                            list.removeAt(index);
                                            Get.back();
                                          });
                                        }
                                      });
                                    },
                                  ),
                                ],
                              ));
                            },
                            width: 70,
                            height: 25,
                            borderRadius: const BorderRadius.only(
                                topLeft: Radius.circular(5),
                                topRight: Radius.circular(15),
                                bottomLeft: Radius.circular(15),
                                bottomRight: Radius.circular(5)),
                            disable: false,
                            colors: const [
                              ColorConst.red2BgColor,
                              ColorConst.red1BgColor
                            ],
                            child: const Text(
                              "删除",
                              style: TextStyle(
                                  fontSize: 13, color: ColorConst.whiteColor),
                            ))),
                    Container(
                        margin: const EdgeInsets.only(top: 10),
                        child: GradientButton(
                            tapCallback: () {
                              Get.toNamed(RouteString.EQUIPMENT_SETTINGS,
                                  arguments: {
                                    'type': '2',
                                    'listItem': list[index]
                                  })?.then((value) {
                                if (value != null && value) {
                                  getData();
                                }
                              });
                            },
                            width: 70,
                            height: 25,
                            borderRadius: const BorderRadius.only(
                                topLeft: Radius.circular(5),
                                topRight: Radius.circular(15),
                                bottomLeft: Radius.circular(15),
                                bottomRight: Radius.circular(5)),
                            disable: false,
                            colors: const [ColorConst.greenColor, Colors.green],
                            child: const Text(
                              "修改",
                              style: TextStyle(
                                  fontSize: 13, color: ColorConst.whiteColor),
                            ))),
                  ],
                )
              ],
            ),
          ),
        ));
  }
}
