import 'dart:async';
import 'package:amos_iot_login_tpl/mine/offline/color.dart';
import 'package:flutter/material.dart';
import 'package:jcs_airport/routes/routes.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:get/get.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:jcs_airport/view/common/no_data.dart';
import './task_execution.dart';

///@Description     待执行任务
///@author          lixiuming
///@create          2023-11-15 11:00
class PendingTask extends StatefulWidget {
  final String state;
  const PendingTask({ Key key, this.state }) : super(key: key);
  @override
  _PendingTaskState createState() => _PendingTaskState();
}

class _PendingTaskState extends State<PendingTask> with SingleTickerProviderStateMixin{
  List<dynamic> taskList = [];
  int total = 0;
  int current = 1;
  bool isLoadComplete = false;
  bool loading = false;

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

  Future setup() async {
    setState(() {
      loading = true;
      fetchTaskList(widget.state, 1);
      loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('待执行任务' +
              (widget.state == 'inProgress'
                  ? '(进行中)'
                  : widget.state == 'timeout'
                      ? '(已超时)'
                      : '(已完成)')),
          centerTitle: true,
        ),
        backgroundColor: const Color.fromARGB(255, 245, 250, 245),
        // 卡片展示，margin为10px，padding为10ox，白色背景
        body: ModalProgressHUD(
          child: EasyRefresh(
            enableControlFinishRefresh: false,
            enableControlFinishLoad: true,
            firstRefresh: true,
            controller: EasyRefreshController(),
            footer: MaterialFooter(),
            header: MaterialHeader(),
            child: taskList.isNotEmpty ? ListView.builder(
              itemCount: taskList.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                    margin: const EdgeInsets.only(left: 10, right: 10, top: 10),
                    child: Card(
                        elevation: 2,
                        child: ListTile(
                            // trailing: Container(),
                            title: Text(
                              taskList[index]['problem'],
                              style: const TextStyle(
                                height: 2,
                                fontSize: 16.0,
                                color: KColorConstant.floorTitleColor,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            subtitle: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                const Padding(
                                  padding: EdgeInsets.only(top: 10),
                                ),
                                RichText(
                                  text: TextSpan(
                                    children: [
                                      const TextSpan(
                                          text: '进度：        ',
                                          style: TextStyle(
                                              fontSize: 14.0,
                                              color: KColorConstant
                                                  .categoryDefaultColor)),
                                      TextSpan(
                                        text: taskList[index]['status'],
                                        style:
                                            taskList[index]['status'] == '待办'
                                                ? const TextStyle(
                                                    fontSize: 14.0,
                                                    color: Colors.orange)
                                                : const TextStyle(
                                                    fontSize: 14.0,
                                                    color: Colors.green),
                                      )
                                    ],
                                  ),
                                ),
                                const Padding(
                                  padding: EdgeInsets.only(top: 8),
                                ),
                                Text(
                                  '发送时间：' + taskList[index]['issueTime'],
                                  style: const TextStyle(
                                      fontSize: 14.0,
                                      color:
                                          KColorConstant.categoryDefaultColor),
                                ),
                                const Padding(
                                  padding: EdgeInsets.only(top: 8),
                                ),
                                Text(
                                  '内容描述：' + taskList[index]['taskClassfly'],
                                  style: const TextStyle(
                                      fontSize: 14.0,
                                      color:
                                          KColorConstant.categoryDefaultColor),
                                ),
                                const Padding(
                                  padding: EdgeInsets.only(top: 8),
                                ),
                                getOperationButton(taskList[index])
                              ],
                            ),
                            // trailing: new Icon(Icons.keyboard_arrow_right),
                            onTap: () {
                              // preExecute(initData[index].offlinePoint);
                            })));
              },
            ) : const Align(
              alignment: Alignment.center,
              heightFactor: 15,
              child: NoData(),
            ),
            onRefresh: () async {
              fetchTaskList(widget.state, 1);
            },
            onLoad: () async {
              // if (!isLoadComplete) {
                await fetchTaskList(widget.state, current + 1);
              // }
            },
          ),
          inAsyncCall: false,
          // demo of some additional parameters
          opacity: 0.7,
          progressIndicator: const CircularProgressIndicator(),
        ));
  }

  Future<void> fetchTaskList(String status, int pageNumber) async {
    var result = await API.pendingTaskList(status, pageNumber, 50);
    print(result);
    if (result == null) {
      return;
    }
    setState(() {
      result['records'].forEach((item) => {
            item['status'] = item['status'] == '1'
                ? '已办'
                : item['status'] == '0'
                    ? '待办'
                    : '逾期'
          });
      if (pageNumber == 1) {
        taskList = result['records'];
      } else {
        taskList = [...taskList, ...result['records']];
      }
      total = result['total'];
      current = result['current'];
    });
  }

  // 获取操作按钮，进度为“待办”时，显示“执行”按钮，否则显示“详情”按钮
  Widget getOperationButton(Map data) {
    double width = double.infinity;
    double height = 38;
    if (data['status'] == '待办') {
      return Container(
        width: width,
        height: height,
        margin: const EdgeInsets.only(top: 10, bottom: 10),
        child: ElevatedButton(
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(
                  const Color.fromARGB(255, 1, 103, 255)),
              shadowColor: MaterialStateProperty.all(Colors.transparent),
            ),
            child: const Text(
              '执行',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.0,
              ),
            ),
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (context) =>
                  TaskExecution(processInstanceId: data['processInstanceId'], source: data['source'], taskLimitTime: data['taskLimitTime'] )) )
                  .then((value) => value ? setup() : null)
              ;
            }),
      );
    } else {
      return Container(
        width: width,
        height: height,
        margin: const EdgeInsets.only(top: 10, bottom: 10),
        child: ElevatedButton(
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(
                  const Color.fromARGB(255, 255, 255, 255)),
              side: MaterialStateProperty.all(
                const BorderSide(color: Color.fromARGB(255, 191, 191, 191)),
              ),
              shadowColor: MaterialStateProperty.all(Colors.transparent),
            ),
            child: const Text(
              '详情',
              style: TextStyle(
                  color: Color.fromARGB(255, 102, 102, 102), fontSize: 14.0),
            ),
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (context) =>
                  TaskExecution(processInstanceId: data['processInstanceId'], source: data['source']  , taskLimitTime: data['taskLimitTime'] )),)
                  .then((value) => value ? setup() : null);
            }),
      );
    }
  }

  Widget getEmergencyDegree(Map data) {
    return Container();
  }
}
