<template>
  <div class="base-info">
    <cy-info-title>基础信息</cy-info-title>
    <el-form
      ref="ruleFormRef"
      :key="key"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      label-width="150px"
      class="rule-form-orange"
    >
      <el-form-item label="客户类别" prop="customerType">
        <el-select
          v-model="ruleForm.customerType"
          placeholder="请选择客户类别"
          :disabled="disabled"
          @change="changeCustomer"
        >
          <el-option
            v-for="item in [
              { value: 0, label: '企业' },
              { value: 1, label: '个体工商户' },
              // { value: 2, label: '个人' },
            ]"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-if="ruleForm.customerType !== 2">
        <el-form-item label="客户名称" prop="customerName">
          <el-select
            v-model="ruleForm.customerName"
            :disabled="disabled"
            :placeholder="placeholder"
            :clearable="false"
            @change="searchChange"
          >
            <el-option
              v-for="item in listData"
              :key="item.customerName"
              :label="item.customerName"
              :value="item.customerName"
            />
          </el-select>
          <!-- <custom-select
            :value.sync="ruleForm.customerName"
            :disabled="disabled"
            :placeholder="placeholder"
            :clearable="false"
            @search-click="searchClick"
            @search-change="searchChange"
          >
            <el-option
              v-for="item in listData"
              :key="item.corporateName"
              :label="item.corporateName"
              :value="item.corporateName"
            />
          </custom-select> -->
        </el-form-item>
        <el-form-item label="证件种类" prop="certificateType">
          <el-select
            v-model="ruleForm.certificateType"
            placeholder="请选择证件种类"
            disabled
          >
            <el-option
              v-for="item in constant.enterpriseCertificateType"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="注册国别" prop="registeredCountry">
          <el-select
            v-model="ruleForm.registeredCountry"
            placeholder="请选择注册国别"
            disabled
          >
            <el-option
              v-for="item in constant.registerCountry"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="socialCreditCode">
          <el-input
            v-model="ruleForm.socialCreditCode"
            placeholder="请输入统一社会信用代码"
            disabled
          />
        </el-form-item>
        <el-form-item label="证件过期时间" prop="certificateExpirationDate">
          <el-input
            v-model="ruleForm.certificateExpirationDate"
            placeholder="请输入证件过期时间"
            disabled
          />
        </el-form-item>
        <el-form-item label="营业执照" class="form-required">
          <cy-upload
            ref="businessLicenseRef"
            :upload-params="{
              fileType: 'bocomRegisterBusinessLicense',
            }"
            :file-data="fileList"
            :disabled="disabled"
            :upload-from-orange-status="true"
            placeholder="请上传营业执照"
          />
        </el-form-item>
        <el-form-item label="注册地址" prop="registeredAddress">
          <el-input
            v-model="ruleForm.registeredAddress"
            placeholder="请输入注册地址"
            disabled
          />
        </el-form-item>
        <el-form-item label="经营地址" prop="businessAddress">
          <el-input
            v-model="ruleForm.businessAddress"
            placeholder="请输入经营地址"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="经营范围" style="width: 100%" prop="businessScope">
          <el-input
            v-model="ruleForm.businessScope"
            type="textarea"
            placeholder="请输入经营范围"
            :disabled="disabled"
            :rows="3"
          />
        </el-form-item>
      </template>
      <template v-if="ruleForm.customerType === 2">
        <el-form-item label="国籍" prop="registeredCountry">
          <el-select
            v-model="ruleForm.registeredCountry"
            placeholder="请选择国籍"
            disabled
          >
            <el-option
              v-for="item in constant.registerCountry"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证正面" class="form-required">
          <cy-upload
            ref="idCardFront"
            :upload-params="{
              fileType: 'bocomIdCardFront',
            }"
            :file-data="frontFileList"
            :disabled="disabled"
            :upload-from-orange-status="true"
            :limit="1"
            :file-type="'jpeg,jpg,png,bmp,gif'"
            placeholder="请上传身份证正面(格式:jpeg、jpg、png、bmp、gif)"
            :is-call-back="true"
            @call-back="callBack"
          />
        </el-form-item>
        <el-form-item label="身份证反面" class="form-required">
          <cy-upload
            ref="idCardReverse"
            :upload-params="{
              fileType: 'bocomIdCardBack',
            }"
            :file-data="backFileList"
            :disabled="disabled"
            :upload-from-orange-status="true"
            :limit="1"
            :file-type="'jpeg,jpg,png,bmp,gif'"
            placeholder="请上传身份证反面(格式:jpeg、jpg、png、bmp、gif)"
            :is-call-back="true"
            @call-back="callBack"
          />
        </el-form-item>
        <el-form-item label="个人姓名" prop="personName">
          <el-input
            v-model="ruleForm.personName"
            placeholder="请输入个人姓名"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="证件种类" prop="idType">
          <el-select
            v-model="ruleForm.idType"
            placeholder="请选择证件种类"
            :disabled="disabled"
          >
            <el-option
              v-for="item in constant.idCard"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="ruleForm.gender" :disabled="disabled">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="证件号码" prop="idNumber">
          <el-input
            v-model="ruleForm.idNumber"
            placeholder="请输入证件号码"
            :disabled="disabled"
            @blur="getIdType"
          />
        </el-form-item>
        <el-form-item label="证件有效期" prop="periodOfValidity">
          <el-date-picker
            v-model="ruleForm.periodValidityDate"
            value-format="yyyy-MM-dd"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%;"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="职业" prop="occupation">
          <el-select
            v-model="ruleForm.occupation"
            placeholder="请选择职业"
            :disabled="disabled"
          >
            <el-option
              v-for="item in constant.occupationTypes"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系地址" prop="contactAddress">
          <el-input
            v-model="ruleForm.contactAddress"
            placeholder="请输入联系地址"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input
            v-model="ruleForm.phoneNumber"
            placeholder="请输入手机号"
            :disabled="disabled"
          />
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getEnterpriseCompany } from '@/api/accountCenter/openInfoManage'
import { getCompanyInfoFormSocialCreditCode } from '@/api/dictionary'
import qichachaInfo from '../../mixins/qichachaInfo'
import { validPhone } from '@/utils/validate'

export default {
  components: {
    // CustomSelect: () => import('@/components/CustomSelect/index.vue')
  },
  mixins: [qichachaInfo],
  props: {
    // 来源
    source: {
      type: String,
      default: ''
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 详情信息
    detailsInfo: {
      type: Object,
      default: () => {}
    },
    placeholder: {
      type: String,
      default: '请选择客户名称'
    }
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号'))
      }
      if (!validPhone(value)) {
        return callback(new Error('请输入有效的手机号'))
      }
      callback()
    }
    return {
      fileList: [], // 营业执照
      frontFileList: [], // 身份证正面
      backFileList: [], // 身份证反面
      listData: [],
      ruleForm: {
        customerType: '',
        customerName: '',
        certificateType: 'enterpriseCertificateType_2011',
        registeredCountry: 'registerCountry_CHN',
        socialCreditCode: '',
        certificateExpirationDate: '',
        registeredAddress: '',
        businessAddress: '',
        businessScope: '',
        gender: '',
        periodOfValidity: '',
        occupation: '',
        phoneNumber: '',
        periodOfValidityFrom: '',
        periodValidityDate: [],
        idType: '',
        idNumber: '',
        personName: '',
        contactAddress: ''
      },
      rules: {
        customerType: [{ required: true, message: `请选择客户类别`, trigger: 'change' }],
        customerName: [{ required: true, message: `请选择客户名称`, trigger: 'change' }],
        personName: [{ required: true, message: `请输入个人姓名`, trigger: 'change' }],
        certificateType: [{ required: true, message: `请选择证件种类`, trigger: 'change' }],
        idType: [{ required: true, message: `请选择证件种类`, trigger: 'change' }],
        registeredCountry: [{ required: true, message: `请选择注册国别`, trigger: 'change' }],
        socialCreditCode: [{ required: true, message: `请输入统一社会信用代码`, trigger: 'blur' }],
        idNumber: [{ required: true, message: `请输入证件号码`, trigger: 'blur' }],
        // certificateExpirationDate: [{ required: true, message: `请输入证件过期时间`, trigger: 'blur' }],
        registeredAddress: [{ required: true, message: `请输入注册地址`, trigger: 'blur' }],
        businessAddress: [{ required: true, message: `请输入经营地址`, trigger: 'blur' }],
        businessScope: [{ required: true, message: `请输入经营范围`, trigger: 'blur' }],
        gender: [{ required: true, message: `请选择性别`, trigger: 'change' }],
        periodValidityDate: [{ required: true, message: `请选择证件有效期`, trigger: 'change' }],
        occupation: [{ required: true, message: `请选择职业`, trigger: 'change' }],
        contactAddress: [{ required: true, message: `请输入联系地址`, trigger: 'blur' }],
        phoneNumber: [
          { required: true, message: `请选择手机号`, trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ]

      },
      key: 1,
      deepRuleForm: {}
    }
  },
  computed: {
    ...mapGetters(['constant'])
  },
  watch: {
    detailsInfo: {
      handler(newV) {
        if (newV && Object.keys(newV).length) {
          const deepData = JSON.parse(JSON.stringify(newV))
          for (const key in this.ruleForm) {
            this.ruleForm[key] = deepData[key]
            if (deepData.customerType === 2) {
              this.ruleForm.personName = deepData.customerName
              this.ruleForm.idType = deepData.certificateType
              this.ruleForm.idNumber = deepData.socialCreditCode
            }
          }
          this.fileList = deepData.file ? [deepData.file] : []
          this.frontFileList = deepData.frontFile ? [deepData.frontFile] : []
          this.backFileList = deepData.backFile ? [deepData.backFile] : []

          this.ruleForm.periodValidityDate = this.ruleForm.periodOfValidityFrom ? [this.ruleForm.periodOfValidityFrom, this.ruleForm.periodOfValidity] : []
          this.searchClick(this.ruleForm.customerType)
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.$store.dispatch('getConstant', ['enterpriseCertificateType', 'idCard', 'registerCountry', 'occupationTypes'])
    this.deepRuleForm = JSON.parse(JSON.stringify(this.ruleForm))
  },
  methods: {
    changeCustomer(val) {
      this.$emit('changeCustomerStatus', val)
      this.ruleForm = JSON.parse(JSON.stringify(this.deepRuleForm))
      if (val !== 2) {
        this.ruleForm.certificateType = 'enterpriseCertificateType_2011'
      } else {
        this.ruleForm.certificateType = ''
      }
      this.ruleForm.customerType = val
      this.key += 1
      this.searchClick(val)
      // this.getConpanyInfo()
    },
    searchClick(val) {
      getEnterpriseCompany({ customerType: val }).then(({ data }) => {
        this.listData = data
      })
    },
    searchChange(val) {
      const obj = this.listData.find((item) => item.customerName === val)
      if (!obj) return
      const {
        socialCreditCode,
        registeredAddress,
        legalRepresentative
      } = obj
      this.ruleForm = {
        ...this.ruleForm,
        socialCreditCode,
        registeredAddress: registeredAddress,
        businessAddress: registeredAddress
      }
      // 法定代表人
      this.$emit('getLegalRepresentative', legalRepresentative)
      this.getConpanyInfo()
    },

    getConpanyInfo() {
      if (this.ruleForm.customerType !== 2 && this.ruleForm.socialCreditCode) {
        getCompanyInfoFormSocialCreditCode({ keyword: this.ruleForm.socialCreditCode }).then(({ data }) => {
          const { scope, date } = data
          this.ruleForm.certificateExpirationDate = date
          this.ruleForm.businessScope = scope
          this.$emit('getCompanyInfo', data)
        })
      }
    },
    submitParams(type) {
      let front = null
      let back = null
      let fileId = null
      if (this.ruleForm.customerType === 2) {
        const idCardFront = this.$refs.idCardFront.getFileLists
        if (type === 'submit' && !idCardFront.length) {
          this.$message.error('请上传身份证正面照片')
          return false
        }
        const idCardReverse = this.$refs.idCardReverse.getFileLists
        if (type === 'submit' && !idCardReverse.length) {
          this.$message.error('请上传身份证反面照片')
          return false
        }

        front = idCardFront.length ? idCardFront[0].id : ''
        back = idCardReverse.length ? idCardReverse[0].id : ''
      } else {
        const businessLicense = this.$refs.businessLicenseRef.getFileLists
        if (type === 'submit' && !businessLicense.length) {
          this.$message.error('请上传营业执照')
          return false
        }
        fileId = businessLicense.length ? businessLicense[0].id : ''
      }
      const { periodValidityDate, personName, customerType, customerName, idType, idNumber, socialCreditCode, certificateType } = this.ruleForm
      const params = {
        ...this.ruleForm,
        periodOfValidityFrom: periodValidityDate && periodValidityDate.length ? periodValidityDate[0] : '',
        periodOfValidity: periodValidityDate && periodValidityDate.length ? periodValidityDate[1] : '',
        fileId,
        front,
        back,
        customerName: customerType === 2 ? personName : customerName,
        certificateType: customerType === 2 ? idType : certificateType,
        socialCreditCode: customerType === 2 ? idNumber : socialCreditCode
      }
      delete params.periodValidityDate
      delete params.idType
      delete params.idNumber
      delete params.personName
      return params
    },
    validate() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleFormRef.validate((valid) => {
          if (valid) {
            return resolve(this.submitParams('submit'))
          } else {
            reject()
            return false
          }
        })
      })
    },
    getParams(type) {
      return new Promise((resolve, reject) => {
        if (type === 'temp') {
          resolve(this.submitParams(type))
        } else {
          this.validate().then((data) => {
            resolve(data)
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.enterprise-inspection {
}
</style>
