import 'dart:io';

import 'package:deus_app/PhotoTool.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/repair_query_device_response_entity.dart';
import 'package:deus_app/model/upload_list_entity_entity.dart';
import 'package:deus_app/page/repair/repair_job_device_list.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class RepairAddPage extends StatefulWidget {
  const RepairAddPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _RepairAddPage();
  }
}

class _RepairAddPage extends State<RepairAddPage> {
  int groupValue = 1;
  String note = '', theme = '';
  List<AssetEntity> imageFiles = [];
  List<int> mList = [];
  var _event;
  RepairQueryDeviceResponseDataList _dataList =
      RepairQueryDeviceResponseDataList();

  FocusNode focusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: TitleBar().backAppbar("新建报修"),
        backgroundColor: const Color(0xfff2f2f2),
        body: Stack(children: [
          Column(
            children: [
              Expanded(
                // flex: 7,
                child: ListView(
                  children: _Ws(),
                ),
              ),
            ],
          ),
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            // flex: 7,
            child: SizedBox(
              height: 50,
              width: double.infinity,
              child: TextButton(
                onPressed: () {
                  if (isAddDevice) {
                    if (imageFiles.isNotEmpty) {
                      uploadList();
                    } else {
                      patrolJobRemark();
                    }
                  } else {
                    showToast('请选择设备');
                  }
                },
                style: ButtonStyle(
                  backgroundColor:
                      MaterialStateProperty.all<Color>(Color(0xFF4875EC)),
                  shape: MaterialStateProperty.all(BeveledRectangleBorder(
                      borderRadius: BorderRadius.circular(0))),
                  foregroundColor:
                      MaterialStateProperty.all<Color>(Colors.white),
                ),
                child: const Text(ConstantString.submit),
              ),
            ),
          )
        ]));
  }

  @override
  void initState() {
    super.initState();
    _event = eventBus.on<RepairQueryDeviceResponseDataList>().listen((event) {
      setState(() {
        _dataList = event;
        isAddDevice = true;
      });
    });
  }

  bool isAddDevice = false;

  List<Widget> _Ws() {
    List<Widget> ws = [];
    ws.add(_basicInformation());
    ws.add(_patrolAddTitle());
    if (isAddDevice) {
      ws.add(_patrolAdd());
    }
    ws.add(_notes());
    return ws;
  }

  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;
                  },
                )
              ],
            ),
          ),
          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 _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),
        child: Column(
          children: [
            Row(
              children: [
                Text(
                  '紧急程度：',
                  style: TextStyle(
                    color: GSYColors.primaryLightValue,
                    fontSize: GSYConstant.TextSize15,
                  ),
                ),
                Radio(
                  value: 1,
                  groupValue: groupValue,
                  onChanged: (value) {
                    // groupValue = value;
                    setState(() {
                      groupValue = value!;
                    });
                  },
                ),
                Text("一般",
                    style: TextStyle(
                      color: GSYColors.primaryLightValue,
                      fontSize: GSYConstant.TextSize15,
                    )),
                Radio(
                  value: 2,
                  groupValue: groupValue,
                  onChanged: (value) {
                    // groupValue = value;
                    setState(() {
                      groupValue = value!;
                    });
                  },
                ),
                Text("紧急",
                    style: TextStyle(
                      color: GSYColors.primaryLightValue,
                      fontSize: GSYConstant.smallTextSize,
                    ))
              ],
            ),
            const SizedBox(
              height: 10,
            ),
            Row(children: [
              Text(
                '报修主题：',
                style: TextStyle(
                  color: GSYColors.primaryLightValue,
                  fontSize: GSYConstant.TextSize15,
                ),
              ),
              const SizedBox(
                width: 15,
              ),
              Container(
                height: 40,
                width: MediaQuery.of(context).size.width / 2 +
                    MediaQuery.of(context).size.width / 8,
                child: TextField(
                  decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      hintText: '请输入报修主题',
                      contentPadding: EdgeInsets.only(
                          bottom: 20, left: 10 // HERE THE IMPORTANT PART
                          )),
                  style: TextStyle(fontSize: 14),
                  textAlignVertical: TextAlignVertical.center,
                  textAlign: TextAlign.left,
                  onChanged: (value) {
                    theme = value;
                  },
                ),
              )
            ]),
            const SizedBox(
              height: 10,
            ),
          ],
        ),
      )
    ]);
  }

  Widget _patrolAddTitle() {
    return 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) => new RepairJobDeviceList()));
              },
              child: Row(
                children: [
                  new Icon(Icons.add),
                  new Text(
                    '选择设备',
                    style: TextStyle(
                      color: Colors.blue,
                      fontSize: GSYConstant.TextSize15,
                    ),
                    textAlign: TextAlign.right,
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _patrolAdd() {
    return Container(
      padding: EdgeInsets.only(top: 15, bottom: 15, left: 12, right: 12),
      color: Colors.white,
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        Container(
          child: Text(
            _dataList.showName,
            style: const TextStyle(
              color: Colors.black,
              fontSize: GSYConstant.middleTextWhiteSize,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        Container(
          padding: EdgeInsets.only(top: 3, bottom: 3, left: 5, right: 5),
          child: Text(
            _dataList.status == 0
                ? '在线'
                : _dataList.status == 1
                    ? '离线'
                    : _dataList.status == 2
                        ? '未激活'
                        : '未知',
            textAlign: TextAlign.right,
            style: TextStyle(
              color: _dataList.status == 0
                  ? Colors.blue
                  : _dataList.status == 1
                      ? Colors.orange
                      : _dataList.status == 2
                          ? Colors.red
                          : Colors.black,
              fontSize: GSYConstant.minTextSize,
            ),
          ),
          decoration: BoxDecoration(
            border: new Border.all(
              color: _dataList.status == 0
                  ? Colors.blue
                  : _dataList.status == 1
                      ? Colors.orange
                      : _dataList.status == 2
                          ? Colors.red
                          : Colors.black, //边框颜色
              width: 1.0, //边框粗细
            ),
            borderRadius:
                const BorderRadius.all(const Radius.circular(3.0)), //边框的弧度
          ),
        )
      ]),
    );
  }

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

  patrolJobRemark() async {
    var result = await DioUtil()
        .request('repair-bill/create', method: DioMethod.post, data: {
      'deviceId': _dataList.id,
      'repairImgIds': mList,
      'instructions': note,
      'urg': groupValue,
      'theme': theme
    });
    if (result['code'] == 0) {
      setState(() {
        eventBus.fire(RefreshRepairPage());
        Navigator.pop(context);
      });
    } else {
      showToast(result['msg']);
    }
  }

  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']);
    }
  }
}
