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/view/Home/CurrentDanger.dart';
import 'package:jcs_airport/view/common/base_dropdown_filter.dart';

import 'hiddenDangerAudit/hidden_danger_audit_detail.dart';

///@Description     隐患审核
///@author          helinlin
///@create          2021-09-27 17:04
class HiddenDanger extends StatefulWidget {
  const HiddenDanger();

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

class HiddenDangerState extends BaseDropdownFilterState<HiddenDanger> {
  ///人员范围
  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'},
  ];
  List state = [
    {'title': '全部状态', 'value': ''},
  ];
  List level = [
    {'title': '全部级别', 'value': ''},
  ];
  int scopeSelectIndex = 0;
  int dateSelectIndex = 0;
  int orderTypeSelectIndex = 0;
  int stateSelectIndex = 0;
  int levelSelectIndex = 0;

  Map<String, Object> filterData = {'my': '0', 'dangerState': '', 'dangerLevel': ''};

  Map company = {};
  Map plan = {};

  List<String> auditState = ['dangerSubmit', 'onSiteConfirm', 'leaderConfirm', 'secondConfirm'];
  List<String> reviewState = [
    'governLeaderConfirm',
    'governChargerConfirm',
    'governLeadershipConfirm',
    'governLeaderReviewConfirm',
    'governSecondReviewConfirm'
  ];
  @override
  bool hasFilter = false;

  @override
  String pageTitle() => '监督检查隐患';

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

    ///处理从首页跳转进来的情况
    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 {
          int type = -1; //1,审核 2,复查
          if (auditState.contains(item['dangerState'])) {
            type = 1;
          } else if (reviewState.contains(item['dangerState'])) {
            type = 2;
          }
          await Get.to(HiddenDangerAuditDetail((item['id'] ?? '').toString(), 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),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            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({'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
  List<DropdownMenuBuilderEntity> getDropdownMenuContentEntity() => <DropdownMenuBuilderEntity>[
        DropdownMenuBuilderEntity(scopeSelectIndex, scope),
        DropdownMenuBuilderEntity(stateSelectIndex, state),
        DropdownMenuBuilderEntity(levelSelectIndex, level)
      ];

  @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:
        filterData['dangerState'] = data['value'];
        setState(() {
          stateSelectIndex = index;
        });
        break;
      case 2:
        filterData['dangerLevel'] = data['value'];
        setState(() {
          levelSelectIndex = index;
        });
        break;
    }
    onRefresh();
  }

  Future<void> _getStatus() async {
    var data = await API.dangerState();
    if (data != null) {
      setState(() {
        state.addAll(data.map((item) {
          return {'title': item['name'], 'value': item['key']};
        }).toList());
      });
    }
  }

  Future<void> _getLevel() async {
    var data = await API.dangerLevel();
    if (data != null) {
      setState(() {
        level.addAll(data.map((item) {
          return {'title': item['dictDataValue'], 'value': item['dictDataKey']};
        }).toList());
      });
    }
  }
}
