<template>
  <div class="app-warp">
    <div class="detail-structure">
      <el-page-header :content="!parentObj.USER_ID ? '新增' : '修改' + '页面'" @back="goBack"/>
      <div class="detail-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="证件类型" prop="CERTIFICATETYPE">
                <el-select v-model="form.CERTIFICATETYPE" disabled style="width: 100%;">
                  <el-option value="4bed7fac8fe24ad4b5c0c69321fd5916" label="身份证"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="证件号码" prop="USER_ID_CARD">
                <el-input v-model="form.USER_ID_CARD" placeholder="请输入证件号码"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学员姓名" prop="NAME">
                <el-input v-model="form.NAME" placeholder="请输入学员姓名"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="USERNAME">
                <el-input v-model="form.USERNAME" placeholder="请输入联系电话"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="SEX">
                <el-radio-group v-model="form.SEX">
                  <el-radio label="998f8531a6254c2eab5c825fa2d9896f">男</el-radio>
                  <el-radio label="fdd532d9def447cdb68af3a938f6f05c">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="工作单位" class="is-required">
                <el-select
                  v-if="inputOrSelect"
                  v-model="form.ENTERPRISE_ID"
                  :remote-method="remoteMethod"
                  :loading="employerLoading"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词查找工作单位"
                  style="width: 100%;"
                  @change="enterpriseChange">
                  <el-option
                    v-for="item in employerOptions"
                    :key="item.ENTERPRISE_ID"
                    :label="item.ENTERPRISE"
                    :value="item.ENTERPRISE_ID"/>
                </el-select>
                <el-input v-if="!inputOrSelect" v-model="form.ENTERPRISE" placeholder="请输入工作单位"/>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <el-button
                style="margin-left: 10px"
                @click="inputOrSelect = !inputOrSelect;form.ENTERPRISE = '';form.ENTERPRISE_ID = ''">
                {{ inputOrSelect ? '输入' : '选择' }}
              </el-button>
            </el-col>
            <el-col :span="12">
              <el-form-item label="统一社会信用代码" prop="CODE">
                <el-input v-model="form.CODE" :disabled="inputOrSelect" placeholder="请输入统一社会信用代码"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="证件照片" class="is-required">
                <el-upload
                  ref="uploadIdPhoto"
                  :on-preview="handlePreviewIdPhoto"
                  :on-remove="handleRemoveIdPhoto"
                  :on-change="handleChangeIdPhoto"
                  :auto-upload="false"
                  :file-list="form.fileListIdPhoto"
                  :limit="1"
                  :class="{hide:hideUpload}"
                  action="#"
                  accept=".jpg,.jpeg,.png"
                  list-type="picture-card">
                  <i class="el-icon-plus"/>
                </el-upload>
                <el-dialog :visible.sync="uploadVisible" append-to-body>
                  <img :src="CAPTURE" width="100%" alt="">
                </el-dialog>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文化水平" prop="DEGREE_OF_EDUCATION">
                <el-select v-model="form.DEGREE_OF_EDUCATION" style="width: 100%;">
                  <el-option v-for="item in degreeOfEducationList" :key="item.DICTIONARIES_ID" :value="item.DICTIONARIES_ID" :label="item.NAME"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职务/职称" prop="DUTIES">
                <el-input v-model="form.DUTIES" placeholder="请输入职务/职称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门" prop="STUDENT_DEPARTMENT">
                <el-input v-model="form.STUDENT_DEPARTMENT" placeholder="请输入部门"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工种" prop="TYPE_OF_WORK">
                <el-input v-model="form.TYPE_OF_WORK" placeholder="请输入工种"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="人员类型" prop="PERSONNEL_TYPE">
                <el-select v-model="form.PERSONNEL_TYPE" multiple style="width: 100%;">
                  <el-option v-for="item in personnelTypeList" :key="item.DICTIONARIES_ID" :value="item.DICTIONARIES_ID" :label="item.NAME"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="detail_foot">
          <el-button type="primary" @click="confirm">{{ !parentObj.USER_ID ? '立即创建' : '修改' }}</el-button>
          <el-button icon="el-icon-arrow-left" @click="goBack">返回</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { debounce } from 'throttle-debounce'
import { requestFN } from '@/utils/request'
import { upload } from '@/utils/upload'
export default {
  data() {
    return {
      config: config,
      form: {
        ROLE_ID: '96036bcce5cf418baf8bc2f91271c8c6',
        CERTIFICATETYPE: '4bed7fac8fe24ad4b5c0c69321fd5916',
        USER_ID_CARD: '',
        NAME: '',
        USERNAME: '',
        SEX: '',
        ENTERPRISE_ID: '',
        ENTERPRISE: '',
        CODE: '',
        DEGREE_OF_EDUCATION: '',
        DUTIES: '',
        STUDENT_DEPARTMENT: '',
        TYPE_OF_WORK: '',
        PERSONNEL_TYPE: [],
        fileListIdPhoto: []
      },
      rules: {
        CERTIFICATETYPE: [
          { required: true, message: '请选择证件类型', trigger: 'change' }
        ],
        USER_ID_CARD: [
          { required: true, message: '请输入证件号码', trigger: 'blur' },
          {
            pattern: /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: '请输入正确的证件号码'
          }
        ],
        NAME: [
          { required: true, message: '请输入学员姓名', trigger: 'blur' }
        ],
        USERNAME: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[189])\d{8}$/,
            message: '请输入正确的联系电话'
          }
        ],
        SEX: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        CODE: [
          { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
          {
            pattern: /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/,
            message: '请输入正确的统一社会信用代码'
          }
        ],
        DEGREE_OF_EDUCATION: [
          { required: true, message: '请选择文化水平', trigger: 'change' }
        ],
        DUTIES: [
          { required: true, message: '请输入职务/职称', trigger: 'blur' }
        ],
        STUDENT_DEPARTMENT: [
          { required: true, message: '请输入部门', trigger: 'blur' }
        ],
        TYPE_OF_WORK: [
          { required: true, message: '请输入工种', trigger: 'blur' }
        ],
        PERSONNEL_TYPE: [
          { required: true, message: '请选择人员类型', trigger: 'change' }
        ]
      },
      degreeOfEducationList: [],
      employerOptions: [],
      personnelTypeList: [],
      inputOrSelect: false,
      uploadVisible: false,
      hideUpload: false,
      CAPTURE: '',
      employerLoading: false
    }
  },
  inject: ['setActiveName', 'parentObj'],
  created() {
    if (this.parentObj.USER_ID) {
      this.getData()
    }
    this.getDict('d7d80f08d73a4accbccf4fd3d8d1d867', 'degreeOfEducationList')
    this.getDict('0b62f92b0b624aab8e89a77304a64d5e', 'personnelTypeList')
  },
  methods: {
    getData() {
      requestFN('/student/findStuById', {
        USER_ID: this.parentObj.USER_ID
      }).then((data) => {
        this.form = data.pd
        this.form.PERSONNEL_TYPE = data.pd.PERSONNEL_TYPE.split(',')
        this.form.fileListIdPhoto = [{
          url: this.config.fileUrl + data.pd.USER_SIGN_FILE_PATH
        }]
        this.hideUpload = true
      })
    },
    getDict(DICTIONARIES_ID, degreeOfEducationList) {
      requestFN('/dictionaries/getLevels', {
        DICTIONARIES_ID
      }).then((data) => {
        this[degreeOfEducationList] = data.list
      })
    },
    remoteMethod: debounce(1000, function(query) {
      this.employerLoading = true
      requestFN('/enterprise/listAll', {
        ENTERPRISE: query
      }).then((data) => {
        this.employerOptions = data.entList
        this.employerLoading = false
      })
    }),
    enterpriseChange(e) {
      for (let i = 0; i < this.employerOptions.length; i++) {
        if (this.employerOptions[i].ENTERPRISE_ID === e) {
          this.form.CODE = this.employerOptions[i].CODE
          this.form.ENTERPRISE = this.employerOptions[i].ENTERPRISE
          return
        }
      }
    },
    handlePreviewIdPhoto(file) {
      this.CAPTURE = file.url
      this.uploadVisible = true
    },
    handleRemoveIdPhoto(file, fileList) {
      this.hideUpload = fileList.length >= 1
    },
    handleChangeIdPhoto(file, fileList) {
      const types = ['image/jpeg', 'image/jpg', 'image/png']
      const isImage = types.includes(file.raw.type)
      if (!isImage) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG 格式!')
        fileList.pop()
      }
      this.hideUpload = fileList.length >= 1
    },
    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.form.ENTERPRISE_ID && !this.form.ENTERPRISE) {
            this.$message.error('请选择工作单位')
            return
          }
          if (this.$refs.uploadIdPhoto.uploadFiles.length === 0) {
            this.$message.error('请上传证件照片')
            return
          }
          const formData = new FormData()
          Object.keys(this.form).map(key => {
            formData.append(key, this.form[key])
          })
          formData.append('PHONE', this.form.USERNAME)
          formData.append('PERSONNEL_TYPE', this.form.PERSONNEL_TYPE.join(','))
          if (this.$refs.uploadIdPhoto.uploadFiles[0]) {
            formData.append('FFILE', this.$refs.uploadIdPhoto.uploadFiles[0].raw)
          }
          upload(!this.parentObj.USER_ID ? '/student/add' : '/student/edit', formData).then((res) => {
            if (res.message) {
              this.$message({
                message: res.message,
                type: 'warning'
              })
            } else {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.goBack()
            }
          })
        } else {
          this.$message.error('请检查输入项')
        }
      })
    },
    goBack() {
      this.setActiveName('List')
    }
  }
}
</script>

<style scoped>

</style>
