import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tzh/base/YSBase.dart';
import 'package:flutter_tzh/home/YSHomeListDetailEmail.dart';
import 'package:flutter_tzh/home/YSHomeListDetailGather.dart';
import 'package:flutter_tzh/tool/YSAlertView.dart';
import 'package:flutter_tzh/tool/YSNetWork.dart';

import '../tool/YSTools.dart';

class YSHomeListDetail extends StatefulWidget {
  final String itemId;
  const YSHomeListDetail({Key? key, required this.itemId}) : super(key: key);

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

class YSHomeListDetailState extends State<YSHomeListDetail> {
  final List _dataArray = [
    {'title':'','array':[
      {'title':'编号','value':'','key':'planNum'},
      {'title':'计划','value':'','key':'name'},
      {'title':'状态','value':'','key':'status'},
      {'title':'取样时间','value':'','key':'time'}
    ]},
    {'title':'地块信息','array':[
      {'title':'地块编号','value':'','key':'landId'},
      {'title':'地块名称','value':'','key':'landName'},
      {'title':'地址','value':'','key':'address'}
    ]},
  ];
  List _samplingPoint = [];
  bool _isShow = false;
  String _planNum = '0';
  @override
  void initState() {
    networkDelay((){
      _getDetailData();
    });
    super.initState();
  }
  _getDetailData() async{
    YSNetWork.ysRequestHttp(context, type: RequestType.get, api: '/samplingPoint/index', parameter: {'planNum':widget.itemId}, successSetter: (dict){
      Map data = dict['data']??[];
      Map sampling = data['sampling']??{};
      _planNum = sampling['planNum'];
      _samplingPoint = data['samplingPoint']??[];
      for (var element in _dataArray) {
        List array = element['array']??[];
        for (var elementSub in array) {
          if(elementSub['key']=='status'){
            elementSub['value'] = statusString(sampling['status']);
          }else if(elementSub['key']=='time'){
            elementSub['value'] = '${sampling['startTime']??''} - ${sampling['endTime']??''}';
          }else{
            elementSub['value'] = '${sampling[elementSub['key']]??''}';
          }
        }
      }
      _getButton(sampling['status']??0);
      setState(() {});
    });
  }
  _getButton(int status) {
    bool isShow = true;
    for (var element in _samplingPoint) {
      if(element['status']==0){
        isShow = false;
        break;
      }
    }
    _isShow = isShow&&status==3;
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ysTitle: '碳排放检测',
      ysChild: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(
              height: ysHeight(context)-ysTOP(context)-44-hsp(_isShow?72:0),
              child: SingleChildScrollView(
                padding: EdgeInsets.only(left: hsp(20),right: hsp(20),top: hsp(20)),
                child: Column(
                  children: [
                    ListView.separated(
                      itemBuilder: (context, index) {
                        Map item = _dataArray[index];
                        List array = item['array']??[];
                        return Container(
                          padding: EdgeInsets.all(hsp(15)),
                          decoration: BoxDecoration(
                              color: const Color(0xFF2E3138),
                              borderRadius: const BorderRadius.all(Radius.circular(24)),
                              border: Border.all(color: const Color(0xFF3E434E),width: hsp(1))
                          ),
                          child: Column(
                            children: [
                              if('${item['title']}'.isNotEmpty)Container(
                                height: hsp(30),
                                alignment: Alignment.centerLeft,
                                child: Text('${item['title']}',style: TextStyle(fontSize: zsp(14),color: const Color(0xFFDBE1EA)),),
                              ),
                              ListView.builder(
                                itemBuilder: (context, indexSub) {
                                  Map itemSub = array[indexSub];
                                  return Container(
                                    padding: EdgeInsets.only(top: hsp(5),bottom: hsp(5)),
                                    // height: hsp(30),
                                    child: LayoutBuilder(builder: (context,conSize){
                                      return Row(
                                        children: [
                                          SizedBox(
                                            width: conSize.maxWidth*0.3,
                                            child: Text('${itemSub['title']}:',style: TextStyle(fontSize: zsp(14),color: ysTitleColor),),
                                          ),
                                          Container(
                                            width: conSize.maxWidth*0.7,
                                            alignment: Alignment.centerRight,
                                            child: Text(itemSub['value']??'',style: TextStyle(fontSize: zsp(14),color: ysValueColor),),
                                          )
                                        ],
                                      );
                                    }),
                                  );
                                },
                                itemCount: array.length,
                                padding: const EdgeInsets.all(0),
                                physics: const NeverScrollableScrollPhysics(),
                                shrinkWrap: true,
                              )
                            ],
                          ),
                        );
                      },
                      separatorBuilder: (context,index){
                        return Container(height: hsp(12),);
                      },
                      itemCount: _dataArray.length,
                      shrinkWrap: true,
                      padding: EdgeInsets.only(bottom: hsp(12)),
                      physics: const NeverScrollableScrollPhysics(),
                    ),
                    Container(
                      padding: EdgeInsets.all(hsp(15)),
                      decoration: BoxDecoration(
                        color: const Color(0xFF2E3138),
                        borderRadius: const BorderRadius.all(Radius.circular(24)),
                        border: Border.all(color: const Color(0xFF3E434E),width: hsp(1))
                      ),
                      child: Column(
                        children: [
                          Container(
                            height: hsp(30),
                            alignment: Alignment.centerLeft,
                            child: Text('取样点列表（${_samplingPoint.length}个）',style: TextStyle(fontSize: zsp(14),color: const Color(0xFFDBE1EA)),),
                          ),
                          SizedBox(
                            height: hsp(30),
                            child: LayoutBuilder(builder: (context,conSize){
                              return Row(
                                children: [
                                  Container(
                                    width: conSize.maxWidth*0.25,
                                    alignment: Alignment.center,
                                    child: Text('取样点',style: TextStyle(fontSize: zsp(14),color: ysTitleColor),),
                                  ),
                                  Container(
                                    width: conSize.maxWidth*0.25,
                                    alignment: Alignment.center,
                                    child: Text('状态',style: TextStyle(fontSize: zsp(14),color: ysTitleColor),),
                                  ),
                                  Container(
                                    width: conSize.maxWidth*0.25,
                                    alignment: Alignment.center,
                                    child: Text('采样时间',style: TextStyle(fontSize: zsp(14),color: ysTitleColor),),
                                  ),
                                  Container(
                                    width: conSize.maxWidth*0.25,
                                    alignment: Alignment.center,
                                    child: Text('操作',style: TextStyle(fontSize: zsp(14),color: ysTitleColor),),
                                  ),
                                ],
                              );
                            }),
                          ),
                          ListView.separated(
                            itemBuilder: (context, indexSub) {
                              Map item = _samplingPoint[indexSub];
                              return SizedBox(
                                child: LayoutBuilder(builder: (context,conSize){
                                  return Row(
                                    children: [
                                      Container(
                                        width: conSize.maxWidth*0.25,
                                        alignment: Alignment.center,
                                        child: Text('${item['name']}',style: TextStyle(fontSize: zsp(14),color: ysValueColor),),
                                      ),
                                      Container(
                                        width: conSize.maxWidth*0.25,
                                        alignment: Alignment.center,
                                        child: Text(item['status']==0?'待采样':'已采样',style: TextStyle(fontSize: zsp(14),color: ysValueColor),),
                                      ),
                                      Container(
                                        width: conSize.maxWidth*0.25,
                                        alignment: Alignment.center,
                                        child: Text('${item['sampleTime']??''}',style: TextStyle(fontSize: zsp(14),color: ysValueColor),),
                                      ),
                                      GestureDetector(
                                        onTap: (){
                                          if(item['status']==0){
                                            Navigator.of(context).push(
                                                CupertinoPageRoute(builder: (context){
                                                  return YSHomeListDetailGather4(gatherId: item['id'],);
                                                })
                                            ).then((value) {
                                              if(value!=null){
                                                _getDetailData();
                                              }
                                            });
                                          }else{
                                            Navigator.of(context).push(
                                                CupertinoPageRoute(builder: (context){
                                                  return YSHomeListDetailGather5(gatherId: item['id'],);
                                                })
                                            ).then((value) {
                                              if(value!=null){
                                                _getDetailData();
                                              }
                                            });
                                          }
                                        },
                                        behavior: HitTestBehavior.opaque,
                                        child: Container(
                                          width: conSize.maxWidth*0.2,
                                          margin: EdgeInsets.only(left: hsp(10)),
                                          alignment: Alignment.center,
                                          decoration: BoxDecoration(
                                              gradient: const LinearGradient(colors: [Color(0xFF2E3138),Color(0xFF535966)]),
                                              border: Border.all(color: const Color(0xFF1A1C1F),width: hsp(1)),
                                              borderRadius: const BorderRadius.all(Radius.circular(5))
                                          ),
                                          child: Row(
                                            mainAxisSize: MainAxisSize.min,
                                            crossAxisAlignment: CrossAxisAlignment.end,
                                            children: [
                                              SizedBox(
                                                child: Text(item['status']==0?'采样':'详情',style: TextStyle(fontSize: zsp(14),color: ysValueColor),),
                                              ),
                                              Icon(Icons.chevron_right,size: hsp(20),color: const Color(0xFFACB5C5),)
                                            ],
                                          ),
                                        ),
                                      ),
                                    ],
                                  );
                                }),
                              );
                            },
                            separatorBuilder: (context,index){
                              return Container(height: hsp(5),);
                            },
                            itemCount: _samplingPoint.length,
                            padding: const EdgeInsets.all(0),
                            physics: const NeverScrollableScrollPhysics(),
                            shrinkWrap: true,
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
            if(_isShow)GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: (){
                LogUtil.d(_samplingPoint);
                int index = 9999;
                for (var element in _samplingPoint) {
                  if(element['value']==null){
                    index = _samplingPoint.indexOf(element);
                    break;
                  }
                }
                String tipsStr = '是否需要邮寄样本？';
                LogUtil.d(index);
                ysShowCenterAlertView(context, YSTipsAlertView(
                  valueSetter: (bool value) async{
                    if(value){
                      Navigator.of(context).push(
                          CupertinoPageRoute(builder: (context){
                            return YSHomeListDetailEmail(planNum: _planNum,);
                          })
                      ).then((value) {
                        if(value!=null){
                          _getDetailData();
                        }
                      });
                    }else{
                      if(index==9999){
                        YSNetWork.ysRequestHttp(context, type: RequestType.get, api: '/samp/complete', parameter: {'planNum':_planNum}, successSetter: (dict){
                          _getDetailData();
                        });
                      }else{
                        ysFlutterToast('请完善${_samplingPoint[index]['name']}的有机土壤碳');
                      }
                    }

                  },
                  tipsStr: tipsStr,
                ));
              },
              child: Image.asset('images/tzh_done.png',height: hsp(72),),
            )
          ],
        ),
      ),
    );
  }
}
