<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="500px"
    @closed="closedHandler"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataForm"
      :model="dataForm"
      size="small"
      label-width="150px"
      :rules="rules"
      :disabled="formDisabled"
      v-loading="loading"
    >
      <el-form-item
        label="用户名"
        prop="userName"
      >
        <el-input
          placeholder="请输入用户名"
          :disabled="type != 'add'"
          v-model="dataForm.userName"
        />
      </el-form-item>
      <el-form-item
        label="申请账号"
        prop="rigisterName"
      >
        <el-input
          placeholder="请输入申请账号"
          :disabled="type != 'add'"
          v-model="dataForm.rigisterName"
        />
      </el-form-item>
      <el-form-item
        label="手机号"
        prop="cellphone"
      >
        <el-input
          placeholder="请输入手机号"
          v-model="dataForm.cellphone"
        />
      </el-form-item>
      <el-form-item
        label="性别"
        prop="sex"
      >
        <el-radio-group v-model="dataForm.sex">
          <el-radio label="1">男</el-radio>
          <el-radio label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="证件类型"
        prop="idType"
      >
        <el-select
          v-model="dataForm.idType"
          placeholder="请选择证件类型"
          :disabled="type != 'add'"
          style="width: 100%"
        >
          <el-option
            v-for="item in idTypeList"
            :label="item.name"
            :key="item.id"
            :value="item.val"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="证件号码"
        prop="idNo"
      >
        <el-input
          placeholder="请输入证件号码"
          :disabled="type != 'add'"
          v-model="dataForm.idNo"
        />
      </el-form-item>

      <el-form-item
        label="员工工号"
        prop="jobNo"
      >
        <el-input
          placeholder="请输入员工工号"
          v-model="dataForm.jobNo"
        />
      </el-form-item>
      <el-form-item
        label="邮件地址"
        prop="email"
      >
        <el-input
          placeholder="请输入邮件地址"
          v-model="dataForm.email"
        />
      </el-form-item>

      <el-form-item
        label="机构名称"
        prop="hospitalCode"
      >
        <el-select
          v-model="dataForm.hospitalCode"
          placeholder="请选择机构名称"
          style="width: 100%"
          filterable
          remote
          ref="hospitalCode"
          :loading="selectLoading"
          :remote-method="remoteMethod"
        >
          <el-option
            v-for="item in hospitalList"
            :label="item.hospitalName"
            :key="item.id"
            :value="item.hospitalCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="是否接收短信通知"
        prop="isReceiveSMS"
      >
        <el-radio-group v-model="dataForm.isReceiveSMS">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span
      slot="footer"
      class="dialog-footer"
    >
      <el-button
        size="small"
        @click="dialogVisible = false"
      >取 消</el-button>
      <el-button
        type="primary"
        size="small"
        :disabled="formDisabled"
        @click="submitForm()"
      >确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { queryUserInfoById, saveOrUpdateUserInfo } from '@/api/user'
import { queryHospitalList } from '@/api/common'
import { getDic } from '@/util/dict'
import IdentityCodeValid from '@/util/checkIdent'
export default {
  computed: {
    title: function() {
      let str = '管理员信息'
      if (this.type === 'add') {
        str += '填写'
      } else if (this.type === 'update') {
        str += '修改'
      } else if (this.type === 'detail') {
        str += '详情'
      }
      return str
    }
  },
  data() {
    const checkContactPhone = (rule, value, callback) => {
      let reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (!reg.test(value)) {
        callback(new Error("请输入正确格式的联系方式"))
      } else {
        callback()
      }
    };
    const checkEmail = (rule, value, callback) => {
      let reg = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/
      if (value && !reg.test(value)) {
        callback(new Error("请输入正确格式的邮箱"))
      } else {
        callback()
      }
    };
    const checkIdNo = (rule, value, callback) => {
      if (this.dataForm.idType === '01' && !IdentityCodeValid(value.toUpperCase())) {
        callback(new Error("请输入正确格式的身份证号"))
      } else {
        callback()
      }
    };
    return {
      dialogVisible: false,
      loading: false,
      formDisabled: false,
      selectLoading: false,
      type: 'add',
      dataForm: {
        userName: '',
        rigisterName: '',
        cellphone: '',
        sex: '',
        idType: '',
        idNo: '',
        jobNo: '',
        email: ''
      },
      idTypeList: [],
      hospitalList: [],
      rules: {
        userName: [
          { required: true, message: '请输入用户名' },
        ],
        rigisterName: [
          { required: true, message: '请输入申请账号' },
        ],
        cellphone: [
          { required: true, message: '请输入手机号' },
          { validator: checkContactPhone }
        ],
        email: [
          { validator: checkEmail }
        ],
        sex: [
          { required: true, message: '请选择性别' },
        ],
        idType: [
          { required: true, message: '请选择证件类型' },
        ],
        idNo: [
          { required: true, message: '请输入证件号码' },
          { validator: checkIdNo }
        ],
        hospitalCode: [
          { required: true, message: '请选择机构名称' },
        ],
        isReceiveSMS: [
          { required: true, message: '请选择是否接收短信通知' },
        ],
      }
    }
  },
  mounted() {
    //获取可选择的医院
    queryHospitalList().then(res => {
      this.hospitalList = res.respData
    })
    getDic(['ID_type']).then(res => {
      this.idTypeList = res.ID_type
    })
  },
  methods: {
    init(type, id) {
      this.dialogVisible = true
      this.loading = true
      this.type = type
      this.formDisabled = type === 'detail'
      if (type === 'update' || type === 'detail') {
        if (!id) {
          this.$message.error('用户id不能为空')
          return
        }
        queryUserInfoById({ userId: id }).then(res => {
          if (res.msg === 201) {
            this.dataForm = res.respData || {}
            this.$nextTick(() => {
              this.loading = false
              this.$refs.dataForm.clearValidate()
            })
          } else {
            this.$message.error(res.content);
          }
        })
      } else {
        this.dataForm = {
          isReceiveSMS: 2
        }
        this.$nextTick(() => {
          this.loading = false
          this.$refs.dataForm.clearValidate()
        })
      }
    },
    submitForm() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          const params = {
            ...this.dataForm
          }
          const hospital = this.hospitalList.find(i => i.hospitalCode === this.dataForm.hospitalCode)
          if (!hospital) {
            this.$message.error('无效数据');
            return
          }
          const { hospitalName } = hospital
          params.hospitalName = hospitalName

          saveOrUpdateUserInfo(params).then(res => {
            if (res.msg === 201) {
              this.dialogVisible = false
              this.$message.success(this.type === 'add' ? '新增成功！' : '修改成功')
              this.$emit('subsucc')
            } else {
              this.$message.error(res.content)
            }
          })
        }
      })
    },
    remoteMethod(query) {
      this.selectLoading = true;
      queryHospitalList(query).then(res => {
        this.hospitalList = res.respData
        this.selectLoading = false;
      })
    },
    closedHandler() {
      this.$refs.dataForm.resetFields()
    }
  }
}
</script>

<style>
</style>