//巡检任务列表
import 'package:deus_app/common/event/RefreshRepairPage.dart';
import 'package:deus_app/common/style/TitleBar.dart';
import 'package:deus_app/generated/json/repair_bill_list_response_entity_helper.dart';
import 'package:deus_app/main.dart';
import 'package:deus_app/model/repair_bill_list_response_entity.dart';
import 'package:deus_app/page/repair/repair_add_page.dart';
import 'package:deus_app/page/repair/repair_detail.dart';
import 'package:deus_app/widget/RepairJobDrawer.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 '../../common/utils/ToastUtils.dart';

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

  static var routeName = '/RepairPage';

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

List<RepairBillListResponseDataList> patrol_job_list =
    <RepairBillListResponseDataList>[];

class _RepairPage extends State<RepairPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  int index = 1;
  RepairBillListResponseEntity patrolJobResponse =
      RepairBillListResponseEntity();

  dynamic _status;
  String _theme = '';
  String _repNum = '';
  var _event;

  _load() async {
    var result = await DioUtil()
        .request('repair-bill/list', method: DioMethod.post, data: {
      'query': {'theme': _theme, 'repNum': _repNum, 'status': _status},
      'index': index,
      'size': 20
    });
    _refreshController.loadComplete();
    _refreshController.refreshCompleted();
    patrolJobResponse = repairBillListResponseEntityFromJson(
        RepairBillListResponseEntity(), result);
    if (patrolJobResponse.code == 0) {
      setState(() {
        if (index == 1) {
          patrol_job_list.clear();
        }
        patrol_job_list.addAll(patrolJobResponse.data.xList);
      });
    } else {
      if (index > 1) {
        index--;
      }
      showToast(patrolJobResponse.msg!);
    }
  }

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldKey,
        appBar: TitleBar().drawAppBar(ConstantString.repairJobText, () {
          _scaffoldKey.currentState?.openEndDrawer();
        }),
        endDrawer: RepairJobDrawer(
            callback: (String theme, String repNum, dynamic status) {
          setState(() {
            _theme = theme;
            _repNum = repNum;
            _status = status;
            index=1;
            _load();
          });
        }),
        //抽屉
        backgroundColor: const Color(0xfff2f2f2),
        body: patrol_job_list.isNotEmpty?Stack(
          children: [
            Column(children: [
              Expanded(
                  child: Container(
                      margin: EdgeInsets.only(bottom: 50),
                      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: ListView.builder(
                          itemCount: patrol_job_list.length,
                          itemBuilder: (context, index) {
                            RepairBillListResponseDataList patrolJobData =
                            patrol_job_list[index];
                            return _patrol_job_list(patrolJobData);
                          },
                        ),
                      ))),
            ]),
            Positioned(
              left: 0,
              right: 0,
              bottom: 0,
              // flex: 7,
              child: SizedBox(
                height: 50,
                width: double.infinity,
                child: TextButton(
                  onPressed: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                            new RepairAddPage()));
                  },
                  style: ButtonStyle(
                    backgroundColor:
                    MaterialStateProperty.all<Color>(Color(0xFF4875EC)),
                    shape: MaterialStateProperty.all(BeveledRectangleBorder(
                        borderRadius: BorderRadius.circular(0))),
                    foregroundColor:
                    MaterialStateProperty.all<Color>(Colors.white),
                    // padding: MaterialStateProperty.all(EdgeInsets.zero)
                  ),
                  child: const Text(ConstantString.newRepair),
                ),
              ),
            )
          ],
        ): Container(
          alignment: Alignment.center,
          child: const Text(
            '暂无数据',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: GSYColors.primaryLightValue,
              fontSize: GSYConstant.middleTextWhiteSize,
            ),
          ),
        )
    );
  }

  Widget _patrol_job_list(RepairBillListResponseDataList patrolJobData) {
    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(
                    patrolJobData.theme,
                    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(
                    patrolJobData.status == 1
                        ? '待接单'
                        : patrolJobData.status == 2
                            ? '待执行'
                            : patrolJobData.status == 3
                                ? '维修中'
                                : patrolJobData.status == 4
                                    ? '已关闭'
                                    : patrolJobData.status == 5
                                        ? '已完成'
                                        : '未知',
                    textAlign: TextAlign.right,
                    style: TextStyle(
                      color:
                          patrolJobData.status == 1 || patrolJobData.status == 2
                              ? Colors.red
                              : patrolJobData.status == 3
                                  ? Colors.orange
                                  : patrolJobData.status == 4 ||
                                          patrolJobData.status == 5
                                      ? Colors.blue
                                      : Colors.black, //边框颜色
                      fontSize: GSYConstant.minTextSize,
                    ),
                  ),
                  decoration: BoxDecoration(
                    border: new Border.all(
                      color:
                          patrolJobData.status == 1 || patrolJobData.status == 2
                              ? Colors.red
                              : patrolJobData.status == 3
                                  ? Colors.orange
                                  : patrolJobData.status == 4 ||
                                          patrolJobData.status == 5
                                      ? 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(
                    patrolJobData.repNum,
                    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(
                    patrolJobData.deviceName,
                    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(
                    patrolJobData.applicationTime,
                    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(
                    patrolJobData.applicant,
                    textAlign: TextAlign.right,
                    style: TextStyle(
                      color: GSYColors.primaryLightValue,
                      fontSize: GSYConstant.smallTextSize,
                    ),
                  ),
                ),
              ]),
              SizedBox(
                height: 5,
              ),
            ],
          ),
          onTap: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) =>
                        new RepairDetail(id: patrolJobData.id)));
          },
        ));
  }

  void _onRefresh() async {
    if (mounted) {
      setState(() {
        index = 1;
        _load();
      });
    }
  }
  void _onLoading() async {
    if (mounted) {
      setState(() {
        if (patrolJobResponse.data!.total! > patrol_job_list.length) {
          index++;
          _load();
        } else {
          _refreshController.loadNoData();
        }
      });
    }
  }

}
