<template>
  <div class="basic-info">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      label-width="150px"
      class="rule-form-orange"
    >
      <el-form-item label="企业类型" prop="enterpriseType">
        <el-select
          v-model="ruleForm.enterpriseType"
          placeholder="请选择企业类型"
          :disabled="source === 'business' || ( $route.query.type === 'update' && ruleForm.certificationStatus !== 'in_certification' )"
        >
          <el-option
            v-for="item in constant.enterprise_type"
            :key="item.dictCode"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="企业名称" prop="name">
        <custom-select
          :value.sync="ruleForm.name"
          :disabled="source === 'business' || ( $route.query.type === 'update' && ruleForm.certificationStatus !== 'in_certification' )"
          placeholder="请输入企业名称"
          @search-click="searchClick"
          @search-change="searchChange"
        >
          <el-option
            v-for="item in listData"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          />
        </custom-select>
      </el-form-item>
      <el-form-item label="统一社会信用代码" prop="certNo">
        <el-input
          v-model="ruleForm.certNo"
          placeholder="请输入统一社会信用代码"
          disabled
        />
      </el-form-item>
      <el-form-item label="纳税人识别号" prop="taxNo">
        <el-input
          v-model="ruleForm.taxNo"
          placeholder="请输入纳税人识别号"
          :disabled="source === 'business' || ( $route.query.type === 'update' && ruleForm.certificationStatus !== 'in_certification')"
        />
      </el-form-item>
      <el-form-item label="成立日期" prop="establishDate">
        <el-input
          v-model="ruleForm.establishDate"
          placeholder="请输入成立日期"
          disabled
        />
      </el-form-item>
      <el-form-item label="营业执照扫描件" prop="businessLicense">
        <span slot="label" class="required-label">营业执照扫描件</span>
        <cy-upload
          ref="businessLicense"
          :upload-params="{
            fileType: 'businessLicense'
          }"
          :file-data="ruleForm.businessLicense"
          :upload-from-orange-status="true"
          placeholder="请上传营业执照扫描件"
          :limit="1"
          :file-size="20"
          :disabled="disabled"
        />
      </el-form-item>
      <el-form-item label="注册资本" prop="registerCapital">
        <!-- <el-input
          v-model="ruleForm.registerCapital"
          placeholder="请输入注册资本"
          disabled
        /> -->
        <cy-amount-input
          v-model="ruleForm.registerCapital"
          placeholder="请输入注册资本"
          unit-name="万元"
          is-unit
          disabled
        />
      </el-form-item>
      <el-form-item label="注册地址" prop="registerAddress">
        <el-input
          v-model="ruleForm.registerAddress"
          placeholder="请输入注册地址"
          disabled
        />
      </el-form-item>

      <el-form-item label="注册地址是否实际经营地址" prop="sameRegisterAndBusinessAddress">
        <el-select
          v-model="ruleForm.sameRegisterAndBusinessAddress"
          placeholder="请选择注册地址是否实际经营地址"
          :disabled="disabled"
        >
          <el-option
            v-for="item in constant.sys_yes_no"
            :key="item.dictCode"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="ruleForm.sameRegisterAndBusinessAddress === 'N'"
        label="经营地址"
        prop="businessAddress"
        :rules="[{ required: true, message: '请输入经营地址', trigger: 'blur' }]"
      >
        <el-input
          v-model="ruleForm.businessAddress"
          placeholder="请输入省，市，区，详细地址"
          :disabled="disabled"
        />
      </el-form-item>

      <el-form-item label="联系人（授权代理人）姓名" prop="contactPerson.name">
        <el-input v-model="ruleForm.contactPerson.name" :disabled="disabled" placeholder="请输入联系人（授权代理人）姓名" />
      </el-form-item>
      <el-form-item label="联系人（授权代理人）手机号" prop="contactPerson.mobile">
        <el-input v-model="ruleForm.contactPerson.mobile" :disabled="disabled" placeholder="请输入常用手机号" />
      </el-form-item>
      <el-form-item label="联系人（授权代理人）身份证号" prop="contactPerson.personalCertNo">
        <cy-card-input v-model="ruleForm.contactPerson.personalCertNo" :disabled="disabled" placeholder="请输入有效的身份证号" />
      </el-form-item>
      <el-form-item label="联系人（授权代理人）邮箱" prop="contactPerson.email">
        <el-input v-model="ruleForm.contactPerson.email" :disabled="disabled" placeholder="请输入邮箱地址">
          <template v-if="!disabled" #append>
            <verification-code :code="ruleForm.contactPerson.email" :template-name="'UserCertification'" type="mail" placeholder="请输入邮箱地址" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        v-if="!disabled"
        label="请输入邮箱验证码"
        prop="emailAuthCode"
        :rules="[{ required: true, message: `请输入验证码`, trigger: 'blur' }]"
      >
        <el-input v-model="ruleForm.emailAuthCode" :disabled="disabled" placeholder="请输入邮箱验证码" />
      </el-form-item>
      <el-form-item label="出口类型" prop="exportType">
        <el-select
          v-model="ruleForm.exportType"
          placeholder="请选择出口类型"
          :disabled="disabled"
        >
          <el-option
            v-for="item in constant.export_type"
            :key="item.dictCode"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="ruleForm.exportType === 'proxy_export'"
        label="代理公司所属区域"
        prop="proxyDistrictCode"
        :rules="[{ required: ruleForm.exportType === 'proxy_export', message: '请选择代理公司所属区域', trigger: 'change' }]"
      >
        <el-select
          v-model="ruleForm.proxyDistrictCode"
          placeholder="请选择代理公司所属区域"
          :disabled="disabled"
        >
          <el-option
            v-for="item in constant.district_code"
            :key="item.dictCode"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="海关企业代码" prop="customsEnterpriseCode">
        <el-input v-model="ruleForm.customsEnterpriseCode" :disabled="source === 'business' || ( $route.query.type === 'update' && ruleForm.certificationStatus !== 'in_certification' )" placeholder="请输入海关企业代码" />
      </el-form-item>
      <el-form-item label="主管税务机关" prop="taxAuthorityArea">
        <el-select
          v-model="ruleForm.taxAuthorityArea"
          placeholder="请选择主管税务机关"
          :disabled="disabled"
        >
          <el-option
            v-for="item in constant.tax_authority_area"
            :key="item.dictCode"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { qccEnterprise, qccEnterpriseDetail } from '@/api/businessManage/index'
import { validIdcard, validMail, validPhone } from '@/utils/validate'
export default {
  components: {
    CustomSelect: () => import('@/components/CustomSelect/index.vue'),
    VerificationCode: () => import('@/components/VerificationCode/index.vue')
  },
  props: {
    detailInfo: {
      type: Object,
      default: () => {}
    },
    source: {
      type: String,
      default: ''
    }
  },
  data() {
    const validTaxNo = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入纳税人识别号'))
      } else if (value.length !== 15 && value.length !== 18) {
        callback(new Error('纳税人识别号格式有误'))
      } else {
        callback()
      }
    }
    const validContactPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入'))
      } else if (!validPhone(value)) {
        callback(new Error('手机号格式有误'))
      } else {
        callback()
      }
    }
    const validContactEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入'))
      } else if (!validMail(value)) {
        callback(new Error('邮箱格式有误'))
      } else {
        callback()
      }
    }
    const validContactIdcard = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入'))
      } else if (!validIdcard(value)) {
        callback(new Error('身份证号格式有误'))
      } else {
        callback()
      }
    }
    const validEnterCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入'))
      } else if (!/^[\da-zA-Z]{10}$/.test(value) || value.length !== 10) {
        callback(new Error('海关企业代码格式有误'))
      } else {
        callback()
      }
    }
    return {
      listData: [],
      ruleForm: {
        changeRecordId: '',
        certificationStatus: '',
        enterpriseType: '',
        name: '',
        certNo: '',
        taxNo: '',
        establishDate: '',
        registerCapital: '',
        registerAddress: '',
        contactPerson: {
          // id: '',
          name: '',
          personalCertNo: '',
          mobile: '',
          email: '',
          isAuthorizedPerson: 'Y'
        },
        sameRegisterAndBusinessAddress: '',
        businessAddress: '',
        businessLicense: [],
        exportType: '',
        proxyDistrictCode: '',
        customsEnterpriseCode: '',
        taxAuthorityArea: '',
        emailAuthCode: null
      },
      rules: {
        enterpriseType: [
          { required: true, message: `请选择企业类型`, trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ],
        certNo: [
          { required: true, message: `请输入统一社会信用代码`, trigger: 'blur' }
        ],
        taxNo: [
          { required: true, message: `请输入纳税人识别号`, trigger: 'blur' },
          { validator: validTaxNo, trigger: 'blur' }
        ],
        establishDate: [
          { required: true, message: `请选择成立日期`, trigger: 'change' }
        ],
        registerCapital: [
          { required: true, message: `请输入注册资本`, trigger: 'blur' }
        ],
        registerAddress: [
          { required: true, message: `请输入注册地址`, trigger: 'blur' }
        ],
        'contactPerson.name': [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        'contactPerson.mobile': [{ required: true, message: '请输入常用手机号', trigger: 'blur' }, { validator: validContactPhone, trigger: 'blur' }],
        'contactPerson.email': [{ required: true, message: '请输入常用邮箱', trigger: 'blur' }, { validator: validContactEmail, trigger: 'blur' }],
        'contactPerson.personalCertNo': [{ required: true, message: '请输入有效的身份证号码', trigger: 'blur' }, { validator: validContactIdcard, trigger: 'blur' }],
        sameRegisterAndBusinessAddress: [{ required: true, message: '请选择注册地址是否实际经营地址', trigger: 'change' }],
        exportType: [{ required: true, message: '请选择出口类型', trigger: 'change' }],
        customsEnterpriseCode: [{ required: true, message: '请输入海关企业代码', trigger: 'blur' }, { validator: validEnterCode, trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'constant'
    ])
  },
  watch: {
    detailInfo: {
      handler(newV) {
        if (Object.keys(newV).length) {
          const details = JSON.parse(JSON.stringify(newV))
          for (const k in this.ruleForm) {
            if (k !== 'contactPerson') {
              if (details[k] !== '' && details[k] !== null && details[k] !== undefined) {
                this.ruleForm[k] = details[k]
              }
            } else {
              for (const key in this.ruleForm.contactPerson) {
                if (details[k][key] !== '' && details[k][key] !== null && details[k][key] !== undefined) {
                  this.ruleForm[k][key] = details[k][key]
                }
              }
            }
          }

          // if (newV && Object.keys(newV).length) {
          //   const { enterpriseType, name, certNo, establishDate, registerCapital, registerAddress } = newV
          //   this.ruleForm = {
          //     ...this.ruleForm,
          //     enterpriseType,
          //     name,
          //     certNo,
          //     establishDate,
          //     registerCapital,
          //     registerAddress
          //   }
          // }
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.$store.dispatch('getConstant', ['sys_yes_no', 'enterprise_type', 'district_code', 'export_type', 'tax_authority_area'])
    this.disabled = this.source === 'business'
  },
  methods: {
    searchClick(val) {
      qccEnterprise({ keyword: val }).then(({ data }) => {
        this.listData = data
      })
    },
    searchChange(val) {
      const obj = this.listData.find(item => item.name === val)
      if (!obj) return

      qccEnterpriseDetail({ keyword: val }).then(({ data }) => {
        const { creditCode, startDate, registCapi, address, operName } = data
        this.ruleForm = {
          ...this.ruleForm,
          certNo: creditCode,
          establishDate: startDate ? startDate.split('T')[0] : '',
          registerCapital: registCapi ? registCapi.split('万')[0] : '',
          registerAddress: address || '',
          legalPerson: operName || ''
        }
        window.$bus.$emit('sendLegalName', operName)
      })
    },
    async validate(type) {
      const businessLicenseFiles = this.$refs.businessLicense.getFileLists
      var params = {
        ...this.ruleForm,
        businessLicense: businessLicenseFiles.length ? { id: businessLicenseFiles.map(item => item.id)[0] } : null
      }
      delete params.certificationStatus
      return new Promise((resolve, reject) => {
        if (type === 'submit') {
          this.$refs.ruleFormRef.validate(valid => {
            if (valid) {
              if (!businessLicenseFiles.length) {
                this.$message.warning('请上传营业执照扫描件')
                return
              }
              return resolve(params)
            } else {
              reject()
              return false
            }
          })
        } else {
          resolve(params)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .basic-info {
    padding: 10px 20px;
  }
</style>
