//巡检任务列表
import 'package:deus_app/common/event/RefreshMaintPage.dart';
import 'package:deus_app/common/style/TitleBar.dart';
import 'package:deus_app/common/utils/ToastUtils.dart';
import 'package:deus_app/main.dart';
import 'package:deus_app/model/maint_pesonse_entity.dart';
import 'package:deus_app/page/maint/maint_job_detail.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../common/style/gsy_style.dart';
import '../../common/utils/ConstantString.dart';
import '../../common/utils/DioUtil.dart';
import '../../widget/MaintJobDrawer.dart';

class MaintJobPage extends StatefulWidget {
  const MaintJobPage({super.key});

  static var routeName = '/MaintJobPage';

  @override
  State createState() {
    return _MaintJobPage();
  }
}

List<MaintJobVO> maint_job_list = <MaintJobVO>[];

int index = 1;

class _MaintJobPage extends State<MaintJobPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  MaintJobList maintJobList = MaintJobList();

  String _device = '', _num = '';
  dynamic _stase;

  var _event;

  _load() async {
    var result = await DioUtil().request('maintJob/list',
        method: DioMethod.post,
        data: {'query': {'jobName':_device,'jobNum':_num,'status':_stase}, 'index': index, 'size': 20});
    _refreshController.loadComplete();
    _refreshController.refreshCompleted();
    MaintJobResponse maintJobResponse = MaintJobResponse.fromJson(result);
    if(maintJobResponse.code==0){
      maintJobList = maintJobResponse.data!;
      setState(() {
        if(index==1){
          maint_job_list.clear();
        }
        maint_job_list.addAll(maintJobList.list!);
      });
    }else{
      if(index>1){
        index--;
      }
      showToast(maintJobResponse.msg!);
    }
  }

  void _onRefresh() async {
    if (mounted) {
      setState(() {
        index = 1;
        _load();
      });
    }
  }

  void _onLoading() async {
    if (mounted) {
      setState(() {
        if (maintJobList.total! > maint_job_list.length) {
          index++;
          _load();
        } else {
          _refreshController.loadNoData();
        }
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _load();
    _event = eventBus.on<RefreshMaintPage>().listen((event) {
      setState(() {
        index=1;
        _load();
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldKey,
        appBar: TitleBar().drawAppBar(ConstantString.maintJobText, () {
          _scaffoldKey.currentState?.openEndDrawer();
        }),
        endDrawer: MaintJobDrawer(
          callback: (String device, String num, dynamic stase) {
            _device = device;
            _num = num;
            _stase = stase;
            index = 1;
            _load();
          },
        ),
        //抽屉
        backgroundColor: const Color(0xfff2f2f2),
        body: maint_job_list.isNotEmpty?Column(
          children: [
            const SizedBox(
              height: 10,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: const [
                SizedBox(
                  width: 15,
                ),
                Text(ConstantString.maintJobTitle,
                    style: GSYConstant.smallActionLightText),
              ],
            ),
            Expanded(
                child: Container(
                    child: SmartRefresher(
                      enablePullDown: true,
                      enablePullUp: true,
                      header: WaterDropHeader(),
                      footer: CustomFooter(
                        builder: (BuildContext context, LoadStatus? mode) {
                          Widget body;
                          if (mode == LoadStatus.idle) {
                            body = Text("上拉加载");
                          } else if (mode == LoadStatus.loading) {
                            body = CupertinoActivityIndicator();
                          } else if (mode == LoadStatus.failed) {
                            body = Text("加载失败！点击重试！");
                          } else if (mode == LoadStatus.canLoading) {
                            body = Text("松手,加载更多!");
                          } else {
                            body = Text("没有更多数据了!");
                          }
                          return Container(
                            height: 55.0,
                            child: Center(child: body),
                          );
                        },
                      ),
                      controller: _refreshController,
                      onRefresh: _onRefresh,
                      onLoading: _onLoading,
                      // child:Expanded(
                      //     child: Container(
                      child: ListView.builder(
                        itemCount: maint_job_list.length,
                        itemBuilder: (context, index) {
                          MaintJobVO maintJobVO = maint_job_list[index];
                          return _maint_job_list(maintJobVO);
                        },
                      ),
                    )))
          ],
        ):Container(
            alignment: Alignment.center,
            child: const Text(
              '暂无数据',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: GSYColors.primaryLightValue,
                fontSize: GSYConstant.middleTextWhiteSize,
              ),
            ),
        )
    );
  }

  Widget _maint_job_list(MaintJobVO maintJobVO) {
    return Container(
        margin: EdgeInsets.only(top: 12, left: 10, right: 10),
        padding: EdgeInsets.only(top: 12, bottom: 10),
        color: Colors.white,
        child: ListTile(
          title: Column(
            children: [
              Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                Container(
                  child: Text(
                    maintJobVO.jobName!,
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: GSYConstant.middleTextWhiteSize,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Container(
                  padding:
                      EdgeInsets.only(top: 3, bottom: 3, left: 5, right: 5),
                  child: Text(
                    maintJobVO.status == 0
                        ? '已关闭'
                        : maintJobVO.status == 1
                            ? '执行中'
                            : maintJobVO.status == 2
                                ? '已完成'
                                : maintJobVO.status == 3
                                    ? '待执行'
                                    : maintJobVO.status == 4
                                        ? '已逾期'
                                        : '未知',
                    textAlign: TextAlign.right,
                    style: TextStyle(
                      color: maintJobVO.status == 0 || maintJobVO.status == 4
                          ? Colors.red
                          :maintJobVO.status == 1|| maintJobVO.status == 3
                              ? Colors.orange
                              : maintJobVO.status == 2
                                  ? Colors.blue
                                  : Colors.black, //边框颜色
                      fontSize: GSYConstant.minTextSize,
                    ),
                  ),
                  decoration: BoxDecoration(
                    border: new Border.all(
                      color: maintJobVO.status == 0 || maintJobVO.status == 4
                          ? Colors.red
                          :maintJobVO.status == 1|| maintJobVO.status == 3
                              ? Colors.orange
                              : maintJobVO.status == 2
                                  ? Colors.blue
                                  : Colors.black, //边框颜色
                      width: 1.0, //边框粗细
                    ),
                    borderRadius: const BorderRadius.all(
                        const Radius.circular(3.0)), //边框的弧度
                  ),
                )
              ]),
              SizedBox(
                height: 12,
              ),
              Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                Container(
                  child: Text(
                    '任务编号:',
                    style: TextStyle(
                      color: GSYColors.primaryLightValue,
                      fontSize: GSYConstant.smallTextSize,
                    ),
                  ),
                ),
                Container(
                  child: Text(
                    maintJobVO.jobNum!,
                    textAlign: TextAlign.right,
                    style: TextStyle(
                      color: GSYColors.primaryLightValue,
                      fontSize: GSYConstant.smallTextSize,
                    ),
                  ),
                ),
              ]),
              SizedBox(
                height: 10,
              ),
              Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                Container(
                  child: Text(
                    '任务开始时间:',
                    style: TextStyle(
                      color: GSYColors.primaryLightValue,
                      fontSize: GSYConstant.smallTextSize,
                    ),
                  ),
                ),
                Container(
                  child: Text(
                    maintJobVO.startTime!,
                    textAlign: TextAlign.right,
                    style: TextStyle(
                      color: GSYColors.primaryLightValue,
                      fontSize: GSYConstant.smallTextSize,
                    ),
                  ),
                ),
              ]),
              SizedBox(
                height: 10,
              ),
              Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                Container(
                  child: Text(
                    '任务结束时间:',
                    style: TextStyle(
                      color: GSYColors.primaryLightValue,
                      fontSize: GSYConstant.smallTextSize,
                    ),
                  ),
                ),
                Container(
                  child: Text(
                    maintJobVO.endTime!,
                    textAlign: TextAlign.right,
                    style: TextStyle(
                      color: GSYColors.primaryLightValue,
                      fontSize: GSYConstant.smallTextSize,
                    ),
                  ),
                ),
              ]),
              SizedBox(
                height: 5,
              ),
            ],
          ),
          onTap: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) =>
                        new MaintJobDetail(id: maintJobVO.id)));
          },
        ));
  }

  @override
  void dispose() {
    super.dispose();
    _event.cancel();
  }
}
