import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.dart';
import 'package:amos_iot_ui/listItem/list_view_item.dart';
import 'package:base/utils/flutter_toast.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/consts/colors.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/utils/convert_date.dart';
import 'package:jcs_airport/view/Home/CurrentDanger.dart';
import 'package:jcs_airport/view/common/base_dropdown_filter.dart';
import 'package:jcs_airport/view/common/choose_department_jcs_tree.dart';
import 'package:jcs_airport/view/workBench/hiddenDanger/common/check_plan.dart';

import 'hidden_danger_audit_detail.dart';

///@Description     隐患审核
///@author          helinlin
///@create          2021-09-27 17:04
class HiddenDangerAudit extends StatefulWidget {
  ///1,审核 2,复查
  final int type;

  const HiddenDangerAudit(this.type);

  @override
  HiddenDangerAuditState createState() => HiddenDangerAuditState();
}

class HiddenDangerAuditState extends BaseDropdownFilterState<HiddenDangerAudit> {
  ///人员范围
  List<Map> scope = [
    {'title': '我的', 'value': '0'},
    {'title': '全部', 'value': '1'},
  ];

  ///日期区间
  List<Map> date = [
    {'title': '全部时间'},
    {'title': '今天'},
    {'title': '昨天'},
    {'title': '本周'},
    {'title': '上周'},
    {'title': '本月'},
    {'title': '上月'},
  ];

  ///排序规则
  List<Map> orderType = [
    {'title': '倒序', 'value': '1'},
    {'title': '正序', 'value': '0'},
  ];
  int scopeSelectIndex = 0;
  int dateSelectIndex = 0;
  int orderTypeSelectIndex = 0;

  Map<String, Object> filterData = {'order': '1', 'my': '0'};
  Map company = {};
  Map plan = {};

  @override
  String pageTitle() => widget.type == 1 ? '隐患审核' : '隐患复查';

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

    ///处理从首页跳转进来的情况
    try {
      if (Get.arguments is PlatformMenu) {
        PlatformMenu platformMenu = Get.arguments;
        if (platformMenu != null && platformMenu.frontComponent == CurrentDanger.currentSupervisionDangerWaitHandle) {
          filterData['my'] = scope[1]['value'];
          setState(() {
            scopeSelectIndex = 1;
          });
        }
      }
    } catch (e) {
      FlutterToast.toastBottom(e.toString());
    }
  }

  @override
  Widget buildListItem(BuildContext context, int index) {
    Map<String, Object> item = dataList[index];
    ListViewItemModel listViewItemModel = ListViewItemModel(
        hasTitle: false,
        hasState: true,
        stateColor: AMOSColors.fireproofSupervisionPointStatusColor(item['finishStatus']),
        hasFooter: true,
        footer: "编号：${item['businessKey']}",
        onclick: () async {
          await Get.to(HiddenDangerAuditDetail((item['id'] ?? '').toString(), widget.type));
          onRefresh();
        });
    return ListViewItem(
      listViewItemModel: listViewItemModel,
      contentWidget: Padding(
        padding: const EdgeInsets.all(5.0),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  flex: 4,
                  child: Row(
                    children: [
                      Text(
                        (item['dangerName'] ?? '').toString(),
                        style: const TextStyle(fontSize: 16),
                      ),
                    ],
                  ),
                ),
                /* Text(
                  item['finishStatusDesc'].toString(),
                  style: TextStyle(color: AMOSColors.maintenancePlanStatusColor(int.parse(item['dangerType'] ?? 0))),
                ),*/
              ],
            ),
            const SizedBox(
              height: 5,
            ),
            Row(
              children: [
                Expanded(
                  child: Row(
                    children: [
                      const Text('级别：'),
                      const SizedBox(
                        width: 5,
                      ),
                      Text((item['dangerLevelName'] ?? '').toString()),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(
              height: 5,
            ),
            Row(
              children: [
                const Text('状态：'),
                const SizedBox(
                  width: 5,
                ),
                Expanded(
                  child: Text(
                    (item['dangerStateName'] ?? '').toString(),
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                  ),
                ),
              ],
            ),
            const SizedBox(
              height: 5,
            ),
            Row(
              children: [
                Expanded(
                  child: Row(
                    children: [
                      const Text('治理方式：'),
                      const SizedBox(
                        width: 5,
                      ),
                      Text((item['reformTypeName'] ?? '').toString()),
                    ],
                  ),
                ),
                Expanded(
                  child: Row(
                    children: [
                      const Text('时效：'),
                      const SizedBox(
                        width: 5,
                      ),
                      Text((item['overtimeState'] == 0 ? '未逾期' : '逾期').toString()),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  @override
  Future<void> getData() async {
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      var data = await API.dangerAuditList(
          filterData..addAll({'type': widget.type == 1 ? 'audit' : 'review', 'current': page.current + 1, 'size': page.size}));
      refreshController.refreshCompleted();
      refreshController.loadComplete();
      if (data != null) {
        setState(() {
          dataList.addAll(data['records'].cast<Map<String, Object>>());
        });
      }
    }).whenComplete(() => Get.back());
  }

  @override
  Future<void> onFilterTap() async {
    await Get.to(Filter(company, plan));
    filterData.addAll({'planId': plan['id'], 'companyId': company['value']});
    onRefresh();
  }

  @override
  List<DropdownMenuBuilderEntity> getDropdownMenuContentEntity() => <DropdownMenuBuilderEntity>[
        DropdownMenuBuilderEntity(scopeSelectIndex, scope),
        DropdownMenuBuilderEntity(dateSelectIndex, date),
        DropdownMenuBuilderEntity(orderTypeSelectIndex, orderType)
      ];

  @override
  void onDropdownItemChanged({int menuIndex, int index, int subIndex, data}) {
    print('menuIndex:$menuIndex index:$index subIndex:$subIndex data:$data');
    switch (menuIndex) {
      case 0:
        filterData['my'] = data['value'];
        setState(() {
          scopeSelectIndex = index;
        });
        break;
      case 1:
        if (data['title'] != '全部时间') {
          DateRange dateRange = ConvertDate.convertDateTextToRealValue(data['title']);
          filterData['startTime'] = dateRange.startTime;
          filterData['endTime'] = dateRange.endTime;
        } else {
          filterData.remove('startTime');
          filterData.remove('endTime');
        }
        setState(() {
          dateSelectIndex = index;
        });
        break;
      case 2:
        filterData['order'] = data['value'];
        setState(() {
          orderTypeSelectIndex = index;
        });
        break;
    }
    onRefresh();
  }
}

///筛选页面
class Filter extends StatefulWidget {
  final Map company;
  final Map plan;

  const Filter(this.company, this.plan);

  @override
  _FilterState createState() => _FilterState();
}

class _FilterState extends State<Filter> {
  List checkType = [];
  TextEditingController typeController = TextEditingController();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('筛选'),
      ),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
          setState(() {});
        },
        child: Column(
          children: [
            Expanded(
              child: Form(
                  child: SingleChildScrollView(
                child: Column(
                  children: [
                    const SizedBox(
                      height: 10,
                    ),
                    Column(
                      children: [
                        FormItem(
                            layout: FormLayout.vertical,
                            label: '公司:',
                            formfield: SelectFormNewPage(
                                value: widget.company['name'],
                                selectPage: ChooseDepartmentJcsTree(
                                  chooseDepartment: widget.company,
                                ),
                                onChanged: (val) {
                                  if (val != null) {
                                    setState(() {
                                      widget.company.addAll(val);
                                    });
                                  }
                                })),
                        const SizedBox(
                          height: 10,
                        ),
                        FormItem(
                            layout: FormLayout.vertical,
                            label: '计划:',
                            formfield: SelectFormNewPage(
                                value: widget.plan['name'],
                                selectPage: CheckPlan(
                                  plan: widget.plan,
                                ),
                                onChanged: (val) {
                                  if (val != null) {
                                    setState(() {
                                      widget.plan.addAll(val);
                                    });
                                  }
                                })),
                      ],
                    ),
                  ],
                ),
              )),
            ),
            Padding(
              padding: const EdgeInsets.all(15.0),
              child: Row(
                children: [
                  Expanded(
                      child: FlatButton(
                    color: const Color.fromRGBO(242, 246, 249, 1),
                    height: 40,
                    onPressed: () {
                      setState(() {
                        widget.company.clear();
                        widget.plan.clear();
                      });
                    },
                    child: const Text(
                      '重置',
                      style: TextStyle(color: Colors.black87),
                    ),
                  )),
                  const SizedBox(
                    width: 5,
                  ),
                  Expanded(
                      child: FlatButton(
                    color: Theme.of(context).primaryColor,
                    height: 40,
                    onPressed: () {
                      Get.back();
                    },
                    child: const Text(
                      '确定',
                      style: TextStyle(color: Colors.white),
                    ),
                  )),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
