import 'package:deus_app/common/dialog/CloseTaskDialog.dart';
import 'package:deus_app/common/dialog/ViewDialog.dart';
import 'package:deus_app/common/event/RefreshMaintDetail.dart';
import 'package:deus_app/common/event/RefreshMaintPage.dart';
import 'package:deus_app/common/style/TitleBar.dart';
import 'package:deus_app/common/style/gsy_style.dart';
import 'package:deus_app/common/utils/ConstantString.dart';
import 'package:deus_app/common/utils/ToastUtils.dart';
import 'package:deus_app/main.dart';
import 'package:deus_app/model/maint_job_detail_response.dart';
import 'package:deus_app/page/maint/maint_job_list.dart';
import 'package:flutter/material.dart';

import '../../common/utils/DioUtil.dart';

/**
 * 巡检任务详情页面
 */
class MaintJobDetail extends StatefulWidget {
  var id;

  MaintJobDetail({super.key, @required this.id});

  static var routeName = '/MaintJobDetail';

  @override
  State createState() {
    print(id);
    return new _MaintJobDetail(id);
  }
}

MaintJobDetailData maintJobDetail = MaintJobDetailData();
List<DeviceList> deviceList = <DeviceList>[];
List<ItemsList> itemList = <ItemsList>[];
List<String> fileUrls = <String>[];

class _MaintJobDetail extends State<MaintJobDetail> {
  var id;

  bool type = false;

  var _event;

  _MaintJobDetail(this.id);

  _load() async {
    var result = await DioUtil().request('maintJob/app-detail',
        method: DioMethod.post, params: {'id': id});
    MaintJobDetailResponse maintJobDetailResponse =
        MaintJobDetailResponse.fromJson(result);
    setState(() {
      maintJobDetail = maintJobDetailResponse.data!;
      deviceList.clear();
      deviceList.addAll(maintJobDetail.deviceList!);
      itemList.clear();
      if (null != maintJobDetail.itemsList) {
        itemList.addAll(maintJobDetail.itemsList!);
      }
      fileUrls.clear();
      if(null!=maintJobDetail.fileUrls){
        for (var value in maintJobDetail.fileUrls!) {
          fileUrls.add(value.url!);
        }
      }
      if (maintJobDetail.status == 1 || maintJobDetail.status == 3|| maintJobDetail.status == 4) {
        type = true;
      }else{
        type = false;
      }
    });
  }

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: TitleBar().backAppbar("维保任务详情"),
        backgroundColor: const Color(0xfff2f2f2),
        body: Column(
          children: [
            Expanded(
              // flex: 7,
              child: ListView(
                children: _Ws(),
              ),
            ),
            Visibility(
            visible: type,
            child: Container(
                  height: 50,
                  // flex: 7,
                  child: Row(
                    children: [
                      Expanded(
                        child: SizedBox(
                          height: 50,
                          child: TextButton(
                            onPressed: () {
                              CloseTaskDialog.showCupertinoAlertDialog(context,
                                      (msg) {
                                    closeJob(msg);
                                  });
                            },
                            child: Text(ConstantString.close_task),
                            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)
                            ),
                          ),
                        ),
                      ),
                      Expanded(
                          child: SizedBox(
                            height: 50,
                            child: TextButton(
                              onPressed: () {
                                // if (type) {
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => MaintlJobList(
                                            responseData: maintJobDetail)));
                                // }
                              },
                              child: Text(ConstantString.login_maint),
                              style: ButtonStyle(
                                backgroundColor:
                                MaterialStateProperty.all<Color>(Colors.blue),
                                foregroundColor:
                                MaterialStateProperty.all<Color>(Colors.white),
                                shape: MaterialStateProperty.all(BeveledRectangleBorder(
                                    borderRadius: BorderRadius.circular(0))),
                                // padding: MaterialStateProperty.all(EdgeInsets.zero)
                              ),
                            ),
                          )),
                    ],
                  ),
                )
            )

          ],
        ));
  }

  List<Widget> _Ws() {
    List<Widget> ws = [];
    ws.add(_maintJobDetail(maintJobDetail));
    ws.add(_device());
    ws.add(_item());
    if (null!= maintJobDetail.remarks&&'' != maintJobDetail.remarks) {
      ws.add(_remark());
    }
    ws.add(_url());
    return ws;
  }

  Widget _maintJobDetail(MaintJobDetailData maintJobDetail) {
    return Column(
      children: [
        Row(
          children: [
            Container(
              margin: EdgeInsets.only(top: 10, left: 12),
              // padding: EdgeInsets.fromLTRB(12, 0, 0, 0),
              alignment: Alignment.bottomLeft,
              child: Text(
                maintJobDetail.jobName == null ? '暂无' : maintJobDetail.jobName!,
                style: TextStyle(
                    fontSize: GSYConstant.middleTextWhiteSize,
                    fontWeight: FontWeight.bold),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 10, left: 10),
              padding: EdgeInsets.fromLTRB(3, 2, 3, 2),
              alignment: Alignment.centerLeft,
              child: Text(
                maintJobDetail.status == 0
                    ? '已关闭'
                    : maintJobDetail.status == 1
                        ? '执行中'
                        : maintJobDetail.status == 2
                            ? '已完成'
                            : maintJobDetail.status == 3
                                ? '待执行'
                                : maintJobDetail.status == 4
                                    ? '已逾期'
                                    : '未知',
                style: TextStyle(
                  fontSize: GSYConstant.minTextSize,
                  color:
                      maintJobDetail.status == 0 || maintJobDetail.status == 4
                          ? Colors.red
                          : maintJobDetail.status == 3
                              ? Colors.orange
                              : maintJobDetail.status == 2
                                  ? Colors.blue
                                  : Colors.black, //边框颜色
                ),
              ),
              decoration: BoxDecoration(
                border: new Border.all(
                  color:
                      maintJobDetail.status == 0 || maintJobDetail.status == 4
                          ? Colors.red
                          : maintJobDetail.status == 3
                              ? Colors.orange
                              : maintJobDetail.status == 2
                                  ? Colors.blue
                                  : Colors.black, //边框颜色
                  width: 1.0, //边框粗细
                ),
                borderRadius:
                    const BorderRadius.all(const Radius.circular(3.0)), //边框的弧度
              ),
            )
          ],
        ),
        Container(
          margin: EdgeInsets.only(top: 10, left: 12, bottom: 12),
          alignment: Alignment.centerLeft,
          child: Text(
            '任务编号:  ' +
                (maintJobDetail.jobNum == null ? '暂无' : maintJobDetail.jobNum!),
            style: TextStyle(
              fontSize: GSYConstant.smallTextSize,
            ),
          ),
        ),
        Container(
          decoration: BoxDecoration(color: Colors.white),
          child: Column(
            children: [
              Container(
                padding: EdgeInsets.fromLTRB(12, 20, 12, 0),
                alignment: Alignment.centerLeft,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    new Text(
                      '维保产品数：',
                      style: GSYConstant.smallTextLight,
                    ),
                    Container(
                      child: Text(
                        maintJobDetail.prodCount == null
                            ? '暂无'
                            : maintJobDetail.prodCount.toString(),
                        style: GSYConstant.smallTextLight,
                        textAlign: TextAlign.right,
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.fromLTRB(12, 15, 12, 0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    new Text(
                      '任务开始时间：',
                      style: GSYConstant.smallTextLight,
                    ),
                    Container(
                      child: Text(
                        maintJobDetail.startTime == null
                            ? '暂无'
                            : maintJobDetail.startTime!,
                        style: GSYConstant.smallTextLight,
                        textAlign: TextAlign.right,
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                  padding: EdgeInsets.fromLTRB(12, 15, 12, 0),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        new Text(
                          '任务结束时间：',
                          style: GSYConstant.smallTextLight,
                        ),
                        Container(
                          child: Text(
                            maintJobDetail.endTime == null
                                ? '暂无'
                                : maintJobDetail.endTime!,
                            style: GSYConstant.smallTextLight,
                            textAlign: TextAlign.right,
                          ),
                        ),
                      ])),
              Container(
                  padding: EdgeInsets.fromLTRB(12, 15, 12, 0),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        new Text(
                          '维保计划名称：',
                          style: GSYConstant.smallTextLight,
                        ),
                        Container(
                          child: Text(
                            maintJobDetail.planName == null
                                ? '暂无'
                                : maintJobDetail.planName!,
                            style: GSYConstant.smallTextLight,
                            textAlign: TextAlign.right,
                          ),
                        ),
                      ])),
              Container(
                  padding: EdgeInsets.fromLTRB(12, 15, 12, 0),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        new Text(
                          '维保计划编号：',
                          style: GSYConstant.smallTextLight,
                        ),
                        Container(
                          child: Text(
                            maintJobDetail.planNum == null
                                ? '暂无'
                                : maintJobDetail.planNum!,
                            style: GSYConstant.smallTextLight,
                            textAlign: TextAlign.right,
                          ),
                        ),
                      ])),
              Container(
                  padding: EdgeInsets.fromLTRB(12, 15, 12, 0),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        new Text(
                          '周期类型：',
                          style: GSYConstant.smallTextLight,
                        ),
                        Container(
                          child: Text(
                            maintJobDetail.cycleType == 1
                                ? '日计划'
                                : maintJobDetail.cycleType == 2
                                    ? '周计划'
                                    : maintJobDetail.cycleType == 3
                                        ? '月计划'
                                        : '暂无',
                            style: GSYConstant.smallTextLight,
                            textAlign: TextAlign.right,
                          ),
                        ),
                      ])),
              Container(
                  padding: EdgeInsets.fromLTRB(12, 15, 12, 0),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        new Text(
                          '维保完成时间：',
                          style: GSYConstant.smallTextLight,
                        ),
                        Container(
                          child: Text(
                            maintJobDetail.finishTime == null
                                ? '暂无'
                                : maintJobDetail.finishTime!,
                            style: GSYConstant.smallTextLight,
                            textAlign: TextAlign.right,
                          ),
                        ),
                      ])),
              Container(
                  padding: EdgeInsets.fromLTRB(12, 15, 12, 15),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        new Text(
                          '维保人员：',
                          style: GSYConstant.smallTextLight,
                        ),
                        Container(
                          child: Text(
                            maintJobDetail.maintStaffName == null
                                ? '暂无'
                                : maintJobDetail.maintStaffName!,
                            style: GSYConstant.smallTextLight,
                            textAlign: TextAlign.right,
                          ),
                        ),
                      ])),
            ],
          ),
        ),
      ],
    );
  }

  Widget _device() {
    return ExpansionTile(
        title: Container(
            child: Text(
          '维保设备',
          style: GSYConstant.normalTextActionWhiteBold,
        )),
        children: deviceList.map((e) => _buildDevice(e)).toList(),
        initiallyExpanded: true);
  }

  Widget _buildDevice(DeviceList device) {
    return FractionallySizedBox(
        widthFactor: 1,
        child: Container(
          margin: device.id == deviceList[deviceList.length - 1].id
              ? EdgeInsets.only(bottom: 0)
              : EdgeInsets.only(bottom: 5),
          decoration: BoxDecoration(color: Colors.white),
          padding: const EdgeInsets.fromLTRB(12, 12, 12, 12),
          child: Column(
            children: [
              Container(
                margin: const EdgeInsets.only(top: 10),
                // padding: const EdgeInsets.fromLTRB(30.0, 0.0, 0.0, 0.0),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        device.showName!,
                        style: GSYConstant.smallTextBold,
                      ),
                      Text(
                        device.isMainted == 0 ? '未完成' : '已完成',
                        style: TextStyle(
                            fontSize: GSYConstant.smallTextSize,
                            color: device.isMainted == 0
                                ? Colors.red
                                : Colors.blue),
                      ),
                    ]),
              ),
              // Divider(
              //   height: 0.8,
              //   indent: 10.0,
              //   endIndent: 10.0,
              //   color: Colors.grey,
              // ),
            ],
          ),
        ));
  }

  Widget _item() {
    return ExpansionTile(
        title: Container(
            child: Text(
          '维保项目',
          style: GSYConstant.normalTextActionWhiteBold,
        )),
        children: itemList.map((e) => _buildItem(e)).toList(),
        initiallyExpanded: false);
  }

  Widget _buildItem(ItemsList item) {
    return FractionallySizedBox(
        widthFactor: 1,
        child: Container(
          margin: item.id == itemList[itemList.length - 1].id
              ? EdgeInsets.only(bottom: 0)
              : EdgeInsets.only(bottom: 5),
          padding: const EdgeInsets.fromLTRB(12, 10, 15, 10),
          decoration: BoxDecoration(color: Colors.white),
          child: Column(
            children: [
              Container(
                alignment: Alignment.centerLeft,
                child: Text(item.name == null ? '' : item.name!,
                    style: TextStyle(
                        fontSize: GSYConstant.middleTextWhiteSize,
                        fontWeight: FontWeight.bold)),
              ),
              Container(
                margin: const EdgeInsets.fromLTRB(0, 10.0, 0, 0),
                alignment: Alignment.centerLeft,
                child: Text(
                  item.requirements!,
                  style: GSYConstant.smallTextLight,
                ),
              ),
            ],
          ),
        ));
  }

  Widget _remark() {
    return ExpansionTile(
        title: Container(
            child: Text(
          '任务结果备注',
          style: GSYConstant.normalTextActionWhiteBold,
        )),
        children: [_buildRemark(maintJobDetail.remarks!)],
        initiallyExpanded: false);
  }

  Widget _buildRemark(String patrolJobDetailData) {
    return FractionallySizedBox(
        widthFactor: 1,
        child: Container(
          decoration: BoxDecoration(color: Colors.white),
          child: Column(
            children: [
              Container(
                margin: const EdgeInsets.fromLTRB(12, 15.0, 12, 15.0),
                alignment: Alignment.centerLeft,
                child:
                    Text(patrolJobDetailData, style: TextStyle(fontSize: 14)),
              )
            ],
          ),
        ));
  }

  Widget _url() {
    return ExpansionTile(
        title: Container(
            child: Text(
          '维保图片',
          style: GSYConstant.normalTextActionWhiteBold,
        )),
        children: [
          Container(
            width: double.infinity,
            margin: EdgeInsets.only(bottom: 5),
            padding: fileUrls.isNotEmpty?EdgeInsets.only(right: 12, top: 10):EdgeInsets.only(right: 0, top: 0),
            color: Colors.white,
            child: Wrap(children: fileUrls.map((e) => _buildImage(e)).toList()),
            alignment: Alignment.centerLeft,
          )
        ],
        initiallyExpanded: false);
  }

  Widget _buildImage(String imageData) {
    return InkWell(
      child: Container(
          margin: EdgeInsets.only(left: 12, bottom: 10),
          width: MediaQuery.of(context).size.width / 4,
          height: MediaQuery.of(context).size.width / 4,
          child: Image.network(
            imageData,
            fit: BoxFit.fill,
          )),
      onTap: () {
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) =>
                    ViewDialog(img: imageData,imgs: fileUrls,width: MediaQuery.of(context).size.width,)));
      },
    );
  }

  closeJob(String msg) async {
    var result = await DioUtil().request('maintJob/close',
        method: DioMethod.post, data: {'id': id, 'closeReason': msg});
    if (0 == result['code']) {
      setState(() {
        eventBus.fire(RefreshMaintPage());
        Navigator.pop(context);
      });
    } else {
      showToast(result['msg']);
    }
  }
}
