import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tzh/base/YSBase.dart';
import 'package:flutter_tzh/home/view/YSInputView.dart';
import 'package:flutter_tzh/tool/YSDatePicker.dart';
import 'package:flutter_tzh/tool/YSNetWork.dart';
import 'package:flutter_tzh/tool/YSTools.dart';

import '../base/YSTabBar.dart';

class YSGather extends StatefulWidget {
  const YSGather({Key? key}) : super(key: key);

  @override
  YSGatherState createState() => YSGatherState();
}

class YSGatherState extends State<YSGather> {
  final List _dataArray = [
    {'title':'地块','type':1,'key':'landId'},
    {'title':'采样计划名称','type':2,'controller':TextEditingController(),'key':'name'},
    {'title':'收件人','type':2,'controller':TextEditingController(),'key':'email'},
    {'title':'主题','type':2,'controller':TextEditingController(),'key':'subject'},
    {'title':'取样时间范围','type':1,'key':'time'},
    {'title':'采样内容','type':2,'key':'content'},
    {'title':'邮件内容','type':3,'key':'text'}
  ];
  bool _isAlert = false;
  List _info = [];
  String _dk = '[地块]';
  String _sj = '[采样时间]';
  String _text = '';
  _getContent() {
    Map nr = _dataArray.firstWhere((element) => element['title']=='邮件内容');
    String content = nr['value']??'';
    Map dk = _dataArray.firstWhere((element) => element['title']=='地块');
    if(dk['valueLabel']!=null){
      _dk = '[${dk['valueLabel']}]';
    }
    Map fw = _dataArray.firstWhere((element) => element['title']=='取样时间范围');
    if(fw['valueLabel']!=null){
      _sj = '[${fw['valueLabel']}]';
    }
    content = '$_text 我们计划在$_sj对$_dk进行采样工作，以收集必要的数据和样本。这次采样旨在了解地块的土壤、水质或其他相关特征\n'
        '您的参与对于确保采样的准确性和可靠性非常重要。我们邀请您到场并全程参与采样工作。您的专业知识和经验将为我们的研究提供宝贵的支持。\n'
        '请您在$_sj准时到达采样地点。如有需要，请提前做好一切准备工作，确保您能够充分发挥自己的专业能力。如果您需要携带任何特定的工具或个人保护装备，请务必提前告知我们。\n'
        '谢谢！';
    nr['value'] = content;
    LogUtil.d(nr);
    setState(() {});
  }
  _getUserTemplate() async{
    YSNetWork.ysRequestHttp(context, type: RequestType.get, api: '/user/template', parameter: {}, successSetter: (dict){
      Map data = dict['data'];
      _info = data['info']??[];
      if(_info.isNotEmpty){
        Map zt = _dataArray.firstWhere((element) => element['title']=='主题');
        TextEditingController ztController = zt['controller'];
        zt['value'] = data['subject'];
        ztController.text = data['subject']??'';
        _text = data['text'];
      }

    });
  }
  @override
  void initState() {
    networkDelay((){
      _getUserTemplate();
    });
    super.initState();
  }
  @override
  void dispose() {
    for (var element in _dataArray) {
      TextEditingController controller = element['controller']??TextEditingController();
      controller.dispose();
    }
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: YSBase(
        ysTitle: '新建土地',
        ysChild: GestureDetector(
          onTap: (){
            _isAlert = false;
            setState(() {});
          },
          child: SingleChildScrollView(
            child: Stack(
              children: [
                Column(
                  children: [
                    SizedBox(
                      height: ysHeight(context)-ysTOP(context)-44-hsp(72),
                      child: ListView.separated(
                        itemBuilder: (context, index) {
                          Map item = _dataArray[index];
                          return LayoutBuilder(builder: (context, constraints) {
                            return Container(
                              padding: EdgeInsets.only(left: hsp(12),right: hsp(12),top: hsp(5),bottom: hsp(5)),
                              decoration: BoxDecoration(
                                  color: const Color(0xFF1A1C1F),
                                  borderRadius: const BorderRadius.all(Radius.circular(3)),
                                  border: Border.all(color: const Color(0xFF3E434E),width: hsp(1))
                              ),
                              child: item['type']==1?GestureDetector(
                                onTap: () {
                                  FocusScope.of(context).unfocus();
                                  if(item['title']=='取样时间范围'){
                                    showDateRangePicker(
                                      context: context,
                                      firstDate: DateTime.now(),
                                      lastDate: DateTime.now().add(const Duration(days: 10000)),
                                      builder: (context,child){
                                        return Theme(data: Theme.of(context).copyWith(
                                          appBarTheme: Theme.of(context).appBarTheme.copyWith(backgroundColor: const Color(0xFF23262B)),
                                          scaffoldBackgroundColor: const Color(0xFF23262B),
                                          textTheme: Theme.of(context).textTheme.copyWith(
                                            bodyText2: TextStyle(fontSize: zsp(14),color: Colors.white),
                                          ),
                                          colorScheme: Theme.of(context).colorScheme.copyWith(primary: const Color(0xFF31D19E),onSurface: Colors.grey)
                                        ), child: child!);
                                        // return Theme(
                                        //   data: ThemeData.dark(),
                                        //   child: child!,
                                        // );
                                      },
                                      initialEntryMode: DatePickerEntryMode.calendarOnly,
                                    ).then((value) {
                                      if(value!=null){
                                        String start = timeFormat(value.start.millisecondsSinceEpoch,format: 'yyyy-MM-dd');
                                        String end = timeFormat(value.end.millisecondsSinceEpoch,format: 'yyyy-MM-dd');
                                        item['valueLabel'] = '$start - $end';
                                        item['value'] = start;
                                        item['value2'] = end;
                                        _getContent();
                                      }
                                    });
                                  }else if(item['title']=='地块'){
                                    FocusScope.of(context).unfocus();
                                    _isAlert = !_isAlert;
                                    setState(() {});
                                    // ysShowCenterAlertView(context, Container(
                                    //   height: hsp(200),
                                    //   color: Colors.white,
                                    //   margin: EdgeInsets.only(top: ysTOP(context)+44+hsp(76),left: hsp(20),right: hsp(20),bottom: (ysHeight(context)-ysTOP(context)-44-hsp(76))*0.5),
                                    // ),isTrans: true,isBarr: true);
                                  }
                                },
                                behavior: HitTestBehavior.opaque,
                                child: Row(
                                  children: [
                                    SizedBox(
                                      width: constraints.maxWidth-hsp(39),
                                      child: Column(
                                        mainAxisSize: MainAxisSize.min,
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text(item['title'],style: TextStyle(fontSize: zsp(11),color: const Color(0xFFACB5C5)),),
                                          SizedBox(
                                            height: hsp(20),
                                            child: Text(item['valueLabel']??item['value']??'请选择${item['title']}',style: TextStyle(fontSize: zsp(16),color: Colors.white),),
                                          )
                                        ],
                                      ),
                                    ),
                                    Image.asset('images/tzh_down.png',height: hsp(10),width: hsp(10),)
                                  ],
                                ),
                              ):Column(
                                mainAxisSize: MainAxisSize.min,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(item['title'],style: TextStyle(fontSize: zsp(11),color: const Color(0xFFACB5C5)),),
                                  item['type']==3?YSInputView2(
                                    key: Key('${item['value']}'),
                                    item: item,
                                    length: 300,
                                    height: 200,
                                  ):SizedBox(
                                    height: hsp(20),
                                    child: item['type']==4?Text(
                                      item['value']??'',style: TextStyle(fontSize: zsp(16),color: Colors.white),
                                    ):CupertinoTextField(
                                      placeholder: '请输入${item['title']}',
                                      style: TextStyle(fontSize: zsp(16),color: Colors.white),
                                      padding: const EdgeInsets.all(0),
                                      placeholderStyle: TextStyle(fontSize: zsp(16),color: Colors.white),
                                      decoration: const BoxDecoration(
                                        color: Colors.transparent
                                      ),
                                      maxLines: 100,
                                      onChanged: (value){
                                        if(value.isNotEmpty){
                                          item['value'] = value;
                                        }else{
                                          item.remove('value');
                                        }
                                      },
                                      controller: item['controller'],
                                    )
                                  )
                                ],
                              ),
                            );
                          });
                        },
                        separatorBuilder: (context,index){
                          return Container(height: hsp(12),);
                        },
                        itemCount: _dataArray.length,
                        padding: EdgeInsets.only(left: hsp(20),right: hsp(20),top: hsp(30)),
                      ),
                    ),
                    GestureDetector(
                      onTap: (){
                        LogUtil.d(_dataArray);
                        Map request = {};
                        for (var element in _dataArray) {
                          if(element['value']==null){
                            ysFlutterToast('请完善${element['title']}');
                            return;
                          }else{
                            if(element['key']=='time'){
                              request['startTime'] = element['value'];
                              request['endTime'] = element['value2'];
                            }else{
                              request[element['key']] = element['value'];
                            }
                          }
                        }
                        LogUtil.d(request);
                        YSNetWork.ysRequestHttp(context, type: RequestType.post, api: '/samp/add', parameter: request, successSetter: (dict){
                          ysFlutterToast('新增采样成功');
                          Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context){
                            return const YSTabBar();
                          }), (route) => false);
                        },isLoading: true);
                      },
                      behavior: HitTestBehavior.opaque,
                      child: SizedBox(
                        height: hsp(72),
                        child: Image.asset('images/continue.png'),
                      ),
                    )
                  ],
                ),
                if(_isAlert)Container(
                  width: ysWidth(context)-hsp(40),
                  color: const Color(0xFF1A1C1F),
                  margin: EdgeInsets.only(top: hsp(76),left: hsp(20)),
                  child: ListView.builder(
                    itemBuilder: (context, index) {
                      Map item = _info[index];
                      return GestureDetector(
                        onTap: (){
                          _isAlert = false;
                          Map dk = _dataArray.firstWhere((element) => element['title']=='地块');
                          Map sjr = _dataArray.firstWhere((element) => element['title']=='收件人');
                          dk['value'] = '${item['landId']}';
                          dk['valueLabel'] = '${item['name']}';
                          sjr['value'] = item['email'];
                          TextEditingController controller = sjr['controller'];
                          controller.text = sjr['value'];
                          _getContent();
                        },
                        behavior: HitTestBehavior.opaque,
                        child: Container(
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.only(left: hsp(12),right: hsp(12)),
                          height: hsp(46),
                          decoration: BoxDecoration(
                              border: Border.all(color: const Color(0xFF3E434E),width: hsp(1))
                          ),
                          child: Text(item['name']??'',style: TextStyle(fontSize: zsp(16),color: Colors.white),),
                        ),
                      );
                    },
                    itemCount: _info.length,
                    padding: const EdgeInsets.all(0),
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
