<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="patientInfoForm.nickname"
              placeholder="请输入居民姓名"
              minlength="2"
              maxlength="15"
              :disabled="!baseInfoEdit"
              clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="mobilePhone">
            <el-input
              v-model="patientInfoForm.mobilePhone"
              maxlength="11"
              placeholder="请输入手机号"
              :disabled="!baseInfoEdit"
              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="diseaseIdList">
            <el-select
              v-model="diseaseIdList"
              multiple
              @change="changeDiseases"
              placeholder="请选择居民疾病诊断">
              <el-option
                v-for="item 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"
              placeholder="请选择居民分组">
              <el-option
                v-for="(item, index) in labelsList"
                :key="index"
                :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="patientInfoForm.idNo"
              placeholder="请输入身份证"
              clearable
              maxlength="18"
              :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"
              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}岁` : '-'}}</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="请选择居民常驻类型"
              clearable>
              <el-option
                v-for="item in residenceList"
                :key="item.no"
                :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="请选择民族"
              clearable>
              <el-option
                v-for="item in nationsList"
                :key="item.code"
                :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="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="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="patientAddress">
            <el-input
              v-model="patientInfoForm.patientAddress"
              placeholder="请输入居民医保卡号码"
              clearable>
            </el-input>
          </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'">提醒绑定</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>
          </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>
    </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,savePatientInfo } from '@/utils/patients/patientsapi';
  export default {
    name: "basicInfo",
    components: {},
    data() {
      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 === ''){
        //   callback(new Error('请输入正确的身份证'))
        // }
        if(value) {
          //校验长度，类型
          if(isCardNo(value) === false){
            callback(new Error('请输入正确的身份证'))
          }
          //检查省份
          if(checkProvince(value,vcity) === false){
            callback(new Error('请输入正确的身份证'))
          }
          //校验生日
          if(checkBirthday(value) === false){
            callback(new Error('请输入正确的身份证'))
          }
          //检验位的检测
          if(checkParity(value) === false){
            callback(new Error('请输入正确的身份证'))
          }
          this.go(value.length);
          callback()
        }else {
          callback()
        }
      };
      return {
        diseasesList: [],
        labelsList: [],
        residenceList: [],
        nationsList: [],
        diseaseIdList: [],
        labelIdList: [],
        baseInfoEdit: true,
        patientInfoForm: {
          nickname: '',
          mobilePhone: '',
          diseases: [],
          patientDiseases: [],
          customLabels: [],
          idNo: '',
          birthTime: '',
          age: '',
          sex: null,
          permanentResidence: '',
          nationality: '',
          socialCard: '',
          fileLocator: '',
          isWechatBind: 1,
          isRemind: 1,
          wechatNickname: '',
          remark: '',
        },
        hasIdNo: false,
        validStatus: false,
        rules: {
          nickname: [{required: true, message: '请输入居民姓名', trigger: ['change', 'blur'] }],
          mobilePhone: [{required: true, message: '请输入手机号', trigger: ['change', 'blur'] },{ validator: checkMobile , trigger: ['blur','change'] }],
          idNo: [{required: false,validator: checkCardNum,  trigger: ['change'] }],
        },
      }
    },
    props: {
      patientInfoObj: Object,
      checkForm: Boolean,
      patientId: String,
    },
    watch: {
      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;
          }
          // this.$refs['patientInfoForm'].clearValidate();
          this.$forceUpdate();
        }else {
        //  新增
          this.patientInfoForm = {
              nickname: '',
              mobilePhone: '',
              diseases: [],
              patientDiseases: [],
              customLabels: [],
              idNo: '',
              birthTime: '',
              age: '',
              sex: null,
              permanentResidence: '',
              nationality: '',
              socialCard: '',
              fileLocator: '',
              isWechatBind: null,
              isRemind: null,
              wechatNickname: '',
              remark: '',
          }
        }
      },
      checkForm(val){
        if(val){// 触发校验
          this.saveInfoData();
        }
      },
    },
    created() {
      this.initConstant();
    },
    mounted(){
    },
    computed: {
      ...mapGetters([
        '_token',
      ]),
      currentCount(){
        if(this.patientInfoForm.remark) {
          return this.patientInfoForm.remark.length
        }else {
          return 0;
        }

      },
    },
    methods: {
      initConstant(){
        getDiseasesList().then((data) => {
          if(data.code == '000000') {
            this.diseasesList = data.data;
          }
        });
        getLabelList({
          type: 1,
          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;
          }
        })
      },
      changeDiseases(val) {
        let newDiseaseList = [];
        val.forEach((valItem) => {
          this.diseasesList.forEach((item2) => {
            if(valItem == item2.diseaseId){
              newDiseaseList.push({parentDiseaseId: item2.diseaseId});
            }
          })
        });
        // this.patientInfoForm.diseases = newDiseaseList;
        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;
      },
      //提醒绑定
      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() {
        this.$refs['patientInfoForm'].validate((valid) => {
          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;
        }
      },

    },
    filters: {
      emptyFilter: function(value) {
        if (!value) {
          return '-';
        } else {
          return value;
        }
      },
    },
  }
</script>
<style lang="scss">
  .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>
