<template>
  <view class="content">
    <view class="card">
      <u--form labelPosition="left" :model="form" :rules="rules" ref="form" labelWidth="100px">
        <u-form-item label="证书正面图片" prop="fileList" borderBottom required>
          <u-upload
              :fileList="form.fileList"
              @afterRead="fnAfterRead"
              @delete="fnDeletePic"
              :maxCount="1"
              previewFullImage
          ></u-upload>
        </u-form-item>
        <u-form-item label="证书反面图片" prop="fileListBack" borderBottom required>
          <u-upload
              :fileList="form.fileListBack"
              @afterRead="fnAfterRead1"
              @delete="fnDeletePic1"
              :maxCount="1"
              previewFullImage
          ></u-upload>
        </u-form-item>
        <u-form-item label="姓名" prop="NAME" borderBottom required>
          <u--input v-model="form.NAME" border="none" disabled disabledColor="#ffffff"></u--input>
        </u-form-item>
        <u-form-item label="性别" prop="SEX_NAME" borderBottom required ng-switch-default="男">
          <u--input v-model="form.SEX_NAME" border="none" disabled disabledColor="#ffffff"></u--input>
        </u-form-item>
        <u-form-item label="手机号" prop="PHONE" borderBottom required>
          <u--input v-model="form.PHONE" border="none" disabled disabledColor="#ffffff"></u--input>
        </u-form-item>
        <u-form-item label="身份证号码" prop="CARD_ID" borderBottom required>
          <u--input v-model="form.CARD_ID" border="none" @blur="fnCardIdDisassembly" disabled
                    disabledColor="#ffffff"></u--input>
        </u-form-item>
        <u-form-item label="证书类型" prop="CER_TYPE_NAME" borderBottom required @click="fnShowCertificateType">
          <u--input v-model="form.CER_TYPE_NAME" border="none" disabled disabledColor="#ffffff"></u--input>
        </u-form-item>
        <u-form-item label="证书名称" prop="CERTIFICATE" borderBottom required>
          <u--input v-model="form.CERTIFICATE" border="none"></u--input>
        </u-form-item>
        <u-form-item label="证书编号" prop="SPECIAL_NUMBER" borderBottom required>
          <u--input v-model="form.SPECIAL_NUMBER" border="none"></u--input>
        </u-form-item>
        <u-form-item label="发证机关" prop="ISSUING_AUTHORITY" borderBottom required>
          <u--input v-model="form.ISSUING_AUTHORITY" border="none"></u--input>
        </u-form-item>
        <!--   @click="fnShowCertificateTypeJobs"     -->
        <u-form-item label="工种" prop="JOBS_TYPE" borderBottom required>
          <u--input v-model="form.JOBS_TYPE" border="none" disabledColor="#ffffff"></u--input>
        </u-form-item>
        <u-form-item v-if="form.CER_TYPE_NAME === '特种作业'" label="作业类别" prop="specialName" borderBottom required
                     @click="fnShowCertificateTypeSpe">
          <u--input v-model="form.specialName" border="none" disabled disabledColor="#ffffff"></u--input>
        </u-form-item>
        <u-form-item v-if="form.CER_TYPE_NAME === '特种作业'" label="操作项目" prop="operationName" borderBottom
                     required @click="fnShowCertificateTypeOpe">
          <u--input v-model="form.operationName" border="none" disabled disabledColor="#ffffff"></u--input>
        </u-form-item>
        <u-form-item label="有效期开始" prop="VALIDITY_TIME_START" borderBottom required
                     @click="fnShowTermOfValidityStart">
          <u--input v-model="form.VALIDITY_TIME_START" border="none" disabled disabledColor="#ffffff"></u--input>
        </u-form-item>
        <u-form-item label="有效期结束" prop="VALIDITY_TIME_END" borderBottom required
                     @click="fnShowTermOfValidityEnd">
          <u--input v-model="form.VALIDITY_TIME_END" border="none" disabled disabledColor="#ffffff"></u--input>
        </u-form-item>
        <u-form-item label="复审时间" prop="REVIEW_TIME" borderBottom required @click="fnShowReviewTime">
          <u--input v-model="form.REVIEW_TIME" border="none" disabled disabledColor="#ffffff"></u--input>
        </u-form-item>
      </u--form>
      <u-picker :show="showCertificateType" :columns="certificateTypeColumns" keyName="NAME"
                @confirm="fnCertificateTypeConfirm" @cancel="fnShowCertificateType"></u-picker>

      <u-picker :show="showCertificateTypeSpe" :columns="certificateTypeColumnsSpe" keyName="NAME"
                @confirm="fnCertificateTypeConfirmSpe" @cancel="fnShowCertificateTypeSpe"></u-picker>
      <u-picker :show="showCertificateTypeOpe" :columns="certificateTypeColumnsOpe" keyName="NAME"
                @confirm="fnCertificateTypeConfirmOpe" @cancel="fnShowCertificateTypeOpe"></u-picker>
      <u-datetime-picker :show="showTermOfValidityStart" v-model="termOfValidityStartValue" mode="date"
                         @confirm="fnTermOfValidityStartConfirm"
                         @cancel="fnShowTermOfValidityStart"></u-datetime-picker>
      <u-datetime-picker :show="showTermOfValidityEnd" v-model="termOfValidityEndValue" mode="date"
                         @confirm="fnTermOfValidityEndConfirm" @cancel="fnShowTermOfValidityEnd"></u-datetime-picker>
      <u-datetime-picker :show="showReviewTime" v-model="reviewTimeValue" mode="date"
                         @confirm="fnReviewTimeConfirm" @cancel="fnShowReviewTime"></u-datetime-picker>
      <view class="mt-10">
        <u-button type="primary" text="保 存" @click="$u.debounce(fnSubmit, 1000,true)"></u-button>
      </view>
    </view>
  </view>
</template>

<script>
import {
  getCertificateInformationView,
  getDataDictionary,
  getUserInfo,
  setCertificateInformationAdd,
  setCertificateInformationEdit,
  setCertificateInformationEditPost
} from "../../api";

export default {
  data() {
    return {
      SPECIAL_USER_ID: '',
      showCertificateType: false,
      showCertificateTypeSpe: false,
      showCertificateTypeOpe: false,
      certificateTypeColumns: [[]],
      certificateTypeColumnsJobs: [[]],
      certificateTypeColumnsSpe: [[]],
      certificateTypeColumnsOpe: [[]],
      showTermOfValidityStart: false,
      termOfValidityStartValue: new Date().toString(),
      showTermOfValidityEnd: false,
      termOfValidityEndValue: new Date().toString(),
      showReviewTime: false,
      reviewTimeValue: new Date().toString(),
      form: {
        fileList: [],
        fileListBack: [],
        NAME: '',
        SEX_NAME: '',
        PHONE: '',
        CARD_ID: '',
        CER_TYPE: '',
        CER_TYPE_NAME: '',
        CERTIFICATE: '',
        JOBS_TYPE: '',
        SPECIAL_TYPE: '',
        OPERATION_TYPE: '',
        SPECIAL_NUMBER: '',
        ISSUING_AUTHORITY: '',
        VALIDITY_TIME_START: '',
        VALIDITY_TIME_END: '',
        REVIEW_TIME: ''
      },
      rules: {
        fileList: {
          type: 'array',
          required: true,
          message: '请上传证书图片',
          trigger: ['change']
        },
        fileListBack: {
          type: 'array',
          required: true,
          message: '请上传证书图片',
          trigger: ['change']
        },
        CER_TYPE_NAME: {
          required: true,
          message: '请选择证书类型',
          trigger: ['change']
        },
        CERTIFICATE: {
          required: true,
          message: '请填写证书名称',
          trigger: ['change']
        },
        SPECIAL_NUMBER: {
          required: true,
          message: '请填写证书编号',
          trigger: ['blur']
        },
        JOBS_TYPE: {
          required: true,
          message: '请填写工种',
          trigger: ['change']
        },
        specialName: {
          required: true,
          message: '请选择作业类别',
          trigger: ['change']
        },
        operationName: {
          required: true,
          message: '请选择操作项目',
          trigger: ['change']
        },
        ISSUING_AUTHORITY: {
          required: true,
          message: '请填写发证机关',
          trigger: ['blur']
        },
        VALIDITY_TIME_START: {
          required: true,
          message: '请选择有效期开始时间',
          trigger: ['change']
        },
        VALIDITY_TIME_END: {
          required: true,
          message: '请选择有效期结束时间',
          trigger: ['change']
        },
        REVIEW_TIME: {
          required: true,
          message: '请选择复审时间',
          trigger: ['change']
        }
      }
    }
  },
  onLoad(query) {
    this.SPECIAL_USER_ID = query.SPECIAL_USER_ID
    if (query.SPECIAL_USER_ID) {
      uni.setNavigationBarTitle({
        title: '证书信息编辑'
      })
    } else {
      uni.setNavigationBarTitle({
        title: '证书信息添加'
      })
    }
    this.fnGetDataDictionary()
    this.fnGetData()
    this.fnGetDataDictionaryJobs()
    this.fnGetDataDictionarySpe()
    //this.fnGetDataDictionaryOpe()
  },
  computed: {
    userInfo() {
      return this.$store.getters.getUserInfo
    }
  },
  methods: {
    async fnGetData() {
      if (this.SPECIAL_USER_ID) {
        let resData = await getCertificateInformationView({
          SPECIAL_USER_ID: this.SPECIAL_USER_ID
        })
        this.form = {...this.form, ...resData.pd, CER_TYPE_NAME: resData.pd.typeName}
        this.$set(this.form, 'fileList', [{
          url: this.$filePath + resData.pd.FILEPATH,
          FILEPATH: this.$filePath + resData.pd.FILEPATH
        }])
        this.$set(this.form, 'fileListBack', [{
          url: this.$filePath + resData.pd.FILEPATH_BACK,
          FILEPATH: this.$filePath + resData.pd.FILEPATH_BACK
        }])
        let resDatares = await getDataDictionary({DICTIONARIES_ID: this.form.SPECIAL_TYPE})
        this.certificateTypeColumnsOpe = [resDatares.list]
      } else {
        let resData = await getUserInfo({
          CORPINFO_ID: this.userInfo.CORPINFO_ID,
        })
        this.form = {...this.form, ...resData.pd}
        this.fnCardIdDisassembly(this.form.CARD_ID)
        this.fnCardIdDisassembly(this.form.CARD_ID)
      }
      if (this.form.SEX_NAME === '0') {
        this.form.SEX_NAME = '男'
      } else if (this.form.SEX_NAME === '1') {
        this.form.SEX_NAME = '女'
      }
    },
    async fnGetDataDictionary() {
      let resData = await getDataDictionary({DICTIONARIES_ID: '6f87965751b84311b066484ac93c8077'})
      this.certificateTypeColumns = [resData.list]
    },
    async fnGetDataDictionaryJobs() {
      let resData = await getDataDictionary({DICTIONARIES_ID: '55484e491a5e442d839c4595380713ec'})
      this.certificateTypeColumnsJobs = [resData.list]
    },
    async fnGetDataDictionarySpe() {
      let resData = await getDataDictionary({DICTIONARIES_ID: 'f4c3890d06d54904b32986cb6428ed4f'})
      this.certificateTypeColumnsSpe = [resData.list]
    },
    async fnGetDataDictionaryOpe() {
      let resData = await getDataDictionary({DICTIONARIES_ID: this.form.SPECIAL_TYPE})
      this.certificateTypeColumnsOpe = [resData.list]
    },
    fnCardIdDisassembly(event) {
      if (uni.$u.test.idCard(event)) {
        if (parseInt(event.substring(17, 1)) % 2 === 1) {
          this.form.SEX = "0";
          this.form.SEX_NAME = "男";
        } else {
          this.form.SEX = "1";
          this.form.SEX_NAME = "女";
        }
      }
    },
    fnShowCertificateType() {
      this.showCertificateType = !this.showCertificateType
    },

    fnShowCertificateTypeSpe() {
      this.showCertificateTypeSpe = !this.showCertificateTypeSpe;
    },
    fnShowCertificateTypeOpe() {
      this.showCertificateTypeOpe = !this.showCertificateTypeOpe
    },
    fnCertificateTypeConfirm(e) {
      this.form.CER_TYPE = e.value[0].DICTIONARIES_ID
      this.form.CER_TYPE_NAME = e.value[0].NAME
      this.fnShowCertificateType()
    },
    fnCertificateTypeConfirmSpe(e) {
      this.form.specialName = e.value[0].NAME
      this.form.SPECIAL_TYPE = e.value[0].DICTIONARIES_ID
      this.fnShowCertificateTypeSpe()
      this.fnGetDataDictionaryOpe();
      this.form.operationName = '';
      this.form.OPERATION_TYPE = '';
    },
    fnCertificateTypeConfirmOpe(e) {
      this.form.operationName = e.value[0].NAME
      this.form.OPERATION_TYPE = e.value[0].DICTIONARIES_ID
      this.fnShowCertificateTypeOpe()
    },
    fnShowTermOfValidityStart() {
      this.showTermOfValidityStart = !this.showTermOfValidityStart
    },
    fnTermOfValidityStartConfirm(event) {
      this.termOfValidityStartValue = event.value
      this.fnShowTermOfValidityStart()
      this.form.VALIDITY_TIME_START = uni.$u.timeFormat(event.value, 'yyyy-mm-dd')
    },
    fnShowTermOfValidityEnd() {
      this.showTermOfValidityEnd = !this.showTermOfValidityEnd
    },
    fnTermOfValidityEndConfirm(event) {
      this.termOfValidityEndValue = event.value
      this.fnShowTermOfValidityEnd()
      this.form.VALIDITY_TIME_END = uni.$u.timeFormat(event.value, 'yyyy-mm-dd')
    },
    fnShowReviewTime() {
      this.showReviewTime = !this.showReviewTime
    },
    fnReviewTimeConfirm(event) {
      this.reviewTimeValue = event.value
      this.fnShowReviewTime()
      this.form.REVIEW_TIME = uni.$u.timeFormat(event.value, 'yyyy-mm-dd')
    },
    fnAfterRead(event) {
      var houzhui
      if(event.file.name){
        houzhui = event.file.name.split('.').pop().toLowerCase();
      }else {
        houzhui = event.file.url.replace(/.+\./, "");
      }
      if (['jpg', 'png'].includes(houzhui)) {
        this.form.fileList.push(event.file);
      } else {
        uni.$u.toast('图片格式不正确，请上传jpg格式图片或者png格式图片');
      }
    },
    fnAfterRead1(event) {
      var houzhui;
      if(event.file.name){
        houzhui = event.file.name.split('.').pop().toLowerCase();
      }else {
        houzhui = event.file.url.replace(/.+\./, "");
      }
      if (['jpg', 'png'].includes(houzhui)) {
        this.form.fileListBack.push(event.file)
      } else {
        uni.$u.toast('图片格式不正确，请上传jpg格式图片或者png格式图片')
        this.form.fileListBack = []
      }
    },
    fnDeletePic(event) {
      this.form.fileList.splice(event.index, 1)
    },
    fnDeletePic1(event) {
      this.form.fileListBack.splice(event.index, 1)
    },
    async fnSubmit() {
      console.info(this.$refs)
      this.$refs.form.validate().then(async () => {
        if (!this.SPECIAL_USER_ID) {
          let files = []
          files.push({
            name: 'FILEPATH',
            file: this.form.fileList[0],
            uri: this.form.fileList[0].url,
          })

          files.push({
            name: 'FILEPATH_BACK',
            file: this.form.fileListBack[0],
            uri: this.form.fileListBack[0].url,
          })

          if (files.length !== 2) {
            uni.$u.toast('请上传证书正反面')
            return
          }

          await setCertificateInformationAdd({
            files: files,
            formData: {
              ...this.form
            }
          })
        } else {
          if (!this.form.fileList[0].FILEPATH || !this.form.fileListBack[0].FILEPATH) {
            uni.$u.toast('1')
            let files = []
            if (!this.form.fileList[0].FILEPATH) {
              files.push({
                name: 'FILEPATH',
                file: this.form.fileList[0],
                uri: this.form.fileList[0].url,
              })
            }

            if (!this.form.fileListBack[0].FILEPATH) {
              files.push({
                name: 'FILEPATH_BACK',
                file: this.form.fileListBack[0],
                uri: this.form.fileListBack[0].url,
              })
            }

            await setCertificateInformationEdit({
              files: files,
              formData: {
                ...this.form
              }
            })
          } else {
            this.form.fileMark = '1',
                await setCertificateInformationEditPost({
                  ...this.form
                })
          }

        }
        // uni.$u.toast('保存成功')
        setTimeout(() => {
          uni.navigateBack()
        }, 2000)
      }).catch((e) => {
        console.info(e)
        uni.$u.toast('请补全必填项')
      })
    }
  },
}


</script>

<style scoped lang="scss">
</style>
