import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_flutter_utils/date_utils.dart';
import 'package:amos_iot_login_tpl/entity/platform_menu.dart';
import 'package:amos_iot_ui/listItem/list_view_item.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/consts/colors.dart';
import 'package:jcs_airport/consts/styles.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/view/common/common_dropdown_filter.dart';
import 'package:jcs_airport/view/workBench/fireproofSupervision/common/choose_fireproof_Supervision_department.dart';
import 'package:jcs_airport/view/workBench/fireproofSupervision/common/choose_fireproof_Supervision_person.dart';
import 'package:jcs_airport/view/workBench/fireproofSupervision/planCheck/plan_check_point.dart';
import 'package:jcs_airport/view/common/base_dropdown_filter.dart';

///@Description     计划检查
///@author          helinlin
///@create          2021-09-01 9:27
class PlanCheck extends StatefulWidget {
  static String userId = 'userId';
  static String title = '计划检查';
  const PlanCheck({Key key}) : super(key: key);

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

class PlanCheckState<T extends StatefulWidget> extends CommonDropdownFilterState<T> {
  @override
  String pageTitle() => PlanCheck.title;

  ///从首页跳转额外处理
  void processFromHome() {
    PlatformMenu platformMenu = Get.arguments;
    if (platformMenu != null) {
      switch (platformMenu.frontComponent) {
        case 'waitCheck':
          statusSelectIndex = 2;
          filterData['finishStatus'] = 2;
          break;
        case 'timeout':
          statusSelectIndex = 4;
          filterData['finishStatus'] = 4;
          break;
        case 'finished':
          statusSelectIndex = 3;
          filterData['finishStatus'] = 3;
          break;
        case 'supervision':
          scopeSelectIndex = 1;
          break;
      }
    }
  }


  @override
  void initState() {
    super.initState();
    processFromHome();
    getFinishStatus();
    _getOrderBy();
    _userIdentify();
  }

  @override
  void getData() {
    Future.delayed(Duration.zero, () async {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      var data = await API.supervisionQueryPlanTask(filterData..addAll({'pageNumber': page.current, 'pageSize': page.size,'outsideType':1}));
      Get.back();
      if (data != null) {
        if ((data['content'] ?? []).length == 0) {
          refreshController.loadNoData();
          return;
        }
        setState(() {
          dataList.addAll(data['content'].cast<Map<String, Object>>());
        });
      }
      refreshController.refreshCompleted();
      refreshController.loadComplete();
    });
  }

  @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['beginTime']} -- ${item['endTime']}",
        onclick: () async {
          await Get.to(PlanCheckPoint(item['planId'], item['planTaskId'], item['route_id'], item['taskName'],
              item['userId'].toString().contains(PlanCheck.userId), item['finishStatus'] == 1));
          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['taskName'] ?? '').toString(),
                        style: const TextStyle(fontSize: 16),
                      ),
                    ],
                  ),
                ),
                Text(
                  item['finishStatusDesc'].toString(),
                  style: TextStyle(color: AMOSColors.maintenancePlanStatusColor(item['finishStatus'])),
                ),
              ],
            ),
            const SizedBox(
              height: 5,
            ),
            Row(
              children: [
                Expanded(
                  child: Row(
                    children: [
                      const Text('任务批号：'),
                      const SizedBox(
                        width: 5,
                      ),
                      Text((item['batchNo'] ?? '').toString()),
                    ],
                  ),
                ),
                Expanded(
                  child: Row(
                    children: [
                      const Text('类型：'),
                      const SizedBox(
                        width: 5,
                      ),
                      Text((item['checkTypeName'] ?? '').toString()),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(
              height: 5,
            ),
            Row(
              children: [
                Expanded(
                  child: Row(
                    children: [
                      const Text('检查单位：'),
                      const SizedBox(
                        width: 5,
                      ),
                      Text((item['finishNum'] ?? '').toString()),
                    ],
                  ),
                ),
                Expanded(
                  child: Row(
                    children: [
                      const Text('剩余：'),
                      const SizedBox(
                        width: 5,
                      ),
                      Text((item['waitNum'] ?? 0).toString()),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(
              height: 5,
            ),
            Row(
              children: [
                Row(
                  children: [
                    const Text('执行人：'),
                    const SizedBox(
                      width: 5,
                    ),
                    Text(item['userName'] ?? ''),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  @override
  Future<void> onFilterTap() async {
    //暂存一下起始时间
    String startDate = filterData['startTime'];
    String endDate = filterData['endTime'];
    await Get.to(Filter(filterData, chooseDepartment, choosePerson));
    print(filterData);
    if (startDate != filterData['startTime'] || endDate != filterData['endTime']) {
      setState(() {
        dateSelectIndex = 0;
      });
    }
    if (choosePerson != null && choosePerson['bizOrgName'] != null) {
      setState(() {
        scopeSelectIndex = 0;
      });
    }
    onRefresh();
  }

  Future<void> getFinishStatus() async {
    var data = await API.supervisionPlanTaskFinishStatus();
    if (data != null) {
      data.forEach((element) {
        status.add({'title': element['name'], 'value': element['value']});
      });
    }
    setState(() {});
  }

  Future<void> _getOrderBy() async {
    var data = await API.supervisionPlanTaskOrderBy();
    if (data != null) {
      data.forEach((element) {
        orderType.add({'title': element.values.first, 'value': element.keys.first});
      });
    }
    setState(() {});
  }

  Future<void> _userIdentify() async {
    var data = await API.supervisionUserIdentify();
    if (data != null) {
      setState(() {
        PlanCheck.userId = data['personSeq'];
        scope.add({'title': '我的', 'value': data['personSeq']});
      });
    }
  }
}

///筛选页面
class Filter extends StatefulWidget {
  final Map<String, Object> filterData;
  final Map chooseDepartment;
  final Map choosePerson;

  const Filter(this.filterData, this.chooseDepartment, this.choosePerson);

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

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

  @override
  void initState() {
    super.initState();
    typeController.text = widget.filterData['checkTypeName'] ?? '';
    _getCheckType();
  }

  @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,
                    ),
                    FormItem(
                        layout: FormLayout.vertical,
                        label: '开始日期',
                        formfield: InputDatePicker(
                          onChange: (val) {
                            setState(() {
                              widget.filterData['startTime'] = DateUtils.formatDate(val, format: 'yyyy-MM-dd HH:mm:ss');
                            });
                          },
                          value: widget.filterData['startTime'] ?? '',
                        )),
                    const SizedBox(
                      height: 10,
                    ),
                    FormItem(
                        layout: FormLayout.vertical,
                        label: '结束日期',
                        formfield: InputDatePicker(
                          onChange: (val) {
                            setState(() {
                              widget.filterData['endTime'] = DateUtils.formatDate(val, format: 'yyyy-MM-dd HH:mm:ss');
                            });
                          },
                          value: widget.filterData['endTime'] ?? '',
                        )),
                    const SizedBox(
                      height: 10,
                    ),
                    Column(
                      children: [
                        FormItem(
                            layout: FormLayout.vertical,
                            label: '检查人员:',
                            formfield: SelectFormNewPage(
                                value: widget.filterData['userName'] ?? '',
                                selectPage: ChooseFireproofSupervisionPerson(
                                  person: widget.choosePerson,
                                ),
                                onChanged: (val) {
                                  if (val != null) {
                                    setState(() {
                                      widget.choosePerson.addAll(val);
                                      widget.filterData['userName'] = val['bizOrgName'];
                                      widget.filterData['userId'] = val['sequenceNbr'];
                                    });
                                  }
                                })),
                        const SizedBox(
                          height: 10,
                        ),
                        FormItem(
                            layout: FormLayout.vertical,
                            label: '被检查单位:',
                            formfield: SelectFormNewPage(
                                value: widget.filterData['companyName'] ?? '',
                                selectPage: ChooseFireproofSupervisionDepartment(widget.chooseDepartment),
                                onChanged: (val) {
                                  if (val != null) {
                                    setState(() {
                                      widget.chooseDepartment.addAll(val);
                                      widget.filterData['companyName'] = val['bizOrgName'];
                                      widget.filterData['companyId'] = val['sequenceNbr'];
                                    });
                                  }
                                })),
                        const SizedBox(
                          height: 10,
                        ),
                        GestureDetector(
                          child: Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 15),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text('检查类型：'),
                                const SizedBox(
                                  height: 5,
                                ),
                                TextField(
                                  controller: typeController,
                                  enabled: false,
                                  style: const TextStyle(fontSize: CoreStyles.textSizeSmall),
                                  decoration: InputDecoration(
                                    filled: true,
                                    fillColor: FormStyles.CONTENT_COLOR,
                                    border: InputBorder.none,
                                    suffixIcon: Transform.translate(
                                      offset: const Offset(5, 0),
                                      child: const Icon(
                                        Icons.arrow_right,
                                        color: Colors.black87,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          onTap: () {
                            showCheckType(context);
                          },
                        ),
                      ],
                    ),
                  ],
                ),
              )),
            ),
            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.filterData.clear();
                        typeController.text = '';
                      });
                    },
                    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),
                    ),
                  )),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void showCheckType(BuildContext context) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return SimpleDialog(
            contentPadding: const EdgeInsets.symmetric(vertical: 10),
            children: checkType
                .map((element) => Column(
                      children: [
                        SimpleDialogOption(
                          child: Center(child: Text(element['name'])),
                          onPressed: () {
                            widget.filterData['taskType'] = element['code'];
                            widget.filterData['checkTypeName'] = element['name'];
                            typeController.text = element['name'];
                            Get.back();
                          },
                        ),
                        const Divider(
                          height: 1,
                        ),
                      ],
                    ))
                .toList(),
          );
        });
  }

  Future<void> _getCheckType() async {
    var data = await API.supervisionPlanTaskCheckType();
    if (data != null) {
      setState(() {
        checkType.addAll(data);
      });
    }
  }
}
