<template>
  <div>
    <div class="app-container">
      <div class="level-title">
        <h1>修改</h1>
      </div>
      <el-form ref="form" :rules="rules" :model="form" label-width="140px" style="width: 500px;">
        <el-form-item label="教师姓名" prop="NAME">
          <el-input id="NAME" ref="NAME" v-model="form.NAME" maxlength="255" placeholder="这里输入教师姓名..." title="教师姓名"/>
        </el-form-item>
        <el-form-item label="手机号" prop="PHONE">
          <el-input id="PHONE" ref="PHONE" v-model="form.PHONE" maxlength="255" placeholder="这里输入手机号..." title="手机号"/>
        </el-form-item>
        <el-form-item label="身份证号" prop="IDENTITY_NUMBER">
          <el-input id="IDENTITY_NUMBER" ref="IDENTITY_NUMBER" v-model="form.IDENTITY_NUMBER" maxlength="255" placeholder="这里输入身份证号..." title="身份证号"/>
        </el-form-item>
        <el-form-item label="文化程度" prop="EDUCATION_LEVEL">
          <el-select ref="EDUCATION_LEVEL" v-model="form.EDUCATION_LEVEL" clearable style="width: 100%;">
            <el-option v-for="item in educationLevelList" :key="item.BIANMA" :label="item.NAME" :value="item.BIANMA" />
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="PROFESSION">
          <el-select ref="PROFESSION" v-model="form.PROFESSION" filterable clearable style="width: 100%;">
            <el-option v-for="item in professionList" :key="item.BIANMA" :label="item.NAME" :value="item.BIANMA" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证照片" prop="frontFile">
          <div v-if="form.IDENTITY_FILEPATH_FRONT" class="img-size">
            <div class="demo-image__preview" style="display:flex">
              <el-image
                :src="config.fileUrl + form.IDENTITY_FILEPATH_FRONT"
                :preview-src-list="new Array( config.fileUrl + form.IDENTITY_FILEPATH_FRONT )"
                style="width: 100px; height: 100px"/>
              <i class="el-icon-close" @click="removePhoto('front')"/>
            </div>
          </div>
          <div v-else style="display: flex;align-items: center">
            <el-upload
              ref="uploadFront"
              :on-remove="handleRemoveFront"
              :on-change="handleChangeFront"
              :on-preview="handlePreview"
              :before-upload="beforeUploadFront"
              :auto-upload="false"
              :limit="1"
              :class="{hide:form.hideUploadFront}"
              action=""
              accept=".jpg,.jpeg,.png"
              list-type="picture-card">
              <i class="el-icon-plus" />
            </el-upload>
            <div style="margin-left:20px;line-height:1.6">
              <div style="color: red;font-size: 12px">* 身份证正面</div>
              <div style="color: red;font-size: 12px">* 图像格式：JPEG、JPG、PNG</div>
              <div style="color: red;font-size: 12px">* 图像大小不超过5M。</div>
              <div style="color: red;font-size: 12px">* 图像分辨率不低于72dpi。</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="身份证照片" prop="reverseFile">
          <div v-if="form.IDENTITY_FILEPATH_REVERSE" class="img-size">
            <div class="demo-image__preview" style="display:flex">
              <el-image
                :src="config.fileUrl + form.IDENTITY_FILEPATH_REVERSE"
                :preview-src-list="new Array( config.fileUrl + form.IDENTITY_FILEPATH_REVERSE )"
                style="width: 100px; height: 100px"/>
              <i class="el-icon-close" @click="removePhoto('reverse')"/>
            </div>
          </div>
          <div v-else style="display: flex;align-items: center">
            <el-upload
              ref="uploadReverse"
              :on-remove="handleRemoveReverse"
              :on-change="handleChangeReverse"
              :on-preview="handlePreview"
              :before-upload="beforeUploadReverse"
              :auto-upload="false"
              :limit="1"
              :class="{hide:form.hideUploadReverse}"
              action=""
              accept=".jpg,.jpeg,.png"
              list-type="picture-card">
              <i class="el-icon-plus" />
            </el-upload>
            <div style="margin-left:20px;line-height:1.6">
              <div style="color: red;font-size: 12px">* 身份证反面</div>
              <div style="color: red;font-size: 12px">* 图像格式：JPEG、JPG、PNG</div>
              <div style="color: red;font-size: 12px">* 图像大小不超过5M。</div>
              <div style="color: red;font-size: 12px">* 图像分辨率不低于72dpi。</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="毕业证照片" prop="diplomaFile">
          <div v-if="form.DIPLOMA_FILEPATH" class="img-size">
            <div class="demo-image__preview" style="display:flex">
              <el-image
                :src="config.fileUrl + form.DIPLOMA_FILEPATH"
                :preview-src-list="new Array( config.fileUrl + form.DIPLOMA_FILEPATH )"
                style="width: 100px; height: 100px"/>
              <i class="el-icon-close" @click="removePhoto('diploma')"/>
            </div>
          </div>
          <div v-else style="display: flex;align-items: center">
            <el-upload
              ref="uploadDiploma"
              :on-remove="handleRemoveDiploma"
              :on-change="handleChangeDiploma"
              :on-preview="handlePreview"
              :before-upload="beforeUploadDiploma"
              :auto-upload="false"
              :limit="1"
              :class="{hide:form.hideUploadDiploma}"
              action=""
              accept=".jpg,.jpeg,.png"
              list-type="picture-card">
              <i class="el-icon-plus" />
            </el-upload>
            <div style="margin-left:20px;line-height:1.6">
              <div style="color: red;font-size: 12px">* 毕业证照片</div>
              <div style="color: red;font-size: 12px">* 图像格式：JPEG、JPG、PNG</div>
              <div style="color: red;font-size: 12px">* 图像大小不超过5M。</div>
              <div style="color: red;font-size: 12px">* 图像分辨率不低于72dpi。</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="资格证照片" prop="certificateFile">
          <div v-if="form.CERTIFICATE_FILEPATH" class="img-size">
            <div class="demo-image__preview" style="display:flex">
              <el-image
                :src="config.fileUrl + form.CERTIFICATE_FILEPATH"
                :preview-src-list="new Array( config.fileUrl + form.CERTIFICATE_FILEPATH )"
                style="width: 100px; height: 100px"/>
              <i class="el-icon-close" @click="removePhoto('certificate')"/>
            </div>
          </div>
          <div v-else style="display: flex;align-items: center">
            <el-upload
              ref="uploadCertificate"
              :on-remove="handleRemoveCertificate"
              :on-change="handleChangeCertificate"
              :on-preview="handlePreview"
              :before-upload="beforeUploadCertificate"
              :auto-upload="false"
              :limit="1"
              :class="{hide:form.hideUploadCertificate}"
              action=""
              accept=".jpg,.jpeg,.png"
              list-type="picture-card">
              <i class="el-icon-plus" />
            </el-upload>
            <div style="margin-left:20px;line-height:1.6">
              <div style="color: red;font-size: 12px">* 资格证照片</div>
              <div style="color: red;font-size: 12px">* 图像格式：JPEG、JPG、PNG</div>
              <div style="color: red;font-size: 12px">* 图像大小不超过5M。</div>
              <div style="color: red;font-size: 12px">* 图像分辨率不低于72dpi。</div>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <el-dialog :visible.sync="dialogVisible">
        <img :src="dialogImageUrl" width="100%" alt="">
      </el-dialog>
    </div>
    <div class="ui-height" />
    <div class="ui-foot">
      <el-button type="primary" @click="confirm">确 定</el-button>
      <el-button @click="goBack">取 消</el-button>
    </div>
  </div>
</template>
<script>
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
import { upload } from '@/utils/upload'
export default {
  components: { },
  directives: { waves },
  data() {
    var validateIdentity = (rule, value, callback) => {
      requestFN(
        '/user/validateIdentity',
        {
          IDENTITY_NUMBER: value
        }
      ).then((data) => {
        if (data.result == 'success') {
          if (!data.pd.ISVALIDATE) {
            callback(new Error('身份证号无效，请输入正确的身份证号码(15-18位)'))
          }
          callback()
        }
      }).catch((e) => {
        callback()
      })
    }
    return {
      listLoading: true,
      config: config,
      varList: [],
      pd: [],
      educationLevelList: [], // 文化程度列表
      professionList: [], // 专业列表
      form: {
        NAME: '', // 教师姓名
        PHONE: '', // 手机号
        IDENTITY_NUMBER: '', // 身份证号
        EDUCATION_LEVEL: '', // 文化程度
        PROFESSION: '', // 专业
        IDENTITY_FILEPATH_FRONT: '', // 身份证照片（正面）
        frontFile: '',
        hideUploadFront: false, // 显示图片

        IDENTITY_FILEPATH_REVERSE: '', // 身份证照片（反面）
        reverseFile: '',
        hideUploadReverse: false, // 显示图片

        DIPLOMA_FILEPATH: '', // 毕业证照片
        diplomaFile: '',
        hideUploadDiploma: false, // 显示图片

        CERTIFICATE_FILEPATH: '', // 资格证照片
        certificateFile: '',
        hideUploadCertificate: false // 显示图片
      },
      dialogType: 'add',
      rules: {
        NAME: [{ required: true, message: '教师姓名不能为空', trigger: 'blur' }],
        PHONE: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
            message: '请输入正确的手机号码'
          }
        ],
        IDENTITY_NUMBER: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { min: 15, max: 18, message: '请输入正确的身份证号码(15-18位)', trigger: 'blur' },
          {
            pattern: /(?:^\d{15}$)|(?:^\d{18}$)|^\d{17}[\dXx]$/,
            message: '请输入正确的身份证号码(15-18位)'
          },
          { validator: validateIdentity, trigger: 'blur' }
        ],
        EDUCATION_LEVEL: [{ required: true, message: '文化程度不能为空', trigger: 'blur' }],
        PROFESSION: [{ required: true, message: '专业不能为空', trigger: 'blur' }],
        frontFile: [{ required: false, message: '请上传身份证照片（正面）' }],
        reverseFile: [{ required: false, message: '请上传身份证照片（反面）' }],
        diplomaFile: [{ required: false, message: '请上传毕业证照片' }],
        certificateFile: [{ required: false, message: '请上传资格证照片' }]
      },
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  created() {
    this.resetForm()
    this.getDict()
    if (this.$parent.TEACHER_ID == '') {
      this.handleAdd()
    } else {
      this.handleEdit(this.$parent.TEACHER_ID)
    }
  },
  methods: {
    // 添加
    handleAdd() {
      this.dialogType = 'add'
      this.initRuls()
    },
    // 修改
    handleEdit(ID) {
      this.dialogType = 'edit'
      requestFN(
        '/teacher/goEdit',
        {
          TEACHER_ID: ID
        }
      ).then((data) => {
        this.form = Object.assign(this.form, data.pd) // copy obj
        this.initRuls()
      }).catch((e) => {
      })
    },
    // 保存
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.$refs.uploadFront) {
            this.$refs.uploadFront.submit()
          }
          if (this.$refs.uploadReverse) {
            this.$refs.uploadReverse.submit()
          }
          if (this.$refs.uploadDiploma) {
            this.$refs.uploadDiploma.submit()
          }
          if (this.$refs.uploadCertificate) {
            this.$refs.uploadCertificate.submit()
          }
          const loading = this.$loading({
            lock: true,
            text: '数据保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          // this.form.VIDEOUSERS = ',' + this.form.VIDEOUSERS.join(',') + ','
          const formData = new FormData()
          Object.keys(this.form).map(key => {
            formData.append(key, this.form[key])
          })
          upload(
            '/teacher/' + this.dialogType,
            formData
          ).then((data) => {
            loading.close()
            this.$message({
              message: '教师信息保存成功。',
              type: 'success'
            })
            this.goBack()
          }).catch((e) => {
            loading.close()
          })
        } else {
          return false
        }
      })
    },
    initRuls() {
      if (this.form.IDENTITY_FILEPATH_FRONT == '' && this.form.frontFile == '') {
        this.rules.frontFile = [{ required: true, message: '请上传身份证照片（正面）' }]
      } else {
        this.rules.frontFile = [{ required: false, message: '请上传身份证照片（正面）' }]
      }
      if (this.form.IDENTITY_FILEPATH_REVERSE == '' && this.form.reverseFile == '') {
        this.rules.reverseFile = [{ required: true, message: '请上传身份证照片（反面）' }]
      } else {
        this.rules.reverseFile = [{ required: false, message: '请上传身份证照片（反面）' }]
      }
      if (this.form.DIPLOMA_FILEPATH == '' && this.form.diplomaFile == '') {
        this.rules.diplomaFile = [{ required: true, message: '请上传毕业证照片' }]
      } else {
        this.rules.diplomaFile = [{ required: false, message: '请上传毕业证照片' }]
      }
      if (this.form.CERTIFICATE_FILEPATH == '' && this.form.certificateFile == '') {
        this.rules.certificateFile = [{ required: true, message: '请上传资格证照片' }]
      } else {
        this.rules.certificateFile = [{ required: false, message: '请上传资格证照片' }]
      }
    },
    handlePreview(file, fileList) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    removePhoto(type) {
      if (type == 'front') {
        this.form.IDENTITY_FILEPATH_FRONT = ''
        this.form.frontFile = ''
        this.form.hideUploadFront = false
      } else if (type == 'reverse') {
        this.form.IDENTITY_FILEPATH_REVERSE = ''
        this.form.reverseFile = ''
        this.form.hideUploadReverse = false
      } else if (type == 'diploma') {
        this.form.DIPLOMA_FILEPATH = ''
        this.form.diplomaFile = ''
        this.form.hideUploadDiploma = false
      } else if (type == 'certificate') {
        this.form.CERTIFICATE_FILEPATH = ''
        this.form.certificateFile = ''
        this.form.hideUploadCertificate = false
      }
    },

    /** 身份证（正面） **/
    beforeUploadFront(file) {
      const types = ['image/jpeg', 'image/jpg', 'image/png']
      const isImage = types.includes(file.type)
      if (!isImage) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG 格式!')
      } else {
        this.form.frontFile = file
      }
    },
    handleRemoveFront(file, fileList) { // 文件列表移除文件时的钩子
      this.form.frontFile = ''
      this.form.hideUploadFront = fileList.length >= 1
    },
    handleChangeFront(file, fileList) {
      this.form.frontFile = file
      this.form.hideUploadFront = fileList.length >= 1
    },

    /** 身份证（反面） **/
    beforeUploadReverse(file) {
      const types = ['image/jpeg', 'image/jpg', 'image/png']
      const isImage = types.includes(file.type)
      if (!isImage) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG 格式!')
      } else {
        this.form.reverseFile = file
      }
    },
    handleRemoveReverse(file, fileList) { // 文件列表移除文件时的钩子
      this.form.reverseFile = ''
      this.form.hideUploadReverse = fileList.length >= 1
    },
    handleChangeReverse(file, fileList) {
      this.form.reverseFile = file
      this.form.hideUploadReverse = fileList.length >= 1
    },

    /** 毕业证照 **/
    beforeUploadDiploma(file) {
      const types = ['image/jpeg', 'image/jpg', 'image/png']
      const isImage = types.includes(file.type)
      if (!isImage) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG 格式!')
      } else {
        this.form.diplomaFile = file
      }
    },
    handleRemoveDiploma(file, fileList) { // 文件列表移除文件时的钩子
      this.form.diplomaFile = ''
      this.form.hideUploadDiploma = fileList.length >= 1
    },
    handleChangeDiploma(file, fileList) {
      this.form.diplomaFile = file
      this.form.hideUploadDiploma = fileList.length >= 1
    },

    /** 资格证照 **/
    beforeUploadCertificate(file) {
      const types = ['image/jpeg', 'image/jpg', 'image/png']
      const isImage = types.includes(file.type)
      if (!isImage) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG 格式!')
      } else {
        this.form.certificateFile = file
      }
    },
    handleRemoveCertificate(file, fileList) { // 文件列表移除文件时的钩子
      this.form.certificateFile = ''
      this.form.hideUploadCertificate = fileList.length >= 1
    },
    handleChangeCertificate(file, fileList) {
      this.form.certificateFile = file
      this.form.hideUploadCertificate = fileList.length >= 1
    },

    // 获取数据字典数据
    getDict: function() {
      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID: 'd7d80f08d73a4accbccf4fd3d8d1d867' // 文化程度PARENT_ID
        }
      ).then((data) => {
        this.educationLevelList = data.list
        // .map(function(obj) {
        //   return obj.NAME
        // })
      })

      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID: '95530fecbcb3421ca600b58c206b99d6' // 专业PARENT_ID
        }
      ).then((data) => {
        this.professionList = data.list
        // .map(function(obj) {
        //   return obj.NAME
        // })
      })
    },
    resetForm() {
      this.form = {
        NAME: '', // 教师姓名
        PHONE: '', // 手机号
        IDENTITY_NUMBER: '', // 身份证号
        EDUCATION_LEVEL: '', // 文化程度
        PROFESSION: '', // 专业
        IDENTITY_FILEPATH_FRONT: '', // 身份证照片（正面）
        frontFile: '',
        hideUploadFront: false, // 显示图片

        IDENTITY_FILEPATH_REVERSE: '', // 身份证照片（反面）
        reverseFile: '',
        hideUploadReverse: false, // 显示图片

        DIPLOMA_FILEPATH: '', // 毕业证照片
        diplomaFile: '',
        hideUploadDiploma: false, // 显示图片

        CERTIFICATE_FILEPATH: '', // 资格证照片
        certificateFile: '',
        hideUploadCertificate: false // 显示图片
      }
    },
    goBack() {
      this.$parent.TEACHER_ID = ''
      this.$parent.activeName = 'TeacherList'
    }
  }
}

</script>
<style lang="scss">
  html{
    touch-action:none;
  }
  .hide .el-upload--picture-card {
    display: none;
  }
</style>
