import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.dart';
import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/consts/colors.dart';
import 'package:jcs_airport/consts/file_type.dart';
import 'package:jcs_airport/consts/styles.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/view/common/TimeLineData.dart';
import 'package:jcs_airport/view/common/image_picker.dart';
import 'package:jcs_airport/view/common/time_line_center.dart';
import 'package:jcs_airport/view/common/time_line_left.dart';
import 'package:jcs_airport/view/workBench/malfunctionReport/reportTask/repair_audit.dart';
import 'package:video_player/video_player.dart';
import 'package:jcs_airport/view/workBench/malfunctionReport/malfunctionReport/malfunction_report.dart';
import 'package:jcs_airport/view/workBench/malfunctionReport/reportTask/verify.dart';

import 'add_repair_record.dart';
import 'report_audit.dart';

class ReportTaskDetail extends StatefulWidget {
  final String sequenceNbr;

  const ReportTaskDetail(this.sequenceNbr);

  @override
  State<StatefulWidget> createState() => ReportTaskDetailData();
}

class ReportTaskDetailData extends State<ReportTaskDetail>
    with SingleTickerProviderStateMixin {
  TabController _tabController;

  ///1去编辑重新提交
  ///2应急指挥科领导审核
  ///3维修部门领导审核
  ///4去维修
  ///5去验收
  ///6重新提交报修单
  int _authButton = 0; //操作权限信息
  String imageUrl = '';
  Map<String, Object> _baseInfoData = {}; //基本信息
  final List<ChooseFileInfo> _files = []; //附件信息
  List<Map<String, Object>> _auditData = []; //审核记录
  List<Map<String, Object>> _maintainData = []; //维修记录
  List<Map<String, Object>> _verifyData = []; //验收记录
  final List<TimeLineData> _reportLogData = []; //报修日志
  final List<TimeLineData> _flowData = []; //流程信息
  Map<String, Object> _currentFlow = {}; //当前流程

  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: 3);
    APIUrlManager.getImageUrl().then((value) {
      setState(() {
        imageUrl = value;
      });
    });
    _initData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('故障报修单详情'),
        bottom: TabContainer(
          color: Colors.white,
          child: TabBar(
            labelColor: Theme.of(context).primaryColor,
            unselectedLabelColor: Colors.black54,
            indicatorColor: Theme.of(context).primaryColor,
            tabs: const [
              Tab(text: '基本信息'),
              Tab(text: '报修日志'),
              Tab(text: '流程'),
            ],
            controller: _tabController,
          ),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          SingleChildScrollView(
            child: Card(
              child: Container(
                padding: const EdgeInsets.all(10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildRow('当前状态：',
                        (_baseInfoData['currentStatusName'] ?? '').toString(),
                        contentColor: AMOSColors.malfunctionStatusColor(
                            _baseInfoData['currentStatusName'].toString())),
                    _buildRow('故障设备：', _baseInfoData['failureEquipment']),
                    _buildRow('故障时间：', _baseInfoData['faultTime']),
                    Container(
                      padding: const EdgeInsets.only(bottom: 8),
                      child: Row(
                        children: [
                          const Expanded(child: Text('故障现象:')),
                          Expanded(
                              flex: 2,
                              child: Text(
                                _baseInfoData['faultPhenomenon'] ?? '',
                                // maxLines: 4,
                              )),
                        ],
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.only(bottom: 8),
                      child: Row(
                        children: [
                          const Expanded(child: Text('照片/视频:')),
                          Expanded(
                            flex: 2,
                            child: ImagePickerAndRemove(
                              _files,
                              readOnly: true,
                            ),
                          )
                        ],
                      ),
                    ),
                    _buildRow('报  送  人：', _baseInfoData['submissionName']),
                    //_buildRow('报送时间：', _baseInfoData['faultTime']),
                    _buildRow('报送部门：', _baseInfoData['submissionBranch']),
                    _buildRow('提交时间：', _baseInfoData['submissionTime']),
                    Transform.translate(
                        offset: const Offset(0, 2),
                        child: const Divider(
                          height: 5,
                        )),
                    _auditData.isNotEmpty
                        ? Row(
                            children: [
                              Expanded(
                                child: CollapseCard(
                                  defaultExpanded: false,
                                  title: const Text(
                                    '审核记录',
                                    style: TextStyle(
                                        fontSize: CoreStyles.textSizeSmall),
                                  ),
                                  children: _auditData
                                      .asMap()
                                      .map((index, element) => MapEntry(
                                          index,
                                          _buildAuditRecordItem(
                                              index, element)))
                                      .values
                                      .toList(),
                                ),
                              )
                            ],
                          )
                        : Container(),
                    _maintainData.isNotEmpty
                        ? Row(
                            children: [
                              Expanded(
                                child: CollapseCard(
                                  defaultExpanded: false,
                                  title: const Text(
                                    '维修记录',
                                    style: TextStyle(
                                        fontSize: CoreStyles.textSizeSmall),
                                  ),
                                  children: _maintainData
                                      .asMap()
                                      .map((index, element) => MapEntry(
                                          index,
                                          _buildRepairRecordItem(
                                              index, element)))
                                      .values
                                      .toList(),
                                ),
                              )
                            ],
                          )
                        : Container(),
                    _verifyData.isNotEmpty
                        ? Row(
                            children: [
                              Expanded(
                                child: CollapseCard(
                                  defaultExpanded: false,
                                  title: const Text(
                                    '验收记录',
                                    style: TextStyle(
                                        fontSize: CoreStyles.textSizeSmall),
                                  ),
                                  children: _verifyData
                                      .asMap()
                                      .map((index, element) => MapEntry(
                                          index,
                                          _buildVerifyRecordItem(
                                              index, element)))
                                      .values
                                      .toList(),
                                ),
                              )
                            ],
                          )
                        : Container(),
                    const SizedBox(
                      height: 10,
                    ),
                    _authButton == 2
                        ? Row(
                            children: [
                              Expanded(
                                  child: FlatButton(
                                color: Theme.of(context).primaryColor,
                                height: 40,
                                onPressed: () async {
                                  await Get.to(ReportAudit(widget.sequenceNbr));
                                  _initData();
                                },
                                child: const Text(
                                  '审核',
                                  style: TextStyle(color: Colors.white),
                                ),
                              )),
                            ],
                          )
                        : Container(),
                    const SizedBox(
                      height: 10,
                    ),
                    _authButton == 3
                        ? Row(
                            children: [
                              Expanded(
                                  child: FlatButton(
                                color: Theme.of(context).primaryColor,
                                height: 40,
                                onPressed: () async {
                                  await Get.to(RepairAudit(widget.sequenceNbr));
                                  _initData();
                                },
                                child: const Text(
                                  '审核',
                                  style: TextStyle(color: Colors.white),
                                ),
                              )),
                            ],
                          )
                        : Container(),
                    const SizedBox(
                      height: 10,
                    ),
                    _authButton == 4
                        ? Row(
                            children: [
                              Expanded(
                                  child: FlatButton(
                                color: Theme.of(context).primaryColor,
                                height: 40,
                                onPressed: () async {
                                  await Get.to(AddRepair(widget.sequenceNbr));
                                  _initData();
                                },
                                child: const Text(
                                  '添加维修记录',
                                  style: TextStyle(color: Colors.white),
                                ),
                              )),
                            ],
                          )
                        : Container(),
                    const SizedBox(
                      height: 10,
                    ),
                    _authButton == 5
                        ? Row(
                            children: [
                              Expanded(
                                  child: FlatButton(
                                color: Theme.of(context).primaryColor,
                                height: 40,
                                onPressed: () async {
                                  await Get.to(Verify(widget.sequenceNbr));
                                  _initData();
                                },
                                child: const Text(
                                  '去验收',
                                  style: TextStyle(color: Colors.white),
                                ),
                              )),
                            ],
                          )
                        : Container(),
                    const SizedBox(
                      height: 10,
                    ),
                    _authButton == 6&&_baseInfoData['isSubmit'].toString()=='true'
                        ? Row(
                            children: [
                              Expanded(
                                  child: FlatButton(
                                color: Theme.of(context).primaryColor,
                                height: 40,
                                onPressed: () async {
                                  await Get.to(MalfunctionReport(
                                    sequenceNbr: widget.sequenceNbr,
                                    isUpdate: false,
                                  ));
                                  _initData();
                                },
                                child: const Text(
                                  '重新提交报修单',
                                  style: TextStyle(color: Colors.white),
                                ),
                              )),
                            ],
                          )
                        : Container(),
                    const SizedBox(
                      height: 10,
                    ),
                    _authButton == 1
                        ? Row(
                            children: [
                              Expanded(
                                  child: FlatButton(
                                color: Theme.of(context).primaryColor,
                                height: 40,
                                onPressed: () async {
                                  await Get.to(MalfunctionReport(
                                      sequenceNbr: widget.sequenceNbr,
                                      isUpdate: true));
                                  _initData();
                                },
                                child: const Text(
                                  '去编辑重新提交',
                                  style: TextStyle(color: Colors.white),
                                ),
                              )),
                            ],
                          )
                        : Container(),
                  ],
                ),
              ),
            ),
          ),
          //报修日志Tab
          SingleChildScrollView(
              child: Card(
                  child: Container(
                      padding: const EdgeInsets.only(top: 20),
                      child: TimeLineCenter(_reportLogData)))),
          //流程Tab
          SingleChildScrollView(
            child: Card(
              child: Container(
                child: Column(
                  children: [
                    TimeLineLeft(_flowData,
                        image: Image.asset(
                          'assets/logo.png',
                          width: 30,
                          height: 30,
                        )),
                    Row(
                      children: const [
                        Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Text('当前流程'),
                        )
                      ],
                    ),
                    Row(
                      children: [
                        const Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Icon(Icons.person),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(_currentFlow['name'] ?? ''),
                        )
                      ],
                    )
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  ///构建审核记录数据项
  Container _buildAuditRecordItem(int index, Map<String, Object> data) {
    return Container(
      padding: const EdgeInsets.only(left: 20, right: 20, bottom: 20),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: Transform.translate(
                  offset: const Offset(-12, 0),
                  child: Row(
                    children: [
                      Text('${index + 1}.'),
                      const Expanded(child: Text('审核时间：')),
                      Expanded(flex: 2, child: Text(data['auditTime'])),
                    ],
                  ),
                ),
              )
            ],
          ),
          const SizedBox(
            height: 5,
          ),
          _buildRow('审核人：', data['auditor']),
          _buildRow('审核部门：', data['auditDepartment']),
          _buildRow('审核意见：', data['auditOpinion']),
          _buildRow('审核结果：', convertAuditResult(data['auditResult'])),
        ],
      ),
    );
  }

  ///构建维修记录数据项
  Container _buildRepairRecordItem(int index, Map<String, Object> data) {
    return Container(
      padding: const EdgeInsets.only(left: 20, right: 20, bottom: 20),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: Transform.translate(
                  offset: const Offset(-12, 0),
                  child: Row(
                    children: [
                      Text('${index + 1}.'),
                      const Expanded(child: Text('维修时间：')),
                      Expanded(flex: 2, child: Text(data['maintainTime'])),
                    ],
                  ),
                ),
              )
            ],
          ),
          const SizedBox(
            height: 5,
          ),
          _buildRow('维  修  人：', data['maintainMan']),
          _buildRow('所属部门：', data['department']),
          _buildRow('维修内容：', data['maintainContent']),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Expanded(child: Text('照片/视频：')),
              Expanded(
                  flex: 2,
                  child: data['attachment'] != null
                      ? ImagePickerAndRemove(
                          data['attachment'],
                          readOnly: true,
                        )
                      : Container()),
            ],
          ),
          const SizedBox(
            height: 5,
          ),
          _buildRow('记录类型：', data['recoreType']),
        ],
      ),
    );
  }

  ///构建验收记录数据项
  Container _buildVerifyRecordItem(int index, Map<String, Object> data) {
    return Container(
      padding: const EdgeInsets.only(left: 20, right: 20, bottom: 20),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: Transform.translate(
                  offset: const Offset(-12, 0),
                  child: Row(
                    children: [
                      Text('${index + 1}.'),
                      const Expanded(child: Text('验收时间：')),
                      Expanded(flex: 2, child: Text(data['verifyTime'] ?? '')),
                    ],
                  ),
                ),
              )
            ],
          ),
          const SizedBox(
            height: 5,
          ),
          _buildRow('验  收  人：', data['recUserName'] ?? ''),
          _buildRow('所属部门：', data['verifyDepartment'] ?? ''),
          _buildRow('验收意见：', data['verifyOpinion'] ?? ''),
        ],
      ),
    );
  }

  ///构建审核记录/维修记录/验收记录 数据项的行
  Widget _buildRow(String title, String content, {Color contentColor}) {
    return Container(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        children: [
          Expanded(child: Text(title)),
          Expanded(
              flex: 2,
              child: Text(
                content ?? '',
                style: TextStyle(color: contentColor),
              )),
        ],
      ),
    );
  }

  void _initData() {
    Future.delayed(Duration.zero, () {
      MsgBox.showProgressDialog(context, content: '加载中，请稍后...');
      Future.wait([
        getAuthButton(),
        getBaseInfo(),
        getAudit(),
        getMaintain(),
        getVerifyRecord(),
        getReportLog(),
        getFlowData(),
        getCurrentFlow()
      ]).whenComplete(() => Get.back());
    });
  }

  String convertAuditResult(int result) {
    switch (result) {
      case 0:
        return '同意';
        break;
      case 1:
        return '拒绝';
        break;
      case 2:
        return '退回';
        break;
      default:
        return '';
        break;
    }
  }

  Future getFlowData() async {
    var flowData = await API.failureDetailsProcessHistory(widget.sequenceNbr);
    if (flowData != null) {
      setState(() {
        _flowData.clear();
        flowData.forEach((element) {
          _flowData.add(TimeLineData(
              element['time'] ?? '', element['name'] ?? '',
              height: 15, isFinished: element['flag'] ?? false));
        });
      });
    }
  }

  Future getCurrentFlow() async {
    var currentFlow =
        await API.failureDetailsGetCurrentTask(widget.sequenceNbr);
    if (currentFlow != null && currentFlow.length > 0) {
      setState(() {
        _currentFlow = currentFlow[0];
      });
    }
  }

  Future getReportLog() async {
    var reportLogData = await API.failureRepairLog(widget.sequenceNbr);
    if (reportLogData != null) {
      setState(() {
        _reportLogData.clear();
        reportLogData.forEach((element) {
          _reportLogData.add(TimeLineData(element['processTime'] ?? '',
              '${element["processDepartment"] ?? ""} - ${element["processAuditorName"] ?? ""} - ${element["processResult"] ?? ""}',
              height: 25.0, indicatorColor: Colors.green));
        });
      });
    }
  }

  Future getMaintain() async {
    var maintainData = await API.failureMaintain(widget.sequenceNbr);
    if (maintainData != null) {
      setState(() {
        ///附件转组件
        maintainData.forEach((e) {
          e['attachment'] = (e['attachment'] ?? [])
              .map((element) {
                var isImage = element['fileCategory'] == FileType.IMAGE;
                //var path = HttpConfig.GateWayURL + element['filePath'];
                var path = imageUrl + element['filePath'];
                if (isImage) {
                  return ChooseFileInfo(null,
                      isPhoto: isImage, isVideo: !isImage, url: path);
                } else {
                  VideoPlayerController _controller =
                      VideoPlayerController.network(path)..initialize();
                  ChewieController _chewieController = ChewieController(
                    videoPlayerController: _controller,
                    autoPlay: true,
                    looping: true,
                  );
                  return ChooseFileInfo(null,
                      isPhoto: isImage,
                      isVideo: !isImage,
                      videoPlayerController: _controller,
                      chewieController: _chewieController);
                }
              })
              .toList()
              .cast<ChooseFileInfo>();
        });
        _maintainData = maintainData.cast<Map<String, Object>>();
      });
    }
  }

  Future getAudit() async {
    var auditData = await API.failureAudit(widget.sequenceNbr);
    if (auditData != null) {
      setState(() {
        _auditData = auditData.cast<Map<String, Object>>();
      });
    }
  }

  Future getVerifyRecord() async {
    var verifyData = await API.failureVerifyRecord(widget.sequenceNbr);
    if (verifyData != null) {
      setState(() {
        _verifyData = verifyData.cast<Map<String, Object>>();
      });
    }
  }

  Future getAuthButton() async {
    var authButton =
        await API.failureDetailsExecuteTaskAuthButton(widget.sequenceNbr);
    if (authButton != null) {
      setState(() {
        _authButton = authButton;
      });
    }
  }

  Future getBaseInfo() async {
    var baseInfoData = await API.failureDetails(widget.sequenceNbr);
    if (baseInfoData != null) {
      _files.clear();

      ///附件转组件
      baseInfoData['attachment'] = baseInfoData['attachment']
          .map((element) {
            var isImage = element['fileCategory'] == FileType.IMAGE;
            var path = imageUrl + element['filePath'];

            if (isImage) {
              _files.add(ChooseFileInfo(null,
                  isPhoto: isImage, isVideo: !isImage, url: path));
            } else {
              VideoPlayerController _controller =
                  VideoPlayerController.network(path)..initialize();
              ChewieController _chewieController = ChewieController(
                videoPlayerController: _controller,
                autoPlay: true,
                looping: true,
              );
              _files.add(ChooseFileInfo(null,
                  isPhoto: isImage,
                  isVideo: !isImage,
                  url: path,
                  videoPlayerController: _controller,
                  chewieController: _chewieController));
            }
          })
          .toList()
          .cast<ChooseFileInfo>();
      setState(() {
        _baseInfoData = baseInfoData;
      });
    }
  }
}
