<!--
 Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

 https://www.mall4j.com/

 未经允许，不可做商业用途！

 版权所有，侵权必究！
-->
<template>
  <div class="Mall4j component-business-info">
    <!-- 工商信息 -->
    <el-form
      ref="companyInfoFormRef"
      :model="companyInfoForm"
      :rules="companyInfoRule"
      label-width="140px"
      class="business-info"
      :disabled="auditStatus===0&&paySettlementType===1&&companyInfoProcessStatus===3"
      @submit.prevent
    >
      <el-row>
        <el-col
          :xs="24"
          :sm="24"
          :md="24"
          :lg="12"
          :xl="12"
        >
          <el-form-item
            :label="$t('multishop.shopInformation.creditCode')"
            prop="creditCode"
          >
            <el-input
              v-model.trim="companyInfoForm.creditCode"
              :disabled="paySettlementType===1&&companyInfoProcessStatus===2"
              maxlength="20"
              style="max-width:380px"
              :placeholder="$t('multishop.shopInformation.creditCodeTips')"
            />
          </el-form-item>
          <el-form-item
            :label="$t('multishop.shopInformation.firmName')"
            prop="firmName"
          >
            <el-input
              v-model="companyInfoForm.firmName"
              maxlength="50"
              style="max-width:380px"
              :placeholder="$t('multishop.shopInformation.firmNameTips')"
            />
          </el-form-item>
          <el-form-item
            :label="$t('multishop.shopInformation.residence')"
            prop="residence"
          >
            <el-input
              v-model="companyInfoForm.residence"
              maxlength="50"
              style="max-width:380px"
              :placeholder="$t('multishop.shopInformation.residenceTips')"
            />
          </el-form-item>
          <el-form-item
            :label="$t('multishop.shopInformation.representative')"
            prop="representative"
          >
            <el-input
              v-model="companyInfoForm.representative"
              maxlength="20"
              style="max-width:380px"
              :placeholder="$t('multishop.shopInformation.representativeTips')"
              prop="representative"
            />
          </el-form-item>
          <el-form-item
            v-if="paySettlementType===1"
            label="法人身份证"
            prop="legalIds"
          >
            <el-input
              v-model="companyInfoForm.legalIds"
              maxlength="18"
              style="max-width:380px"
              placeholder="请输入法人身份证号"
            />
          </el-form-item>
          <el-form-item
            v-if="paySettlementType===1"
            label="法人手机号"
            prop="legalPhone"
          >
            <el-input
              v-model="companyInfoForm.legalPhone"
              maxlength="11"
              placeholder="输入法人手机号"
              style="max-width:380px"
              @input="(val)=>{companyInfoForm.legalPhone=val.replace(/[^\d|*]/g,'')}"
            />
          </el-form-item>
          <el-form-item :label="$t('multishop.shopInformation.capital')">
            <el-input
              v-model="companyInfoForm.capital"
              prop="capital"
              style="max-width:380px"
              @input="changeNum"
              @keydown="channelInputLimit"
            >
              <template #append>
                <el-button>{{ $t('multishop.shopInformation.priceUnit') }}</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item
            :label="$t('multishop.shopInformation.foundTime')"
            prop="foundTime"
          >
            <el-date-picker
              v-model="companyInfoForm.foundTime"
              style="max-width:380px"
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('multishop.shopInformation.foundTimeTips')"
              :disabled-date="pickerOptions"
            />
          </el-form-item>
          <el-form-item
            :label="$t('multishop.shopInformation.businessTerm')"
            prop="startTime"
          >
            <div style="display: flex">
              <el-date-picker
                v-model="companyInfoForm.startTime"
                style="width:100%;max-width:177px"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                :placeholder="$t('date.start')"
                :clearable="false"
              />
              <span style="margin: 0 10px">-</span>
              <span class="end-time">
                <el-date-picker
                  ref="endTimeRef"
                  v-model="companyInfoForm.endTime"
                  style="width:100%;max-width:177px"
                  type="date"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :placeholder="endTimeFlag && !companyInfoForm.endTime ? '' : $t('date.end')"
                  clearable
                  @change="endTimeFlag = false"
                  @focus="endTimeFlag = false"
                />
                <span
                  v-if="endTimeFlag && !companyInfoForm.endTime"
                  class="text"
                  @click="focusEndTime"
                >
                  {{ $t('multishop.shopInformation.noFixedTerm') }}
                </span>
              </span>
            </div>
          </el-form-item>
          <el-form-item
            :label="$t('multishop.shopInformation.businessScope')"
            prop="businessScope"
          >
            <el-input
              v-model="companyInfoForm.businessScope"
              type="textarea"
              resize="none"
              :rows="4"
              :placeholder="$t('multishop.shopInformation.businessScopeTips')"
              maxlength="500"
              style="max-width:380px"
            />
          </el-form-item>
        </el-col>
        <el-col
          :xs="24"
          :sm="24"
          :md="24"
          :lg="12"
          :xl="12"
        >
          <el-form-item
            :label="$t('multishop.shopInformation.businessLicense')"
            prop="businessLicense"
          >
            <div class="business-license-box">
              <div class="license-content">
                <imgs-upload
                  v-model="companyInfoForm.businessLicense"
                  :limit="1"
                />
                <div class="example-box">
                  <img
                    src="@/assets/example-img/Business-license.png"
                    alt
                  >
                  <div class="tips">
                    {{ $t('multishop.shopInformation.example') }}
                  </div>
                </div>
              </div>
              <div class="upload-tips">
                {{ $t('multishop.shopInformation.uploadTips') }}
              </div>
            </div>
          </el-form-item>
          <div class="id-box">
            <div class="upload-content">
              <div class="upload-img">
                <el-form-item
                  class="idcard"
                  :label="$t('multishop.shopInformation.identityCardFront')"
                  prop="identityCardFront"
                >
                  <imgs-upload
                    v-model="companyInfoForm.identityCardFront"
                    :limit="1"
                  />
                </el-form-item>
                <el-form-item
                  class="idcard"
                  label-width="0"
                  prop="identityCardLater"
                >
                  <imgs-upload
                    v-model="companyInfoForm.identityCardLater"
                    :limit="1"
                  />
                </el-form-item>
              </div>
              <div class="upload-example">
                <div class="example-box">
                  <img
                    src="@/assets/example-img/idcard1.png"
                    alt
                  >
                  <div class="tips">
                    {{ $t('multishop.shopInformation.portraitFace') }}
                  </div>
                </div>
                <div class="example-box">
                  <img
                    src="@/assets/example-img/idcard2.png"
                    alt
                  >
                  <div class="tips">
                    {{ $t('multishop.shopInformation.national') }}
                  </div>
                </div>
              </div>
              <div
                class="upload-tips"
                style="margin-bottom:15px"
              >
                {{ $t('multishop.shopInformation.identityCardTips') }}
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer">
      <div class="foot-box">
        <div
          v-if="paySettlementType!==1"
          v-permission="['shop:shopCompany:save']"
          class="btn prev-btn"
          style="margin-left:143px"
          @click="validationCompanyInfoForm"
        >
          {{ $t('multishop.shopInformation.saveInformation') }}
        </div>
        <div
          v-if="paySettlementType===1 && !(auditStatus===0&&companyInfoProcessStatus===3)"
          class="btn prev-btn"
          style="margin-left:143px"
          @click="validationCompanyInfoForm"
        >
          确认提交
        </div>
      </div>
    </div>
    <!-- /工商信息 -->
  </div>
</template>

<script setup>
import * as api from '@/api/multishop/shop-process.js'
import { validNoEmptySpace, checkIDCard } from '@/utils/validate.js'
import moment from 'moment'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['setActiveName', 'getmodifyInformation', 'closeBrowse', 'closeBrowse'])

const allinPayStyore = useAllinpayStore()
const paySettlementType = ref(allinPayStyore.paySettlementType)
// 店铺工商信息
const companyInfoForm = ref({
  creditCode: '',
  firmName: '',
  residence: '',
  representative: '',
  capital: '',
  foundTime: '',
  startTime: '',
  endTime: '',
  businessScope: '',
  businessLicense: '',
  identityCardFront: '',
  identityCardLater: '',
  legalPhone: '',
  legalIds: ''
})

const endTimeFlag = ref(true)

// 成立日期：今日之前可选
const pickerOptions = (time) => {
  const date = moment().add(0, 'days').startOf('days')
  return (
    time.getTime() >= date.valueOf()
  )
}

// eslint-disable-next-line no-unused-vars
const validbusinessScope = (rule, value, callback) => {
  if (!value || !value.trim()) {
    companyInfoForm.value.businessScope = ''
    callback(new Error($t('multishop.shopInformation.businessScopeEmpty')))
  } else {
    callback()
  }
}

// 纯空格校验
// eslint-disable-next-line no-unused-vars
const validEmptySpace = (rule, value, callback) => {
  if (validNoEmptySpace(value)) {
    callback(new Error($t('multishop.shopInformation.EmptyTips')))
  } else {
    callback()
  }
}

// eslint-disable-next-line no-unused-vars
const validIDCard = (rule, value, callback) => {
  if (!value || !checkIDCard(value)) {
    callback(new Error('请输入正确的法人身份证'))
  } else {
    callback()
  }
}

// eslint-disable-next-line no-unused-vars
const validMobile = (rule, value, callback) => {
  if (!isStarMobile(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const companyInfoRule = computed(() => {
  return {
    creditCode: [
      { required: true, message: $t('multishop.shopInformation.creditCodeEmpty'), trigger: 'blur' }
    ],
    firmName: [
      { required: true, message: $t('multishop.shopInformation.firmNameEmpty'), trigger: 'blur' }
    ],
    residence: [
      // 住所，非必填，校验纯空格
      { validator: validEmptySpace, trigger: 'blur' }
    ],
    representative: [
      { required: true, message: $t('multishop.shopInformation.representativeEmpty'), trigger: 'blur' }
    ],
    legalIds: [
      { required: true, message: '法人身份证不能为空', trigger: 'blur' },
      { validator: validIDCard, trigger: 'blur' }
    ],
    legalPhone: [
      { required: true, message: '法人手机号不能为空', trigger: 'blur' },
      { validator: validMobile, trigger: 'blur' }
    ],
    businessScope: [
      { required: true, message: $t('multishop.shopInformation.businessScopeEmpty'), trigger: 'blur' },
      { validator: validbusinessScope, trigger: 'blur' }
    ],
    startTime: [
      { required: true, message: $t('multishop.shopInformation.startTimeTip'), trigger: 'change' }
    ],
    businessLicense: [
      { required: true, message: $t('multishop.shopInformation.businessLicenseTips'), trigger: 'change' }
    ],
    identityCardFront: [
      { required: true, message: $t('multishop.shopInformation.identityCardFrontTips'), trigger: 'change' }
    ],
    identityCardLater: [
      { required: true, message: $t('multishop.shopInformation.identityCardLaterTips'), trigger: 'change' }
    ]
  }
})

const companyInfoProcessStatus = computed(() => {
  return allinPayStyore.companyInfoProcessStatus
})

const auditStatus = computed(() => {
  return allinPayStyore.auditStatus
})

onMounted(() => {
  queryShopBusinessInfo()
})

/**
 * 查询工商信息
 */
const queryShopBusinessInfo = () => {
  api.getCompanyInfo().then(data => {
    data && (companyInfoForm.value = data)
    endTimeFlag.value = true
  })
}
const endTimeRef = ref(null)
const focusEndTime = () => {
  endTimeRef.value?.focus()
}
/**
 * 注册资本输入框限制长度
 */
const changeNum = () => {
  if (companyInfoForm.value.capital < 1) {
    companyInfoForm.value.capital = ''
  }
  if (companyInfoForm.value.capital.length > 8) {
    companyInfoForm.value.capital = companyInfoForm.value.capital.slice(0, 8)
  }
}
const channelInputLimit = (e) => {
  const key = e.key
  // 不允许输入'-'
  if (key === '-' || key === '+') {
    e.returnValue = false
    return false
  }
  return true
}
/**
 * 验证工商信息
 */
const companyInfoFormRef = ref(null)
const validationCompanyInfoForm = () => {
  // 工商信息
  companyInfoFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    updateCompanyInfo()
  })
}
/**
 * 申请变更工商信息
 */
const updateCompanyInfo = Debounce(() => {
  api.applyChangeCompanyInfo(companyInfoForm.value).then(() => {
    ElMessage({
      message: $t('multishop.shopInformation.updataCompanyTips'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        if (paySettlementType.value === 1 && (companyInfoProcessStatus === 1 || companyInfoProcessStatus === 3 || companyInfoProcessStatus === 0)) {
          emit('setActiveName', '4')
          // 重新更新工商信息状态
          emit('getmodifyInformation')
          return
        }
        emit('closeBrowse')
      }
    })
  }).catch(() => {
    if (paySettlementType.value !== 1) {
      emit('closeBrowse')
    }
  })
}, 1500)

// const handleInputValue = () => {
//   if (companyInfoForm.value.capital >= 99999999.99) {
//     companyInfoForm.value.capital = 99999999.99
//   }
// }
</script>

<style lang="scss" scoped>
@use "index";
</style>
