
import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterappfuyou/code/YSChapters.dart';
import 'package:flutterappfuyou/code/base/YSNetWorking.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../YSPage.dart';
import 'YSChoose.dart';
import 'YSHospital.dart';
import 'YSHospitalDetail.dart';
import 'base/YSBase.dart';
import 'base/YSTools.dart';

class YSMeans extends StatefulWidget {
  final bool isEdit;
  final bool isFirst;
  const YSMeans({Key key, this.isEdit, this.isFirst = false}) : super(key: key);
  @override
  _YSMeansState createState() => _YSMeansState();
}

class _YSMeansState extends State<YSMeans> {//,{'title':'手机号码：','content':'请输入手机号码'}
  final ImagePicker _picker = ImagePicker();
  List dataArray = [{'title':'居住地：','content':'请选择居住地址'},{'title':'详细地址：','content':'请输入详细地址'},{'title':'选择卫生院：','content':'请选择卫生院'},
    {'title':'女方姓名：','content':'请输入姓名'},{'title':'证件类型：','content':'居民身份证'},{'title':'证件号码：','content':'请输入证件号码'}];
  String _place,_hospital,_street;
  Map _hospitalDetail = {};
  TextEditingController _location = TextEditingController();
  TextEditingController _name = TextEditingController();
  TextEditingController _number = TextEditingController();
  TextEditingController _phone = TextEditingController();
  int _hospitalId,_placeId,_streetId;
  int _type = 1;
  String _cardType = '居民身份证';
  bool _isCanChange = true;
  @override
  void initState() {
    Future.delayed(Duration(seconds: 0)).then((value){
      getVersionData(context);
      if(widget.isEdit==true){
        _getUserData();
      }
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      isBack: widget.isFirst==false,
      ystitle: '完善资料',
      yschild: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              height: MediaQuery.of(context).size.height-155,
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(
                      height: 45,
                      width: MediaQuery.of(context).size.width,
                      alignment: Alignment.center,
                      padding: EdgeInsets.all(15),
                      child: Text('请完善以下信息，信息将用于查询医疗档案！',style: TextStyle(fontSize: 10,color: Color(0xFFEF6E92),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                    ),
                    Container(
                      width: MediaQuery.of(context).size.width,
                      height: 1.5,
                      child: Image.asset('lib/images/line.png'),
                    ),
                    Container(
                      height: 51.5*dataArray.length,
                      child: ListView.separated(
                        itemBuilder: (context,index){
                          return Container(
                            height: 50,
                            width: MediaQuery.of(context).size.width,
                            padding: EdgeInsets.only(left: 15,right: 15,top: index==1?5:15,bottom: index==1?5:15),
                            child: index==1?Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text((dataArray[index]['title']).toString(),style: TextStyle(fontSize: 14,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                                CupertinoTextField(
                                  style: TextStyle(fontSize: 11,color: Color(0xFF77808F),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                                  placeholder: (dataArray[index]['content']).toString(),
                                  placeholderStyle: TextStyle(fontSize: 11,color: Color(0xFF77808F),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                                  padding: EdgeInsets.all(0),
                                  decoration: BoxDecoration(),
                                  controller: _location,
                                )
                              ],
                            ):Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text((dataArray[index]['title']).toString(),style: TextStyle(fontSize: 14,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                                if (index==0||index==2||index==4) GestureDetector(
                                  child: Row(
                                    children: [
                                      Text((index==0&&_place!=null)?'$_place $_street':(index==2&&_hospital!=null)?_hospital:(index==4&&_cardType!=null)?_cardType:(dataArray[index]['content']).toString(),
                                        style: TextStyle(fontSize: 14,color: (index==2&&_hospital==null)?Colors.red:(index==4&&_isCanChange==false)?Color(0xFF969799).withOpacity(0.5):Color(0xFF77808F),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                      index==4&&_isCanChange==false?Container():Icon(Icons.keyboard_arrow_right,size: 20,color: Color((0xFFAEB3BD)),)
                                    ],
                                  ),
                                  onTap: (){
                                    if(index==4&&_isCanChange==false)return;
                                    Navigator.of(context).push(
                                        CupertinoPageRoute(
                                          builder: (context){
                                            if(index==0){
                                              return YSChooseArea();
                                            }else if(index==2){
                                              return _hospital==null?YSHospital(healthId: _hospitalId, areaId: _placeId,):YSHospitalDetail(healthId: _hospitalId,);
                                            }else{
                                              return YSChooseType();
                                            }
                                          }
                                        )
                                    ).then((value){
                                      if(index==2){
                                        _getUserData2();
                                      }else if(value!=null){
                                        if(index==0){
                                          print('$value');
                                          _hospitalId = null;
                                          _hospital = null;
                                          // _hospitalId = value['healthId'];
                                          _placeId = value['areaId'];
                                          _streetId = value['streetId'];
                                          // _hospital = value['health'];
                                          _place = value['area'];
                                          _street = value['street'];
                                          setState(() {});
                                          // _getHospitalDetail(_hospitalId);
                                        }else if(index==2){
                                          print('$value');
                                          _hospitalId = value['id'];
                                          _hospital = value['name'];
                                          _getHospitalDetail(_hospitalId);
                                        }else{
                                          LogUtil.d(value);
                                          _cardType = value;
                                          _type = _cardType=='居民身份证'?1:_cardType=='军人身份证'?2:_cardType=='护照'?3:_cardType=='港澳居民来往内地通行证'?4:_cardType=='台湾居民来往大陆通行证'?5
                                              :_cardType=='中华人民共和国旅行证'?6:7;
                                          setState(() {
                                            dataArray[4] = {'title':'证件类型：','content':value};
                                          });
                                        }
                                      }
                                    });
                                  },
                                  behavior: HitTestBehavior.opaque,
                                ) else index==5?Row(
                                  children: [
                                    Container(
                                      height: 20,
                                      width: 170,
                                      child: _isCanChange?CupertinoTextField(
                                        style: TextStyle(fontSize: 14,color: _isCanChange?Color(0xFF77808F):Color(0xFF969799).withOpacity(0.5),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                                        placeholder: dataArray[4]['content']=='居民身份证'?'请拍摄身份证正面照片':(dataArray[index]['content']).toString(),
                                        placeholderStyle: TextStyle(fontSize: 14,color: Color(0xFF77808F),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                                        padding: EdgeInsets.all(0),
                                        decoration: BoxDecoration(color: Colors.transparent),
                                        textAlign: TextAlign.right,
                                        controller: _number,
                                        enabled: _isCanChange,
                                        keyboardType: TextInputType.number,
                                      ):Text(_number.text,style: TextStyle(fontSize: 14,color: Color(0xFF969799).withOpacity(0.5),
                                          decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                      alignment: Alignment.centerRight,
                                    ),
                                    dataArray[4]['content']=='居民身份证'&&_isCanChange?CupertinoButton(
                                      child: Image(height: 20,width: 20,image: AssetImage('lib/images/camer.png'),),padding: EdgeInsets.all(0),
                                      onPressed: (){
                                        showCupertinoModalPopup(
                                            context: context,
                                            builder: (context) {
                                              return CupertinoActionSheet(
                                                actions: <Widget>[
                                                  CupertinoActionSheetAction(
                                                    child: Text('相机'),
                                                    onPressed: () {
                                                      Navigator.pop(context);
                                                      _picker.getImage(source: ImageSource.camera).then((value){
                                                        _uploadImageData(value);
                                                      });
                                                    },
                                                  ),
                                                  CupertinoActionSheetAction(
                                                    child: Text('相册'),
                                                    onPressed: () {
                                                      Navigator.pop(context);
                                                      _picker.getImage(source: ImageSource.gallery).then((value){
                                                        _uploadImageData(value);
                                                      });
                                                    },
                                                  ),
                                                ],
                                                cancelButton: CupertinoActionSheetAction(
                                                  child: Text('取消'),
                                                  onPressed: () {
                                                    Navigator.pop(context);
                                                  },
                                                ),
                                              );
                                            }
                                        );
                                      },
                                    ):Container()
                                  ],
                                ):Container(
                                  height: 20,
                                  width: 200,
                                  child: CupertinoTextField(
                                    style: TextStyle(fontSize: 14,color: Color(0xFF77808F),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                                    placeholder: (dataArray[index]['content']).toString(),
                                    placeholderStyle: TextStyle(fontSize: 14,color: Color(0xFF77808F),decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                                    padding: EdgeInsets.all(0),
                                    decoration: BoxDecoration(),
                                    textAlign: TextAlign.right,
                                    controller: index==3?_name:_phone,
                                  ),
                                ),
                              ],
                            )
                          );
                        },
                        separatorBuilder: (context,index){
                          return Container(
                            width: MediaQuery.of(context).size.width,
                            height: 1.5,
                            child: Image.asset('lib/images/line.png'),
                          );
                        },
                        itemCount: dataArray.length,
                        physics: NeverScrollableScrollPhysics(),
                        padding: EdgeInsets.all(0),
                      ),
                    ),
                    Container(
                      width: MediaQuery.of(context).size.width,
                      height: 1.5,
                      child: Image.asset('lib/images/line.png'),
                    ),
                    if(_hospital!=null)Container(
                      height: 50,
                      padding: EdgeInsets.only(left: 15),
                      alignment: Alignment.center,
                      child: Text('$_hospital服务范围',
                        style: TextStyle(fontSize: 14,color: Color(0xFF77808F),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                    ),
                    // if(_hospital!=null)Container(
                    //   width: MediaQuery.of(context).size.width,
                    //   height: 1.5,
                    //   child: Image.asset('lib/images/line.png'),
                    // ),
                    if(_hospitalDetail.isNotEmpty)Padding(
                      padding: EdgeInsets.only(left: 15,right: 15),
                      child: DottedBorder(
                        color: Color(0xFFFF6D96),
                        borderType: BorderType.RRect,
                        radius: Radius.circular(9),
                        strokeWidth: 1,
                        child: Container(
                          height: ysHeight(context)-ysTOP(context)-241.5-51.5*dataArray.length,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            color: Color(0xFFE96D8F).withOpacity(0.1),
                            borderRadius: BorderRadius.all(Radius.circular(9))
                          ),
                          child: SingleChildScrollView(
                            padding: EdgeInsets.all(10),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(_hospitalDetail['jurisdiction'],style: TextStyle(fontSize: 14,color: Colors.black,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                Text('\n地址：${_hospitalDetail['address']}\n',style: TextStyle(fontSize: 14,color: Colors.black,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                Text('咨询电话：${_hospitalDetail['contacts']}\n',style: TextStyle(fontSize: 14,color: Colors.black,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                              ],
                            ),
                          )
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Container(
              height: 70,
              child: CupertinoButton(
                padding: EdgeInsets.only(bottom: 20),
                child: Container(
                  width: MediaQuery.of(context).size.width-150,
                  height: 40,
                  decoration: BoxDecoration(
                    color: Color(0xFFEA6C8F),
                    borderRadius: BorderRadius.all(Radius.circular(20))
                  ),
                  alignment: Alignment.center,
                  child: Text('完成',style: TextStyle(fontSize: 16,color: Colors.white,decoration: TextDecoration.none),),
                ),
                onPressed: (){
                  _postUserInfo();
                },
              ),
            )
          ],
        ),
      ),
    );
  }

  _uploadImageData(var image) async{
    ysUploadFile(context,path: image.path,type: 'idcard',setter: (value) async{
      Map diction = await ysRequestHttp(context, requestType.post, 'sign/idcard', {'path':value['path']});
      if(diction!=null){
        _number.text = '${diction['data']['id_card']}';
        _name.text = '${diction['data']['name']}';
      }
    });
    // var dict = await ysRequestHttpNoLoading(context, requestType.get, 'upQiniuToken', {'type':'idcard'});
    // if(dict!=null){
    //   var result = await syStorage.upload('${image.path}', '${dict['token']}', '${dict['path']}');
    //   print('$result');
    //   if(result.success==true){
    //     Map diction = await ysRequestHttp(context, requestType.post, 'sign/idcard', {'path':dict['path']});
    //     if(diction!=null){
    //       _number.text = '${diction['data']['id_card']}';
    //     }
    //   }
    // }
  }

  _postUserInfo() async{
    FocusScope.of(context).unfocus();
    Map request = {};
    if(_placeId==null){
      ysFlutterToast(context, '请选择居住地');
      return;
    }
    if(_location.text.isEmpty){
      ysFlutterToast(context, '详细地址不能为空');
      return;
    }
    request['region_id'] = _placeId;
    request['area_id'] = _streetId;
    if(_location.text!=null||_location.text.isNotEmpty){
      request['address'] = _location.text;
    }
    if(_hospitalId==null){
      ysFlutterToast(context, '请选择卫生院');
      return;
    }
    request['health_id'] = _hospitalId;
    if(_name.text==null||_name.text.isEmpty){
      ysFlutterToast(context, '请输入女方姓名');
      return;
    }
    request['name'] = _name.text;
    if(_type!=null){
      request['id_card_type'] = _type;
    }
    if(_number.text==null||_number.text.isEmpty){
      ysFlutterToast(context, '请完善证件号码');
      return;
    }
    request['id_card'] = _number.text;
    // if(_phone.text==null||_phone.text.isEmpty){
    //   ysFlutterToast(context, '请输入手机号码');
    //   return;
    // }
    // request['phone'] = _phone.text;
    Map dict = await ysRequestHttp(context, requestType.post, 'user/info', request);
    if(dict!=null){
      if(widget.isEdit==true){
        Navigator.pop(context);
      }else{
        SharedPreferences _prefer = await SharedPreferences.getInstance();
        int chapters = _prefer.getInt('chapters');
        _prefer.setBool('isMeans', true);
        if(chapters==null){
          Navigator.pushAndRemoveUntil(context, MaterialPageRoute(
              builder: (context){
                return YSChapters(isFirst: true,);
              }
          ), (route) => false);
        }else{
          Navigator.pushAndRemoveUntil(context, MaterialPageRoute(
              builder: (context){
                return YSPage();
              }
          ), (route) => false);
        }
      }
    }
  }

  _getUserData() async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.get, 'user/info', {});
    if(dict!=null){
      _type = dict['id_card_type'];
      _placeId = dict['region_id'];
      _hospitalId = dict['health_id'];
      _streetId = dict['area_id'];
      _isCanChange = dict['is_can_change_id_card']??true;
      if(_hospitalId!=null){
        _getHospitalDetail(_hospitalId);
      }
      setState(() {
        _street = dict['area_name']!=null?'${dict['area_name']}':'';
        _place = dict['region_name']!=null?'${dict['region_name']}':'';
        _location.text = dict['address']!=null?'${dict['address']}':'';
        _hospital = dict['health_name']!=null?'${dict['health_name']}':'';
        _name.text = dict['name']!=null?'${dict['name']}':'';
        _cardType = dict['id_card_type']==null?'居民身份证':dict['id_card_type']==1?'居民身份证':dict['id_card_type']==2?'军人身份证':dict['id_card_type']==3?'护照':dict['id_card_type']==4?'港澳居民来往内地通行证'
            :dict['id_card_type']==5?'台湾居民来往大陆通行证':dict['id_card_type']==6?'中华人民共和国旅行证':'其它';
        dataArray[4] = {'title':'证件类型：','content':_cardType};
        _number.text = dict['id_card']!=null?'${dict['id_card']}':'';
        _phone.text = dict['phone']!=null?'${dict['phone']}':'';
      });
    }
  }

  _getUserData2() async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.get, 'user/info', {});
    if(dict!=null){
      if(dict['health_id']!=null){
        _hospitalId = dict['health_id'];
        _getHospitalDetail(_hospitalId);
        // if(User().isNoBind){
        //   _placeId = dict['region_id'];
        //   _streetId = dict['area_id'];
        //   _street = dict['area_name']!=null?'${dict['area_name']}':'';
        //   _place = dict['region_name']!=null?'${dict['region_name']}':'';
        // }
      }
      setState(() {});
    }
  }

  _getHospitalDetail (int healthId) async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'common/healthCenter', {'id':healthId});
    if(dict!=null){
      _hospitalDetail = dict['data'];
      _hospital = _hospitalDetail['name'];
      setState(() {});
    }
  }

}
