import 'dart:io';

import 'package:deus_app/PhotoTool.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/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/repair_detail_response_entity.dart';
import 'package:deus_app/model/upload_list_entity_entity.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 RepairJobEdit extends StatefulWidget {

  static var routeName = "/PatrolJobEdit";

  RepairDetailResponseData responseData;
  @override
  State createState() {
    return _RepairJobEdit(responseData);
  }
  RepairJobEdit({super.key, required this.responseData});
}

class _RepairJobEdit extends State<RepairJobEdit> {

  List<MaintJobItemsListResponseData> patrolItemVOS = <MaintJobItemsListResponseData>[];

  List<AssetEntity> imageFiles = [];

  List<int>mList=[];

  RepairDetailResponseData responseData;

  var _event;

  String note='';

  FocusNode focusNode = FocusNode();

  _RepairJobEdit(this.responseData);

  @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: () {
                          if(imageFiles.isNotEmpty){
                            uploadList();
                          }else{
                            patrolJobRemark();
                          }
                        },
                        child: Text(ConstantString.completeRepair),
                        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)
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            )
          ],
        ));
  }

  List<Widget> _Ws() {
    List<Widget> ws = [];
    ws.add(_mainPatrolAdd());
    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(
              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,
                  decoration: InputDecoration(border: OutlineInputBorder()),
                  style: TextStyle(fontSize: 14),
                  focusNode: focusNode,
                  onChanged: (value) {
                    note = value;
                  },
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _mainPatrolAdd(){
    return Column(
      children: [
        Container(
          padding: EdgeInsets.fromLTRB(12,0, 12, 0),
          alignment: Alignment.centerLeft,
          height: 50,
          child: Text(
                '设备信息：',
                style: TextStyle(
                  color: Colors.black,
                  fontSize: GSYConstant.TextSize15,
                ),
          ),
        ),
        Container(
          // padding: const EdgeInsets.fromLTRB(30.0, 0.0, 0.0, 0.0),
          alignment: Alignment.centerLeft,
          color: Colors.white,
          padding: EdgeInsets.fromLTRB(12,15, 12, 15),
          child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(responseData.deviceName!,
                    style: GSYConstant.smallTextBold),
                Text(
                  '未维修',
                  style: TextStyle(
                      fontSize: GSYConstant.smallTextSize,
                      color: Colors.red),
                ),
              ]),
        ),
      ],
    );
  }

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

  @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('repair-bill/app-complete',
        method: DioMethod.post, data: {'id': responseData.id,'repairResIds':mList,'remarks':note});
    if (result['code'] == 0) {
      setState(() {
        eventBus.fire(RefreshRepairDetail());
        eventBus.fire(RefreshRepairPage());
        Navigator.of(context).pop();
      });
    } else {
      showToast(result['msg']);
    }
  }


}
