import 'dart:io';

import 'package:deus_app/PhotoTool.dart';
import 'package:deus_app/common/dialog/CloseTaskDialog.dart';
import 'package:deus_app/common/event/RefreshMaintDetail.dart';
import 'package:deus_app/common/event/RefreshMaintEdit.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/DioUtil.dart';
import 'package:deus_app/common/utils/ToastUtils.dart';
import 'package:deus_app/generated/json/maint_job_items_list_response_entity_helper.dart';
import 'package:deus_app/generated/json/upload_list_entity_entity_helper.dart';
import 'package:deus_app/main.dart';
import 'package:deus_app/model/maint_job_items_list_response_entity.dart';
import 'package:deus_app/model/upload_list_entity_entity.dart';
import 'package:deus_app/page/maint/maint_job_select.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class MairintJobEdit extends StatefulWidget {
  static var routeName = "/PatrolJobEdit";

  var id;

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

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

class _MairintJobEdit extends State<MairintJobEdit> {
  List<MaintJobItemsListResponseData> patrolItemVOS =
      <MaintJobItemsListResponseData>[];

  List<AssetEntity> imageFiles = [];

  List<int> mList = [];

  var id;

  var _event;

  String note = '';

  FocusNode focusNode = FocusNode();

  _MairintJobEdit(this.id);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: TitleBar().backAppbar("维保任务详情"),
        backgroundColor: const Color(0xfff2f2f2),
        body: Column(
          children: [
            Expanded(
              // flex: 7,
              child: ListView(
                children: _Ws(),
              ),
            ),
            Container(
              height: 50,
              // flex: 7,
              child: Row(
                children: [
                  Expanded(
                    child: SizedBox(
                      height: 50,
                      child: TextButton(
                        onPressed: () {
                          Navigator.pop(context);
                        },
                        child: Text(ConstantString.back),
                        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: () {
                        CloseTaskDialog.showAlertDialog(context, () {
                          if (imageFiles.isNotEmpty) {
                            uploadList();
                          } else {
                            patrolJobRemark();
                          }
                        }, '您确认完成维保？');
                      },
                      child: Text(ConstantString.complete),
                      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(_mainPatrolAdd());
    ws.addAll(_item());
    ws.add(_notes());
    ws.add(_picture());
    // ws.add(_url());
    return ws;
  }

  Widget _picture() {
    return Container(
        child: Column(
      children: [
        Container(
          height: 50,
          padding: EdgeInsets.only(left: 12),
          alignment: Alignment.centerLeft,
          child: Text('维保图片',
              style: TextStyle(
                color: Colors.black,
                fontSize: GSYConstant.TextSize15,
              )),
        ),
        Container(
          padding: EdgeInsets.only(left: 12, right: 12),
          decoration: BoxDecoration(color: Colors.white),
          child: PhotoTool(
              imageCount: 5,
              lineCount: 5,
              addCall: (List<AssetEntity> _imageFiles) {
                imageFiles.clear();
                imageFiles.addAll(_imageFiles);
              },
              removeCall: (int index) {
                imageFiles.removeAt(index);
              },
              focusNode: focusNode),
        )
      ],
    ));
  }

  Widget _notes() {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            height: 50,
            padding: EdgeInsets.only(left: 12),
            alignment: Alignment.centerLeft,
            child: Text('任务结果备注',
                style: TextStyle(
                  color: Colors.black,
                  fontSize: GSYConstant.TextSize15,
                )),
          ),
          Container(
            padding: EdgeInsets.only(left: 12, right: 12, bottom: 12),
            decoration: BoxDecoration(color: Colors.white),
            child: Column(
              children: [
                const SizedBox(
                  height: 10,
                ),
                TextField(
                  maxLines: 5,
                  focusNode: focusNode,
                  decoration: InputDecoration(border: OutlineInputBorder()),
                  style: TextStyle(fontSize: 14),
                  onChanged: (value) {
                    note = value;
                  },
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _mainPatrolAdd() {
    return Column(
      children: [
        Container(
          padding: EdgeInsets.fromLTRB(12, 0, 12, 0),
          height: 50,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '维保项目：',
                style: TextStyle(
                  color: Colors.black,
                  fontSize: GSYConstant.TextSize15,
                ),
              ),
              Container(
                child: TextButton(
                  onPressed: () {
                    focusNode.unfocus();
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => MaintJobSelect(
                                  id: id,
                                )));
                  },
                  child: Row(
                    children: [
                      new Icon(Icons.add),
                      new Text(
                        '添加项目',
                        style: TextStyle(
                          color: Colors.blue,
                          fontSize: GSYConstant.TextSize15,
                        ),
                        textAlign: TextAlign.right,
                      )
                    ],
                  ),
                ),
              ),
            ],
          ),
        )
      ],
    );
  }

  List<Widget> _item() {
    return patrolItemVOS.map((e) => _buildItem(e)).toList();
  }

  Widget _buildItem(MaintJobItemsListResponseData item) {
    return FractionallySizedBox(
        widthFactor: 1,
        child: Container(
          padding: const EdgeInsets.fromLTRB(12, 0, 15, 5),
          decoration: BoxDecoration(color: Colors.white),
          child: Column(
            children: [
              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(item.name,
                        style: TextStyle(
                            fontSize: GSYConstant.middleTextWhiteSize,
                            fontWeight: FontWeight.bold)),
                    IconButton(
                        onPressed: () {
                          deletePatrolItem(item.id);
                        },
                        icon: new Icon(Icons.delete))
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsets.fromLTRB(0, 10.0, 0, 0),
                alignment: Alignment.centerLeft,
                child: Text(
                  item.requirements,
                  style: GSYConstant.smallTextLight,
                ),
              ),
              const SizedBox(
                height: 5,
              ),
              Divider(
                height: 0.8,
                color: Colors.grey,
              ),
            ],
          ),
        ));
  }

  patrolItem() async {
    var result = await DioUtil().request('maintJob/app-items-list',
        method: DioMethod.get, params: {'maintJobId': id});
    if (0 == result['code']) {
      MaintJobItemsListResponseEntity jobEdit =
          maintJobItemsListResponseEntityFromJson(
              MaintJobItemsListResponseEntity(), result);
      setState(() {
        patrolItemVOS.clear();
        patrolItemVOS.addAll(jobEdit.data);
      });
    } else {
      showToast(result['msg']);
    }
  }

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

  deletePatrolItem(int itemId) async {
    var result = await DioUtil().request('maintJob/deleteItems',
        method: DioMethod.post, data: {'id': itemId, 'jobId': id});
    if (result['code'] == 0) {
      setState(() {
        patrolItem();
      });
    } else {
      showToast(result['msg']);
    }
  }

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

  uploadList() async {
    List<MultipartFile> files = [];
    for (var element in imageFiles) {
      File? imgFile = await element.file;
      String? s = imgFile?.path;
      MultipartFile file = MultipartFile.fromFileSync(s!);
      files.add(file);
    }
    var formData = FormData.fromMap({'files': files});
    var result = await DioUtil().request('uploadImg/uploadList',
        method: DioMethod.post, data: formData);
    if (result['code'] == 0) {
      UploadListEntityEntity data =
          uploadListEntityEntityFromJson(UploadListEntityEntity(), result);
      setState(() {
        mList.clear();
        mList.addAll(data.data);
        patrolJobRemark();
      });
    } else {
      showToast(result['msg']);
    }
  }

  patrolJobRemark() async {
    var result = await DioUtil().request('maintJob/complete',
        method: DioMethod.post,
        data: {'id': id, 'fileIds': mList, 'remarks': note});
    if (result['code'] == 0) {
      setState(() {
        eventBus.fire(RefreshMaintDetail());
        eventBus.fire(RefreshMaintPage());
        Navigator.of(context)
          ..pop()
          ..pop();
      });
    } else {
      showToast(result['msg']);
    }
  }
}
