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/unit_rigister_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/widgets/app_bar/custom_app_bar.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';

///用户列表
class UserListPage extends StatefulWidget {
  const UserListPage({super.key});

  @override
  State<UserListPage> createState() => _UserListPageState();
}

class _UserListPageState extends State<UserListPage> {
  final EasyRefreshController _controller = EasyRefreshController();
  List<RowUserLists> list = [];

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBarCustom(text: '用户列表', height: 50),
      body: Stack(
        children: [
          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.USER_SETTINGS,
                            arguments: {'type': '1'})?.then((value) {
                          if (value != null && value) {
                            getData();
                          }
                        });
                      },
                      width: 60,
                      height: 60,
                      borderRadius:
                          const BorderRadius.all(Radius.circular(360)),
                      disable: false,
                      colors: const [
                        ColorConst.blueColor,
                        ColorConst.blue1Color
                      ],
                      child: const Text(
                        "新建\n用户",
                        style: TextStyle(
                            fontSize: 14, color: ColorConst.whiteColor),
                      ))),
            ),
          ]
        ],
      ),
    );
  }

  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.USER_SETTINGS, arguments: '3');
        },
        child: Card(
          elevation: 2,
          margin: const EdgeInsets.only(left: 0, right: 0, top: 15, bottom: 0),
          color: Colors.white,
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(10)),
          ),
          child: Padding(
            padding:
                const EdgeInsets.only(left: 10, right: 0, top: 15, bottom: 10),
            child: Column(
              children: <Widget>[
                Row(
                  children: [
                    ClipRRect(
                        borderRadius: BorderRadius.circular(5.0),
                        child: Image.asset('assets/home/user_easyico_icon.png',
                            width: 55, height: 55)),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          margin: const EdgeInsets.only(left: 10, bottom: 5),
                          child: Text.rich(TextSpan(children: [
                            const TextSpan(
                                text: '用户名：',
                                style: TextStyle(
                                    fontSize: 13, color: Colors.black)),
                            TextSpan(
                                text: list[index].loginName,
                                style: const TextStyle(
                                    fontSize: 13, color: Colors.black54)),
                          ])),
                        ),
                        Container(
                          margin: const EdgeInsets.only(left: 10, bottom: 5),
                          child: Text.rich(TextSpan(children: [
                            const TextSpan(
                                text: '姓名：',
                                style: TextStyle(
                                    fontSize: 13, color: Colors.black)),
                            TextSpan(
                                text: list[index].name,
                                style: const TextStyle(
                                    fontSize: 13, color: Colors.black54)),
                          ])),
                        ),
                        Container(
                          margin: const EdgeInsets.only(left: 10),
                          child: Text.rich(TextSpan(children: [
                            const TextSpan(
                                text: '用户身份：',
                                style: TextStyle(
                                    fontSize: 13, color: Colors.black)),
                            TextSpan(
                                text: roleNames(index),
                                style: const TextStyle(
                                    fontSize: 13, color: Colors.black54)),
                          ])),
                        )
                      ],
                    )
                  ],
                ),
                const DividerCustom(Colors.transparent, 0, 10, 0, 0),
                if (isUnitRoles(StorageUtil.getInstance().getRoleNames())! ||
                    !isItemRoleNames(roleNames(index))) ...[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      if (!isItemRoleNames(roleNames(index))) ...[
                        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.getUserDetele(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, right: 10),
                          child: GradientButton(
                              tapCallback: () {
                                setState(() {
                                  Get.toNamed(RouteString.USER_SETTINGS,
                                      arguments: {
                                        'type': '2',
                                        'item': 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),
                              ))),
                    ],
                  )
                ]
              ],
            ),
          ),
        ));
  }

  dynamic roleNames(index) {
    String result = "";
    var arrayList = list[index].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;
    }
  }
}
