<template>
  <div class="form-warp">
    <el-form
      :model="patientInfoForm"
      :rules="rules"
      ref="patientInfoForm"
      label-width="150px"
      label-suffix=":"
      size="small"
      >
      <el-row>
        <el-col :span="12">
          <el-form-item label="居民姓名" prop="nickname">
            <el-input
              v-model.trim="patientInfoForm.nickname"
              placeholder="请输入居民姓名"
              :disabled="!baseInfoEdit"
              clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="mobilePhone">
            <el-input
              v-model.trim="patientInfoForm.mobilePhone"
              maxlength="11"
              placeholder="请输入手机号"
              :disabled="!baseInfoEdit"
              clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" style="text-align: center;margin-top:15px;" v-show="!patientId"> <el-button plain size="small" @click="toggleClick">{{tipsText}}</el-button></el-col>
      </el-row>
      <div v-show="isShowAll || patientId">
        <div class="has-header">数据记录</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="诊断" prop="diseaseIdList">
              <el-select
                v-model="diseaseIdList"
                multiple
                @change="changeDiseases"
                :popper-append-to-body="false"
                placeholder="请选择居民疾病诊断">
                <el-option
                  v-for="(item, index) in diseasesList"
                  :key="item.diseaseId"
                  :label="item.diseaseName"
                  :value="item.diseaseId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分组" prop="labelIdList">
              <el-select
                v-model="labelIdList"
                multiple
                @change="changeLabels"
                :popper-append-to-body="false"
                placeholder="请选择居民分组">
                <el-option
                  v-for="(item, index) in labelsList"
                  :key="index.labelId"
                  :label="item.labelName"
                  :value="item.labelId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="has-header">基本信息</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证" prop="idNo">
              <el-input
                v-model.trim="patientInfoForm.idNo"
                placeholder="请输入身份证"
                clearable
                maxlength="18"
                @blur="idNoBlurHandler"
                :disabled="hasIdNo">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthTime">
              <el-date-picker
                type="date"
                v-model="patientInfoForm.birthTime"
                placeholder="请选择出生日期"
                value-format="yyyy-MM-dd"
                value="yyyy-MM-dd"
                @change="getAge"
                :picker-options="setPickerOption"
                :editable="false"
                style="width:250px"
                clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <span>{{(patientInfoForm.age || patientInfoForm.age == 0 ) ? `${patientInfoForm.age}岁` : '-'}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="patientInfoForm.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="常驻类型" prop="permanentResidence">
              <el-select
                v-model="patientInfoForm.permanentResidence"
                placeholder="请选择居民常驻类型"
                :popper-append-to-body="false"
                clearable>
                <el-option
                  v-for="(item, index) in residenceList"
                  :key="index"
                  :label="item.value"
                  :value="item.noChar">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="民族" prop="nationality">
              <el-select
                v-model="patientInfoForm.nationality"
                placeholder="请选择民族"
                :popper-append-to-body="false"
                clearable>
                <el-option
                  v-for="(item, index) in nationsList"
                  :key="index"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="医保号" prop="socialCard">
              <el-input
                v-model.trim="patientInfoForm.socialCard"
                placeholder="请输入居民医保卡号码"
                maxlength="30"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="健康档案编号" prop="fileLocator">
              <el-input
                v-model.trim="patientInfoForm.fileLocator"
                placeholder="请输入居民健康档案编号"
                maxlength="30"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="has-header">联系方式</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所在地区" prop="addressList">
              <el-cascader
                placeholder="请选择省市县乡"
                :options="provinceList"
                v-model="addressList"
                @active-item-change="handleItemChange"
                :props="optionProps">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model="patientInfoForm.address"
                placeholder="请输入居民的详细地址"
                maxlength="50"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工作单位" prop="workplace">
              <el-input
                v-model="patientInfoForm.workplace"
                placeholder="请输入居民的工作单位"
                maxlength="30"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="patientId">
            <el-form-item label="微信" prop="address">
              <p class="info" v-if="patientInfoForm.isWechatBind == '1'">未绑定 <el-button type="text" class="ml10" @click="remindBind" v-if="patientInfoForm.isRemind == '1'" style="color: #449284;">提醒绑定</el-button><span class="ml10" v-if="patientInfoForm.isRemind == '2'">已提醒</span></p>
              <!--<p class="info" v-else-if="patientInfoForm.isWechatBind == '2'">已绑定 <span class="ml10">（微信名：{{patientInfoForm.wechatNickname | emptyFilter}}）</span></p>-->
              <p class="info" v-else-if="patientInfoForm.isWechatBind == '2'">{{patientInfoForm.wechatNickname | emptyFilter}}</p>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="has-header">其他</div>
        <el-row>
          <el-col :span="16">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                v-model="patientInfoForm.remark"
                placeholder="请输入内容"
                clearable
                maxlength="200"
                :autosize="{ minRows: 3, maxRows: 7}"
                show-word-limit>
              </el-input>
              <span class="text-count">{{currentCount}} / 200</span>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex';
  import { checkMobile } from '@/utils/patients/checkValid';
  import { isCardNo, checkProvince, checkBirthday, checkParity } from '@/utils/patients/checkCardNum';
  import {
    getDiseasesList,
    getLabelList,
    getConstants,
    getNationsList,
    getRemindPatient,
    getProvinceList,
    getCityList,
    getCountyList,
    getTownList } from '@/utils/patients/patientsapi';
  export default {
    name: "basicInfo",
    components: {},
    data() {
      let validCode=(rule,value,callback)=>{
        if(value) {
          let reg=/^[0-9a-zA-Z]*$/g
          if(!reg.test(value)){
            callback(new Error('只可输入数字加英文'))
          }else if(value.length >30) {
            callback(new Error('只可输入30个以内的字符'))
          }else{
            callback()
          }
        }else {
          callback()
        }
      };
      let checkCardNum = (rule, value, callback) =>{
        let vcity={ 11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",
          21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",
          33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",
          42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",
          51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",
          63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"
        };
        if(value) {
          if(isCardNo(value) && checkProvince(value,vcity) && checkBirthday(value) && checkParity(value)) {
            this.isTrue = true;
            callback()
          }else {
            callback(new Error('请输入正确的身份证'))
          }
        }else {
          callback()
        }
      };
      return {
        diseasesList: [],
        labelsList: [],
        residenceList: [],
        nationsList: [],
        diseaseIdList: [],
        labelIdList: [],
        addressList: [],
        baseInfoEdit: true,
        isTrue: false,
        patientInfoForm: {
          nickname: '',
          mobilePhone: '',
          diseases: [],
          patientDiseases: [],
          customLabels: [],
          idNo: '',
          birthTime: '',
          age: null,
          sex: null,
          permanentResidence: '',
          nationality: '',
          socialCard: '',
          fileLocator: '',
          isWechatBind: 1,
          isRemind: 1,
          wechatNickname: '',
          remark: '',
          patientAddress: '',
          address: '',
          workplace: '',
          provinceId: null,
          cityId: null,
          countyId: null,
          townId: null,
        },
        hasIdNo: false,
        validStatus: false,
        provinceList: [],
        provinceLists: [], //省列表
        cityLists: [], //市列表
        countyLists: [], //县列表
        townLists: [],//乡镇列表
        optionProps: {
          value: "id",
          label: "name",
          children: "children"
        },
        tipsText: '展开录入完整信息',
        isShowAll: false,
        rules: {
          nickname: [{required: true, message: '请输入居民姓名', trigger: ['change', 'blur'] },
            { min: 2, max: 15, message: '长度在2至15个字符之间', trigger: 'change' }],
          mobilePhone: [{required: true, message: '请输入手机号', trigger: ['change', 'blur'] },
            { validator: checkMobile , trigger: ['blur','change'] }],
          idNo: [{required: false,validator: checkCardNum,  trigger: ['change'] }],
          socialCard: [{required: false,validator: validCode,  trigger: ['change'] }],
          fileLocator: [{required: false,validator: validCode,  trigger: ['change'] }],
        },
        setPickerOption: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          // disabledDate(time) {
          //   let curDate = (new Date()).getTime();
          //   let three = 90 * 24 * 3600 * 1000;
          //   let threeMonths = curDate - three;
          //   return time.getTime() > Date.now() || time.getTime() < threeMonths;;
          // }
        },
      }
    },
    props: {
      patientInfoObj: Object,
      checkForm: Boolean,
      patientId: {
        required: false,
        type: String,
        default: function () {
          return '';
        }
      },
    },
    watch: {
      async patientInfoObj(val) {
        if(this.patientId){  //编辑居民信息，对拿到的数据做处理
          this.patientInfoForm = val;
          this.baseInfoEdit = this.patientInfoForm.baseInfoEdit;
          let customLabels = this.patientInfoForm.customLabels;
          let diseases = this.patientInfoForm.diseases;
          if(customLabels && customLabels.length > 0){
            customLabels.forEach((kkk)=>{
              this.labelIdList.push(Number(kkk.labelId))
            })
          }else {
            this.labelIdList = [];
          }
          if(diseases && diseases.length > 0) {
            diseases.forEach((dis)=>{
              this.diseaseIdList.push(Number(dis.diseaseId))
            })
          }else {
            this.diseaseIdList = [];
          }
          if(this.patientInfoForm.idNo) {
            this.hasIdNo = true;
          }else {
            this.hasIdNo = false;
          }
          //对地区数据做回显处理
          if(this.patientInfoForm.patientAddress) {
            let provinceId = this.patientInfoForm.provinceId;
            let cityId = this.patientInfoForm.cityId;
            let countyId = this.patientInfoForm.countyId;
            let townId = this.patientInfoForm.townId;
            if(provinceId) {
              await this.getCity(provinceId);
            }
            if(cityId) {
              await this.getCounty(provinceId, cityId);
            }
            if(countyId) {
              await this.getTown(provinceId, cityId, countyId);
            }
            this.addressList = [Number(provinceId), Number(cityId), Number(countyId), Number(townId)];
            this.$forceUpdate();
          }else {
            this.addressList = [];
          }
        }else {  //  新增
          this.initForm();
        }
      },
      // 'patientInfoForm.age'(val) {
      //   console.log('年龄',val)
      // },
      checkForm(val){
        if(val){// 触发校验
          this.saveInfoData();
        }
      },
    },
    created() {
      this.initConstant();
    },
    mounted(){
      if(!this.patientId){//新建计划
        this.initForm();
      }
    },
    computed: {
      ...mapGetters([
        '_token',
      ]),
      currentCount(){
        if(this.patientInfoForm.remark) {
          return this.patientInfoForm.remark.length
        }else {
          return 0;
        }
      },
    },
    methods: {
      initForm() {
        this.patientInfoForm = {
          nickname: '',
          mobilePhone: '',
          diseases: [],
          patientDiseases: [],
          customLabels: [],
          idNo: '',
          birthTime: '',
          age: null,
          sex: null,
          permanentResidence: '',
          nationality: '',
          socialCard: '',
          fileLocator: '',
          isWechatBind: null,
          isRemind: null,
          wechatNickname: '',
          remark: '',
          patientAddress: '',
          address: '',
          workplace: '',
          provinceId: null,
          cityId: null,
          countyId: null,
          townId: null,
        }
      },
      initConstant(){
        getDiseasesList().then((data) => {
          if(data.code == '000000') {
            this.diseasesList = data.data;
          }
        });
        getLabelList({
          type: 2,
          token: this._token,
        }).then((data) => {
          if(data.code == '000000') {
            this.labelsList = data.data.labelNameList;
          }
        });
        getConstants({
          numList: 'P221',
        }).then((data) => {
          if(data.code == '000000') {
            this.residenceList = data.data.P221;
          }
        });
        getNationsList().then((data) => {
          if(data.code == '000000') {
            this.nationsList = data.data;
          }
        });
        this.getProvinceLists();
      },
      changeDiseases(val) {
        let newDiseaseList = [];
        val.forEach((valItem) => {
          this.diseasesList.forEach((item2) => {
            if(valItem == item2.diseaseId){
              newDiseaseList.push({parentDiseaseId: item2.diseaseId});
            }
          })
        });
        this.patientInfoForm.patientDiseases = newDiseaseList;
      },
      changeLabels(val){
        let newLabelsList = [];
        val.forEach((valItem) => {
          this.labelsList.forEach((item2) => {
            if(valItem == item2.labelId){
              newLabelsList.push(item2);
            }
          })
        });
        this.patientInfoForm.customLabels = newLabelsList;
      },
      idNoBlurHandler() {
        if(this.isTrue) {
          this.go(this.patientInfoForm.idNo.length);
        }
      },
      //提醒绑定
      remindBind() {
        let remindMobileWechatPara = {
          qrcodeType: 1,
          patientId: this.patientId,
          // deviceInfo: window.getDeviceInfo()
        }
        getRemindPatient({
          ...remindMobileWechatPara
        }).then( data => {
          if(data.code == '000000') {
            this.$message.success(data.data.respMsg);
            this.$router.go(-1);
          }else {
            this.$message.error(data.message);
          }
        })
      },
      saveInfoData() {
        //对地区数据做处理
        if(this.addressList.length > 0) {
          this.patientInfoForm.provinceId = this.addressList[0];
          this.patientInfoForm.cityId = this.addressList[1];
          this.patientInfoForm.countyId = this.addressList[2];
          this.patientInfoForm.townId = this.addressList[3];
          this.provinceLists.forEach((item) => {
            if(this.patientInfoForm.provinceId == item.provinceId) {
              this.patientInfoForm.provinceName = item.provinceName;
            }
          });
          this.cityLists.forEach((item) => {
            if(this.patientInfoForm.cityId == item.cityId) {
              this.patientInfoForm.cityName = item.cityName;
            }
          });
          this.countyLists.forEach((item) => {
            if(this.patientInfoForm.countyId == item.countyId) {
              this.patientInfoForm.countyName = item.countyName;
            }
          })
          this.townLists.forEach((item) => {
            if(this.patientInfoForm.townId == item.townId) {
              this.patientInfoForm.townName = item.townName;
            }
          })
          if(this.patientInfoForm.provinceName && this.patientInfoForm.cityName && this.patientInfoForm.countyName && this.patientInfoForm.townName) {
            this.patientInfoForm.patientAddress = `${this.patientInfoForm.provinceName}${this.patientInfoForm.cityName}${this.patientInfoForm.countyName}${this.patientInfoForm.townName}`
          }else {
            this.patientInfoForm.patientAddress = '';
          }
        }
        this.$refs['patientInfoForm'].validate((valid) => {
          if(!this.patientInfoForm.idNo) {
            this.patientInfoForm.idNo = null;
          }
          if (valid) {
            // console.log('提交表单',this.patientInfoForm);
            this.$emit('addListenSave',{
              status: true,
              patientInfoForm: {
                ...this.patientInfoForm,
                birthTime: this.patientInfoForm.birthTime ? `${this.patientInfoForm.birthTime} 00:00:00` : '',
              }
            })
          } else {
            this.$emit('addListenSave',{
              status: false,
              // patientInfoForm: this.patientInfoForm,
              patientInfoForm: {
                ...this.patientInfoForm,
                birthTime: this.patientInfoForm.birthTime ? `${this.patientInfoForm.birthTime} 00:00:00` : '',
              }
            })
          }
        });
      },
      // 实现自动生成生日，性别，年龄
      go(val) {
        let iden = this.patientInfoForm.idNo;
        let sex = null;
        let birth = null;
        let myDate = new Date();
        let month = myDate.getMonth() + 1;
        let day = myDate.getDate();
        let age = 0;

        if(val===18){
          age = myDate.getFullYear() - iden.substring(6, 10) - 1;
          sex = iden.substring(16,17);
          birth = iden.substring(6,10)+"-"+iden.substring(10,12)+"-"+iden.substring(12,14);
          if (iden.substring(10, 12) < month || iden.substring(10, 12) == month && iden.substring(12, 14) <= day) age++;

        }
        if(val===15){
          age = myDate.getFullYear() - iden.substring(6, 8) - 1901;
          sex = iden.substring(13,14);
          birth = "19"+iden.substring(6,8)+"-"+iden.substring(8,10)+"-"+iden.substring(10,12);
          if (iden.substring(8, 10) < month || iden.substring(8, 10) == month && iden.substring(10, 12) <= day) age++;
        }

        if(sex%2 === 0)
          sex = 2;
        else
          sex = 1;
        this.patientInfoForm.sex = sex;
        this.patientInfoForm.age = age;
        this.patientInfoForm.birthTime = birth;
        // this.baseInfo.birthplace = this.area[iden.substring(0,2)];
      },
      getAge(val) {
        if(val) {
          // let birthdays = new Date(this.patientInfoForm.birthTime.replace(/-/g, "/"));
          let birthdays = new Date(val.replace(/-/g, "/"));
          let d = new Date();
          let age = d.getFullYear() - birthdays.getFullYear() - (d.getMonth() < birthdays.getMonth() || (d.getMonth() == birthdays.getMonth() && d.getDate() < birthdays.getDate()) ? 1 : 0);
          this.patientInfoForm.age = age;
        }else {
          this.patientInfoForm.age = null;
        }
      },
      handleItemChange (val) {
        if (val.length === 1) {  //获取市（二级）
          this.getCity(val[0]);
        } else if (val.length === 2) {  //获取县区 （三级）
          this.getCounty(val[0], val[1]);
        } else if(val.length === 3) { //获取乡镇 （四级）
          this.getTown(val[0], val[1], val[2]);
        }
        this.$forceUpdate();
      },
      async getProvinceLists() {
        await getProvinceList({}).then((data) => {
          if(data.code == '000000') {
            this.provinceLists = data.data.provinceList;
            this.provinceLists.map(item => {
              this.$set(item, "id", item.provinceId);
              this.$set(item, "name", item.provinceName);
              this.$set(item, "children", []);
            });
            this.provinceList = this.provinceLists;
            // this.$forceUpdate();
          }
        })
      },
      async getCity(provinceId) {
        await getCityList({provinceId: provinceId}).then((data) => {
          if(data.code == '000000') {
            this.cityLists = data.data.cityList;
            this.cityLists.map(item => {
              this.$set(item, "id", item.cityId);
              this.$set(item, "name", item.cityName);
              this.$set(item, "children", []);
            });
            this.provinceList.map((item, index) => {
              if(item.id == provinceId) {
                item.children = this.cityLists;
              }
            })
            // this.$forceUpdate();
          }
        })
      },
      async getCounty(provinceId, cityId) {
        await getCountyList({cityId: cityId}).then((data) => {
          if(data.code == '000000') {
            this.countyLists = data.data.countyList;
            this.countyLists.map(item => {
              this.$set(item, "id", item.countyId);
              this.$set(item, "name", item.countyName);
              this.$set(item, "children", []);
            });
            this.provinceList.map((item, index) => {
              if(item.id == provinceId) {
                item.children.map((city, idx) => {
                  city.children = this.countyLists;
                })
              }
            })
            // this.$forceUpdate();
          }
        })
      },
      async getTown(provinceId, cityId, countyId) {
        await getTownList({countyId: countyId}).then((data) => {
          if(data.code == '000000') {
            this.townLists = data.data.townList;
            this.townLists.map(item => {
              this.$set(item, "id", item.townId);
              this.$set(item, "name", item.townName);
              // this.$set(item, "children", []);
            });
            this.provinceList.map((item, index) => {
              if(item.id == provinceId) {
                item.children.map((city, index2) => {
                  if(city.id == cityId) {
                    city.children.map((county, index3) => {
                      county.children = this.townLists;
                    })
                  }
                })
              }
            })
          }
          // this.$forceUpdate();
        })
      },
      toggleClick() {
        if(this.isShowAll) {
          this.tipsText = '展开录入完整信息';
          this.isShowAll = false;
        }else {
          this.tipsText = '收起录入完整信息';
          this.isShowAll = true;
        }
      }
    },
    filters: {
      emptyFilter: function(value) {
        if (!value && value != 0) {
          return '-';
        } else {
          return value;
        }
      },
    },
  }
</script>
<style lang="scss">
  .screenSet{
    overflow: visible!important;
  }
  .el-input{
    width: 250px;
  }
.form-warp{
  margin-top: 30px;
  .has-header{
    padding: 15px 0;
    margin-bottom: 20px;
    border-bottom: 1px dashed #888;
  }
  .info{
    font-size: 12px;
    color: #999;
  }
  .text-count{
    position: absolute;
    right: 5px;
    bottom: 0px;
    line-height: 28px;
    color: #999;
    font-size: 12px;
  }
  .ml10{
    margin-left: 10px;
  }
}
</style>
