import 'package:deus_app/common/dialog/CloseTaskDialog.dart';
import 'package:deus_app/common/dialog/ViewDialog.dart';
import 'package:deus_app/common/event/RefreshRepairDetail.dart';
import 'package:deus_app/common/event/RefreshRepairPage.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/DioUtil.dart';
import 'package:deus_app/common/utils/ToastUtils.dart';
import 'package:deus_app/generated/json/repair_detail_response_entity_helper.dart';
import 'package:deus_app/main.dart';
import 'package:deus_app/model/repair_detail_response_entity.dart';
import 'package:deus_app/page/repair/repair_job_edit.dart';
import 'package:flutter/material.dart';

class RepairDetail extends StatefulWidget {
  var id;

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

  @override
  State createState() {
    return _RepairDetail(id);
  }
}

class _RepairDetail extends State<RepairDetail> {
  var id;

  bool type = false;

  RepairDetailResponseData responseData = RepairDetailResponseData();

  List<String> repairImgUrls = [];
  List<String> repairResUrls = [];

  String buttonText='';

  var _event;

  bool isClose=false;

  _RepairDetail(this.id);

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: TitleBar().backAppbar("报修详情"),
      backgroundColor: const Color(0xfff2f2f2),
      body: Stack(
        children: [
          Container(
            margin: EdgeInsets.only(bottom: type ? 60 : 0),
            child: ListView(
              children: _Ws(),
            ),
          ),
          Visibility(
              visible: type,
              child: Positioned(
                left: 0,
                right: 0,
                bottom: 0,
                // flex: 7,
                child: Row(
                  children: [
                    Visibility(
                      visible: isClose,
                      child: Expanded(
                        child: SizedBox(
                          height: 50,
                          child: TextButton(
                            onPressed: () {
                              CloseTaskDialog.showAlertDialog(context, () {
                                closeJob();
                              }, '确认关闭申请？');
                            },
                            style: ButtonStyle(
                              backgroundColor: MaterialStateProperty.all<Color>(
                                  Colors.blue),
                              shape: MaterialStateProperty.all(
                                  BeveledRectangleBorder(
                                      borderRadius: BorderRadius.circular(0))),
                              foregroundColor: MaterialStateProperty.all<Color>(
                                  Colors.white),
                              // padding: MaterialStateProperty.all(EdgeInsets.zero)
                            ),
                            child: const Text(ConstantString.close_job),
                          ),
                        ),
                      ),
                    ),

                    Expanded(
                        child: SizedBox(
                          height: 50,
                          child: TextButton(
                            onPressed: () {
                              if (type) {
                                if('维修接单'==buttonText){
                                  CloseTaskDialog.showAlertDialog(context, () {
                                    receive();
                                  }, '确认维修接单么？');
                                }else if('开始维修'==buttonText){
                                  CloseTaskDialog.showAlertDialog(context, () {
                                    start();
                                  }, '确认后不支持更换维修人员');
                                }else{
                                  Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) =>
                                              RepairJobEdit(responseData: responseData)));
                                }

                              }
                            },
                            style: ButtonStyle(
                              backgroundColor:
                              MaterialStateProperty.all<Color>(Color(0xFF4875EC)),
                              foregroundColor:
                              MaterialStateProperty.all<Color>(Colors.white),
                              shape: MaterialStateProperty.all(
                                  BeveledRectangleBorder(
                                      borderRadius: BorderRadius.circular(0))),
                              // padding: MaterialStateProperty.all(EdgeInsets.zero)
                            ),
                            child: Text(buttonText),
                          ),
                        )),
                  ],
                ),
              ))
        ],
      ),
    );
  }

  List<Widget> _Ws() {
    List<Widget> ws = [];
    ws.add(_patrolJobDetail(responseData));
    ws.add(_basicInformation());
    ws.add(_notes());
    ws.add(_img());
    return ws;
  }

  Widget _notes() {
    return Column(children: [
      Container(
        height: 50,
        padding: EdgeInsets.only(left: 12),
        alignment: Alignment.centerLeft,
        child: const Text(
          '维修结果备注：',
          style: TextStyle(
            color: Colors.black,
            fontSize: GSYConstant.TextSize15,
          ),
        ),
      ),
      Container(
        color: Colors.white,
        padding: EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 10),
        alignment: Alignment.centerLeft,
        child: Text(
          responseData.repResRemarks == null
              ? '无'
              : responseData.repResRemarks!,
          style: const TextStyle(
            color: Colors.black,
            fontSize: GSYConstant.TextSize15,
          ),
        ),
      ),
    ]);
  }

  Widget _img() {
    return Column(children: [
      Container(
        height: 50,
        padding: EdgeInsets.only(left: 12),
        alignment: Alignment.centerLeft,
        child: const Text(
          '维修图片：',
          style: TextStyle(
            color: Colors.black,
            fontSize: GSYConstant.TextSize15,
          ),
        ),
      ),
      Container(
        width: double.infinity,
        margin: EdgeInsets.only(bottom: 5),
        padding: repairResUrls.isNotEmpty?EdgeInsets.only(right: 12, top: 10):EdgeInsets.only(right: 0, top: 0),
        color: Colors.white,
        child: Wrap(
            children: repairResUrls.map((e) => _buildImage(e,1)).toList()),
        alignment: Alignment.centerLeft,
      )
    ]);
  }

  Widget _basicInformation() {
    return Column(children: [
      Container(
        height: 50,
        padding: EdgeInsets.only(left: 12),
        alignment: Alignment.centerLeft,
        child: const Text(
          '基本信息：',
          style: TextStyle(
            color: Colors.black,
            fontSize: GSYConstant.TextSize15,
          ),
        ),
      ),
      Container(
        color: Colors.white,
        padding: EdgeInsets.only(left: 12, right: 12, top: 15, bottom: 15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '紧急程度：',
                  style: GSYConstant.smallTextLight,
                ),
                Text(
                  responseData.urg == 1 ? "一般" : "紧急",
                  style: GSYConstant.smallTextLight,
                  textAlign: TextAlign.right,
                ),
              ],
            ),
            const SizedBox(
              height: 12,
            ),
            Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
              const Text(
                '报修设备：',
                style: GSYConstant.smallTextLight,
              ),
              Text(
                responseData.device == null
                    ? ''
                    : responseData.device!.showName!,
                style: GSYConstant.smallTextLight,
                textAlign: TextAlign.right,
              ),
            ]),
            const SizedBox(
              height: 12,
            ),
            Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
              const Text(
                '报修说明：',
                style: GSYConstant.smallTextLight,
              ),
              Text(
                responseData.instructions == null
                    ? '无'
                    : responseData.instructions!,
                style: GSYConstant.smallTextLight,
                textAlign: TextAlign.right,
              ),
            ]),
            const SizedBox(
              height: 12,
            ),
            const Text(
              '图片说明：',
              style: GSYConstant.smallTextLight,
              textAlign: TextAlign.left,
            ),
            const SizedBox(
              height: 10,
            ),
            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: repairImgUrls.map((e) => _buildImage(e,0)).toList()),
              alignment: Alignment.centerLeft,
            )
          ],
        ),
      )
    ]);
  }

  Widget _buildImage(String imageData,int i) {
    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: i==0?repairImgUrls:repairResUrls,width: MediaQuery.of(context).size.width,)));
      },
    );
  }

  Widget _patrolJobDetail(RepairDetailResponseData patrolJobDetailData) {
    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(
                patrolJobDetailData.theme == null
                    ? '暂无'
                    : patrolJobDetailData.theme!,
                style: TextStyle(
                    fontSize: GSYConstant.middleTextWhiteSize,
                    fontWeight: FontWeight.bold),
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: 10, left: 10),
              padding: const EdgeInsets.fromLTRB(3, 2, 3, 2),
              alignment: Alignment.centerLeft,
              decoration: BoxDecoration(
                border: Border.all(
                  color: patrolJobDetailData.status == 1 ||
                          patrolJobDetailData.status == 2
                      ? Colors.red
                      : patrolJobDetailData.status == 3
                          ? Colors.orange
                          : patrolJobDetailData.status == 4 ||
                                  patrolJobDetailData.status == 5
                              ? Colors.blue
                              : Colors.black, //边框颜色
                  width: 1.0, //边框粗细
                ),
                borderRadius:
                    const BorderRadius.all(const Radius.circular(3.0)), //边框的弧度
              ),
              child: Text(
                patrolJobDetailData.status == 1
                    ? '待接单'
                    : patrolJobDetailData.status == 2
                        ? '待执行'
                        : patrolJobDetailData.status == 3
                            ? '维修中'
                            : patrolJobDetailData.status == 4
                                ? '已关闭'
                                : patrolJobDetailData.status == 5
                                    ? '已完成'
                                    : '未知',
                style: TextStyle(
                  fontSize: GSYConstant.minTextSize,
                  color: patrolJobDetailData.status == 1 ||
                          patrolJobDetailData.status == 2
                      ? Colors.red
                      : patrolJobDetailData.status == 3
                          ? Colors.orange
                          : patrolJobDetailData.status == 4 ||
                                  patrolJobDetailData.status == 5
                              ? Colors.blue
                              : Colors.black, //边框颜色
                ),
              ),
            )
          ],
        ),
        Container(
          margin: const EdgeInsets.only(top: 10, left: 12, bottom: 12),
          alignment: Alignment.centerLeft,
          child: Text(
            '报修单号:  ' + patrolJobDetailData.repNum,
            style: TextStyle(
              fontSize: GSYConstant.smallTextSize,
            ),
          ),
        ),
        // Divider(
        //   height: 0.8,
        //   indent: 5.0,
        //   endIndent: 5.0,
        //   color: Colors.grey,
        // ),
        Container(
          decoration: BoxDecoration(color: Colors.white),
          child: Column(
            children: [
              Container(
                padding: EdgeInsets.fromLTRB(12, 15, 12, 0),
                alignment: Alignment.centerLeft,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    new Text(
                      '申请人：',
                      style: GSYConstant.smallTextLight,
                    ),
                    Container(
                      child: Text(
                        patrolJobDetailData.applicant,
                        style: GSYConstant.smallTextLight,
                        textAlign: TextAlign.right,
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.fromLTRB(12, 12, 12, 0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    new Text(
                      '申请时间：',
                      style: GSYConstant.smallTextLight,
                    ),
                    Container(
                      child: Text(
                        patrolJobDetailData.applicationTime,
                        style: GSYConstant.smallTextLight,
                        textAlign: TextAlign.right,
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                  padding: EdgeInsets.fromLTRB(12, 12, 12, 0),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        new Text(
                          '维修人员：',
                          style: GSYConstant.smallTextLight,
                        ),
                        Container(
                          child: Text(
                            patrolJobDetailData.maintainer,
                            style: GSYConstant.smallTextLight,
                            textAlign: TextAlign.right,
                          ),
                        ),
                      ])),
              Container(
                  padding: EdgeInsets.fromLTRB(12, 12, 12, 0),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        new Text(
                          '接单时间：',
                          style: GSYConstant.smallTextLight,
                        ),
                        Container(
                          child: Text(
                            patrolJobDetailData.orderRecTime,
                            style: GSYConstant.smallTextLight,
                            textAlign: TextAlign.right,
                          ),
                        ),
                      ])),
              Container(
                  padding: EdgeInsets.fromLTRB(12, 12, 12, 15),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const Text(
                          '完成时间：',
                          style: GSYConstant.smallTextLight,
                        ),
                        Text(
                          patrolJobDetailData.completeTime,
                          style: GSYConstant.smallTextLight,
                          textAlign: TextAlign.right,
                        ),
                      ])),
            ],
          ),
        ),
      ],
    );
  }

  _load() async {
    var result = await DioUtil().request('repair-bill/app-detail',
        method: DioMethod.post, data: {'id': id});
    RepairDetailResponseEntity patrolJobResponse =
        repairDetailResponseEntityFromJson(
            RepairDetailResponseEntity(), result);
    if (patrolJobResponse.code == 0) {
      setState(() {
        responseData = patrolJobResponse.data;
        repairImgUrls.clear();
        repairImgUrls.addAll(responseData.repairImgUrls);
        repairResUrls.clear();
        repairResUrls.addAll(responseData.repairResUrls);
        if (responseData.status == 1 || responseData.status == 2|| responseData.status == 3) {
          type = true;
          if(responseData.status == 1){
            isClose=true;
            buttonText='维修接单';
          }else if(responseData.status==2){
            isClose=false;
            buttonText='开始维修';
          }else if(responseData.status==3){
            buttonText='登记维修';
          }
        }else{
          type = false;
        }
      });
    } else {
      showToast(patrolJobResponse.msg);
    }
  }

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

  closeJob() async {
    var result = await DioUtil().request('repair-bill/close',
        method: DioMethod.get, params: {'id': id});
    if (0 == result['code']) {
      setState(() {
        eventBus.fire(RefreshRepairPage());
        Navigator.pop(context);
      });
    } else {
      showToast(result['msg']);
    }
  }

  receive() async {
    var result = await DioUtil().request('repair-bill/receive',
        method: DioMethod.post, data: {'id': id});
    if (0 == result['code']) {
      setState(() {
        _load();
      });
    } else {
      showToast(result['msg']);
    }
  }

  start() async {
    var result = await DioUtil().request('repair-bill/start',
        method: DioMethod.post, data: {'id': id});
    if (0 == result['code']) {
      setState(() {
        _load();
      });
    } else {
      showToast(result['msg']);
    }
  }
}
