<template>
  <div class="app-warp">
    <div class="detail-structure">
      <el-page-header :content="dialogType=='add'?'新增页面':'编辑页面'" @back="goBack"/>
      <div class="detail-container">
        <div class="level-title">
          <h1>证书管理</h1>
        </div>
        <el-form ref="form" :rules="rules" :model="form" label-width="160px" class="edit_form">
          <el-form-item label="资质类型" prop="QUALIFICATION_TYPE">
            <el-select ref="QUALIFICATION_TYPE" v-model="form.QUALIFICATION_TYPE" clearable>
              <el-option v-for="item in QUALIFICATION_TYPE_List" :key="item.BIANMA" :label="item.NAME" :value="item.BIANMA" />
            </el-select>
          </el-form-item>
          <el-form-item label="职业证书编号" prop="VOCATIONAL_CERTIFICATE_NUMBER">
            <el-input id="VOCATIONAL_CERTIFICATE_NUMBER" ref="VOCATIONAL_CERTIFICATE_NUMBER" v-model="form.VOCATIONAL_CERTIFICATE_NUMBER" maxlength="255" placeholder="这里输入职业证书编号..." title="职业证书编号" @input="form.VOCATIONAL_CERTIFICATE_NUMBER = form.VOCATIONAL_CERTIFICATE_NUMBER.replace(/[^a-zA-Z0-9\-]/g, '')"/>
          </el-form-item>
          <el-form-item label="是否永久有效" prop="IS_PERMANENT_VALID">
            <el-select ref="IS_PERMANENT_VALID" v-model="form.IS_PERMANENT_VALID" placeholder="请选择是否永久有效">
              <el-option v-for="item in PERMANENT_VALID_List" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="证书有效期（开始）" prop="CERTIFICATE_DATE_BEGIN">
            <el-date-picker v-model="form.CERTIFICATE_DATE_BEGIN" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" placeholder="选择证书（开始）日期" />
          </el-form-item>
          <el-form-item v-if="form.IS_PERMANENT_VALID === '-1'" label="证书有效期（结束）" prop="CERTIFICATE_DATE_END">
            <el-date-picker v-model="form.CERTIFICATE_DATE_END" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" placeholder="选择证书（结束）日期" />
          </el-form-item>
          <el-form-item label="证书照片" prop="certificateFile">
            <div v-if="form.CERTIFICATE_FILEPATH" class="img-size">
              <div class="demo-image__preview">
                <el-image
                  :src="config.fileUrl + form.CERTIFICATE_FILEPATH"
                  :preview-src-list="new Array( config.fileUrl + form.CERTIFICATE_FILEPATH )"
                  style="width: 210px; height: 132px;"/>
                <i class="el-icon-close" @click="removePhoto"/>
              </div>
            </div>
            <div v-else class="imgs_update">
              <el-upload
                ref="uploadCertificate"
                :on-remove="handleRemoveCertificate"
                :on-change="handleChangeCertificate"
                :on-preview="handlePreview"
                :before-upload="beforeUploadCertificate"
                :auto-upload="false"
                :limit="1"
                :class="{hide:hideUploadCertificate}"
                action=""
                accept=".jpg,.jpeg,.png"
                list-type="picture-card">
                <div class="up_tip_icon">
                  <div class="up_tip_i">
                    <i class="el-icon-picture-outline" />
                  </div>
                  <div class="up_tip_text">
                    上传资格证照片
                  </div>
                </div>
              </el-upload>
              <div class="up_tip_test">
                <p class="h1">资格证照片</p>
                <p>图像格式：JPEG、JPG、PNG</p>
                <p>图像大小不超过5M。</p>
                <p>图像分辨率不低于72dpi。</p>
                <el-popover
                  placement="top-start"
                  width="280"
                  trigger="hover"
                >
                  <img :src="imgzmUrl" alt="" class="up_tip_sfz">
                  <el-button slot="reference" type="text">查看示例</el-button>
                </el-popover>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div class="detail_foot">
          <el-button type="primary" @click="confirm">保存</el-button>
          <el-button icon="el-icon-arrow-left" @click="goBack">返回</el-button>
        </div>
      </div>
      <el-dialog :visible.sync="dialogVisible">
        <img :src="dialogImageUrl" width="100%" alt="">
      </el-dialog>
    </div>
  </div>
</template>
<script>

import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
import { upload } from '@/utils/upload'
export default {
  directives: { waves },
  data() {
    return {
      imgzmUrl: require('@/assets/images/zgzs.png'),
      config: config,
      listLoading: true,
      PERMANENT_VALID_List: [{ value: '1', label: '是' }, { value: '-1', label: '否' }],
      QUALIFICATION_TYPE_List: [], // 数据字典
      form: {
        TEACHER_ID: this.$parent.TEACHER_ID, // 教师ID
        QUALIFICATION_TYPE: '', // 资质类型
        VOCATIONAL_CERTIFICATE_NUMBER: '', // 职业证书编号
        IS_PERMANENT_VALID: '', // 是否永久有效
        CERTIFICATE_DATE_BEGIN: '', // 证书有效期（开始）
        CERTIFICATE_DATE_END: '', // 证书有效期（结束）
        CERTIFICATE_FILEPATH: '', // 证书照片
        certificateFile: ''
      },
      hideUploadCertificate: false, // 显示图片
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      dialogType: 'add',
      rules: {
        TEACHER_ID: [{ required: true, message: '教师ID不能为空', trigger: 'blur' }],
        QUALIFICATION_TYPE: [{ required: true, message: '请选择资质类型', trigger: 'blur' }],
        VOCATIONAL_CERTIFICATE_NUMBER: [{ required: true, message: '职业证书编号不能为空', trigger: 'blur' }],
        IS_PERMANENT_VALID: [{ required: true, message: '是否永久有效不能为空', trigger: 'blur' }],
        CERTIFICATE_DATE_BEGIN: [{ required: true, message: '证书有效期（开始）不能为空', trigger: 'blur' }],
        CERTIFICATE_DATE_END: [{ required: false, message: '证书有效期（结束）不能为空', trigger: 'blur' }],
        certificateFile: [{ required: false, message: '请上传资格证照片' }]
      },
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  created() {
    this.resetForm()
    this.getDict()
    if (this.$parent.TEACHERCERTIFICATE_ID == '') {
      this.handleAdd()
    } else {
      this.handleEdit(this.$parent.TEACHERCERTIFICATE_ID)
    }
  },
  methods: {
    // 添加
    handleAdd() {
      this.dialogType = 'add'
      this.initRuls()
    },
    // 修改
    handleEdit(ID) {
      this.dialogType = 'edit'
      requestFN(
        '/teachercertificate/goEdit',
        {
          TEACHERCERTIFICATE_ID: ID
        }
      ).then((data) => {
        this.form = Object.assign({}, data.pd) // copy obj
        this.initRuls()
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 保存
    confirm() {
      if (this.form.IS_PERMANENT_VALID == '-1') {
        this.rules.CERTIFICATE_DATE_END = [{ required: true, message: '证书有效期（结束）不能为空', trigger: 'blur' }]
      } else {
        this.rules.CERTIFICATE_DATE_END = [{ required: false, message: '证书有效期（结束）不能为空', trigger: 'blur' }]
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          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(
            '/teachercertificate/' + this.dialogType,
            formData
          ).then((data) => {
            loading.close()
            this.$message({
              message: '教师证书信息保存成功。',
              type: 'success'
            })
            this.goBack()
          }).catch((e) => {
            this.listLoading = false
          })
        } else {
          return false
        }
      })
    },
    initRuls() {
      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() {
      this.form.CERTIFICATE_FILEPATH = ''
      this.form.certificateFile = ''
      this.hideUploadCertificate = false
    },

    /** 资格证照 **/
    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.hideUploadCertificate = fileList.length >= 1
    },
    handleChangeCertificate(file, fileList) {
      this.form.certificateFile = file
      this.hideUploadCertificate = fileList.length >= 1
    },

    // 获取数据字典数据
    getDict: function() {
      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID: '82d41f1cab2a4ed394ddbe69a15bb8f1' // 资质类型PARENT_ID
        }
      ).then((data) => {
        this.QUALIFICATION_TYPE_List = data.list
      }).catch((e) => {

      })
    },
    resetForm() {
      this.form = {
        TEACHER_ID: this.$parent.TEACHER_ID, // 教师ID
        QUALIFICATION_TYPE: '', // 资质类型
        VOCATIONAL_CERTIFICATE_NUMBER: '', // 职业证书编号
        IS_PERMANENT_VALID: '', // 是否永久有效
        CERTIFICATE_DATE_BEGIN: '', // 证书有效期（开始）
        CERTIFICATE_DATE_END: '', // 证书有效期（结束）
        CERTIFICATE_FILEPATH: '', // 证书照片
        certificateFile: '',
        hideUploadCertificate: false // 显示图片
      }
      this.hideUploadCertificate = false // 显示图片
    },
    goBack() {
      this.$parent.TEACHERCERTIFICATE_ID = ''
      this.$parent.activeName = 'CertificateList'
    }
  }
}

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