<template>
  <div class="tab-content">
    <div class="info-section">
      <div class="section-title-row">
        <div class="section-title-left">
          <span class="section-title-text">企业基本信息</span>
          <span class="section-title-divider">/</span>
          <span class="supplier-no">供应商编码：{{ localDetailData.supplierNo }}</span>
        </div>
        <el-button v-if="!isViewMode" type="primary" icon="Document" @click="onSaveClick">保存</el-button>
      </div>

      <el-form :model="localDetailData" label-width="120px" class="detail-form">
        <el-row :gutter="12" class="form-row">
          <el-col :span="8">
            <el-form-item label="所属公司：" required>
              <el-select v-model="localDetailData.ownedCompany" placeholder="请选择" clearable filterable style="width: 100%" :disabled="isViewMode">
                <el-option v-for="company in companyOptions" :key="company.id" :label="company.companyName" :value="company.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商名称：" required>
              <el-input v-model="localDetailData.enterpriseName" placeholder="请输入企业名称" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工商名称：" required>
              <el-input
                v-model="localDetailData.businessName"
                :disabled="isViewMode"
                placeholder="请输入工商名称"
                @blur="!isBasicInfoSaved && !isViewMode && emit('getBusinessInfo')"
                @keyup.enter="!isBasicInfoSaved && !isViewMode && emit('getBusinessInfo')"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12" class="form-row">
          <el-col :span="8">
            <el-form-item label="企业简称：" required>
              <el-input v-model="localDetailData.shortName" placeholder="请输入企业简称" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商等级：" required>
              <el-select
                v-model="localDetailData.cooperateLevel"
                placeholder="请选择"
                clearable
                filterable
                style="width: 100%"
                :disabled="isViewMode"
              >
                <el-option
                  v-for="level in supplierLevelOptions"
                  :key="level.id"
                  :label="`${level.supplierLevelNo} , ${level.supplierLevelName}`"
                  :value="String(level.id)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="企业规模：" required>
              <el-select
                v-model="localDetailData.membershipSize"
                placeholder="请选择"
                clearable
                filterable
                style="width: 100%"
                :disabled="isViewMode"
              >
                <el-option
                  v-for="scale in enterpriseScaleOptions"
                  :key="scale.id"
                  :label="`${scale.enterpriseScaleCode} , ${scale.enterpriseScaleName}`"
                  :value="scale.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12" class="form-row">
          <!-- <el-col :span="8">
            <el-form-item label="行业类别：" required>
              <el-select v-model="detailData.industrCategory" placeholder="请选择" clearable filterable style="width: 100%" :disabled="isViewMode">
                <el-option
                  v-for="industry in industryCategoryOptions"
                  :key="industry.id"
                  :label="industry.industryCategoryName"
                  :value="industry.id"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="供应商类型：" required>
              <el-select v-model="localDetailData.supplierType" placeholder="请选择" clearable filterable style="width: 100%" :disabled="isViewMode">
                <el-option
                  v-for="type in supplierTypeOptions"
                  :key="type.id"
                  :label="`${type.supplierTypeNo} , ${type.supplierTypeName}`"
                  :value="type.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="固定电话：" :error="fixedPhoneError">
              <el-input
                v-model="localDetailData.fixedPhone"
                placeholder="请输入固定电话"
                type="tel"
                @blur="onFixedPhoneBlur"
                :disabled="isViewMode"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12" class="form-row">
          <el-col :span="8">
            <el-form-item label="传真：">
              <el-input v-model="localDetailData.fax" placeholder="请输入传真" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="企业邮箱：" :error="mailboxError">
              <el-input v-model="localDetailData.mailbox" placeholder="请输入企业邮箱" @blur="onMailboxBlur" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="开始时间：">
              <el-date-picker
                v-model="localDetailData.validityFromDate"
                type="date"
                placeholder="请选择"
                style="width: 100%"
                :disabled="isViewMode"
              />
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row :gutter="12" class="form-row">
          <!-- <el-col :span="8">
            <el-form-item label="结束时间：">
              <el-date-picker v-model="localDetailData.validityToDate" type="date" placeholder="请选择" style="width: 100%" :disabled="isViewMode" />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="邮政编码：" :error="postCodeError">
              <el-input v-model="localDetailData.postCode" placeholder="请输入邮政编码" @blur="onPostCodeBlur" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="网址：">
              <el-input v-model="localDetailData.url" placeholder="请输入网址" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12" class="form-row">
          <el-col :span="8">
            <el-form-item label="详细地址：" required>
              <el-cascader
                v-model="selectedOfficeRegionProxy"
                :options="regionOptions"
                placeholder="请选择省市区"
                clearable
                filterable
                style="width: 100%"
                @change="onOfficeRegionChange"
                :disabled="isViewMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label=" " label-width="0">
              <el-input v-model="localDetailData.officeAddress" placeholder="请输入详细地址" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="info-section">
      <div class="section-title">工商信息</div>

      <el-row :gutter="12" class="form-row">
        <el-col :span="8">
          <div class="form-item">
            <span class="label">企业工商名称：</span>
            <span class="value">{{ businessInfo.businessName || localDetailData.businessName || '' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="form-item">
            <span class="label">登记机关：</span>
            <span class="value">{{ businessInfo.registrationAuthority || '' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="form-item">
            <span class="label">成立日期：</span>
            <span class="value">{{ formatDate(businessInfo.establishmentDate) || '' }}</span>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="12" class="form-row">
        <el-col :span="8">
          <div class="form-item">
            <span class="label">登记状态：</span>
            <span class="value">{{ businessInfo.registrationStatus || '' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="form-item">
            <span class="label">实缴资本：</span>
            <span class="value">{{ businessInfo.paidInCapital || '' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="form-item">
            <span class="label">社会信用代码：</span>
            <span class="value">{{ businessInfo.socialCreditCode || localDetailData.socialCreditCode || '' }}</span>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="12" class="form-row">
        <el-col :span="8">
          <div class="form-item">
            <span class="label">法人姓名：</span>
            <span class="value">{{ businessInfo.legalPersonName || '' }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="form-item">
            <span class="label">注册资本：</span>
            <span class="value">{{ businessInfo.registeredCapital || '' }}</span>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="12" class="form-row">
        <el-col :span="24">
          <div class="form-item">
            <span class="label">工商地址：</span>
            <el-input v-model="businessInfo.businessAddress" placeholder="工商地址" style="width: 70%" :disabled="true" />
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="12" class="form-row">
        <!-- <el-col :span="8">
          <div class="form-item">
            <span class="label">营业执照：</span>
            <ImageUpload
              v-model="localDetailData.businessLicense"
              :limit="1"
              :disabled="isViewMode"
              :file-size="5"
              :file-type="['png', 'jpg', 'jpeg']"
              :is-show-tip="false"
              value-type="url"
            />
          </div>
        </el-col>
        <el-col :span="8">
          <div class="form-item">
            <span class="label">法人身份证照片：</span>
            <ImageUpload
              v-model="localDetailData.personImage"
              :limit="1"
              :disabled="isViewMode"
              :file-size="5"
              :file-type="['png', 'jpg', 'jpeg']"
              :is-show-tip="false"
              value-type="url"
            />
          </div>
        </el-col> -->
        <el-col :span="8" />
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import ImageUpload from '@/components/ImageUpload/index.vue';
import { ElMessage } from 'element-plus';

const props = defineProps<{
  detailData: any;
  companyOptions: any[];
  enterpriseScaleOptions: any[];
  industryCategoryOptions: any[];
  supplierLevelOptions: any[];
  supplierTypeOptions: any[];
  isAddMode: boolean;
  isViewMode: boolean;
  isBasicInfoSaved: boolean;
  businessInfo: any;
  businessAddress: any;
  businessInfoLoading: boolean;
  regionOptions: any[];
  selectedOfficeRegion: string[];
  paymentInfoList: any[];
  formatDate: (date: any) => string;
}>();

const emit = defineEmits<{
  (e: 'save'): void;
  (e: 'getBusinessInfo'): void;
  (e: 'officeRegionChange', value: string[]): void;
  (e: 'update:selectedOfficeRegion', value: string[]): void;
  (e: 'addPayment'): void;
  (e: 'viewPayment', row: any): void;
  (e: 'editPayment', row: any): void;
  (e: 'update:detailData', value: any): void;
}>();

const localDetailData = computed({
  get: () => props.detailData,
  set: (value) => emit('update:detailData', value)
});

const selectedOfficeRegionProxy = computed({
  get: () => props.selectedOfficeRegion,
  set: (value) => emit('update:selectedOfficeRegion', value)
});

const onOfficeRegionChange = (val: unknown) => {
  emit('officeRegionChange', (val || []) as string[]);
};

const fixedPhoneError = ref('');
const fixedPhoneReg = /^(\d{3,4}-?)?\d{7,8}(-\d{1,6})?$/;
const postCodeError = ref('');
const mailboxError = ref('');
const mailboxReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

const validateFixedPhone = (val: unknown) => {
  const v = String(val ?? '').trim();
  if (!v) return '';
  if (!fixedPhoneReg.test(v)) return '请输入正确的固定电话';
  return '';
};

const validatePostCode = (val: unknown) => {
  const v = String(val ?? '').trim();
  if (!v) return '';
  if (!/^\d+$/.test(v)) return '邮政编码只能输入数字';
  return '';
};

const validateMailbox = (val: unknown) => {
  const v = String(val ?? '').trim();
  if (!v) return '';
  if (!mailboxReg.test(v)) return '请输入正确的邮箱格式';
  return '';
};

const validateFax = (val: unknown) => {
  const v = String(val ?? '').trim();
  if (!v) return '';
  if (!/^\d+$/.test(v)) return '传真只能输入数字';
  return '';
};

watch(
  () => props.detailData?.fixedPhone,
  (v) => {
    fixedPhoneError.value = validateFixedPhone(v);
  },
  { immediate: true }
);

watch(
  () => props.detailData?.postCode,
  (v) => {
    postCodeError.value = validatePostCode(v);
  },
  { immediate: true }
);

watch(
  () => props.detailData?.mailbox,
  (v) => {
    mailboxError.value = validateMailbox(v);
  },
  { immediate: true }
);

const onFixedPhoneBlur = () => {
  fixedPhoneError.value = validateFixedPhone(props.detailData?.fixedPhone);
};

const onPostCodeBlur = () => {
  postCodeError.value = validatePostCode(props.detailData?.postCode);
};

const onFaxBlur = () => {
  const err = validateFax(props.detailData?.fax);
  if (err) ElMessage.warning(err);
};

const onMailboxBlur = () => {
  mailboxError.value = validateMailbox(props.detailData?.mailbox);
};

const onSaveClick = () => {
  const err = validateFixedPhone(props.detailData?.fixedPhone);
  fixedPhoneError.value = err;
  if (err) {
    ElMessage.warning(err);
    return;
  }

  const postCodeErr = validatePostCode(props.detailData?.postCode);
  postCodeError.value = postCodeErr;
  if (postCodeErr) {
    ElMessage.warning(postCodeErr);
    return;
  }

  const faxErr = validateFax(props.detailData?.fax);
  if (faxErr) {
    ElMessage.warning(faxErr);
    return;
  }

  const mailboxErr = validateMailbox(props.detailData?.mailbox);
  mailboxError.value = mailboxErr;
  if (mailboxErr) {
    ElMessage.warning(mailboxErr);
    return;
  }

  emit('save');
};
</script>

<style scoped>
.tab-content {
  --el-component-size: 24px;
  padding: 16px;
}

.detail-form :deep(.el-form-item__label) {
  white-space: nowrap;
}

.detail-form :deep(.form-row) {
  margin-bottom: 2px;
}

.detail-form :deep(.el-form-item) {
  margin-bottom: 8px;
}

.tab-content :deep(.form-row) {
  margin-bottom: 2px;
}

.tab-content :deep(.el-form-item) {
  margin-bottom: 8px;
}

.tab-content :deep(.info-section) {
  margin-bottom: 20px;
}

.tab-content :deep(.section-title),
.tab-content :deep(.section-title-row) {
  margin-bottom: 12px;
  padding-bottom: 8px;
}

.tab-content :deep(.section-title-text) {
  font-size: 14px;
}

.tab-content :deep(.supplier-no) {
  font-size: 13px;
}

.tab-content :deep(.el-form-item__label) {
  font-size: 13px;
  height: var(--el-component-size);
  line-height: var(--el-component-size);
  padding-top: 0;
  padding-bottom: 0;
}

.tab-content :deep(.form-item) {
  line-height: 24px;
  font-size: 13px;
}

.detail-form :deep(.el-input),
.detail-form :deep(.el-select),
.detail-form :deep(.el-date-editor),
.detail-form :deep(.el-cascader) {
  width: 100%;
}

.detail-form :deep(.el-input__wrapper),
.detail-form :deep(.el-select__wrapper),
.detail-form :deep(.el-date-editor),
.detail-form :deep(.el-cascader) {
  min-height: var(--el-component-size);
}

.detail-form :deep(.el-input__inner) {
  height: var(--el-component-size);
  line-height: var(--el-component-size);
}

.detail-form :deep(.el-form-item__content) {
  align-items: center;
  min-height: var(--el-component-size);
}

.detail-form :deep(.el-input__wrapper),
.detail-form :deep(.el-select__wrapper),
.detail-form :deep(.el-date-editor),
.detail-form :deep(.el-cascader) {
  height: var(--el-component-size);
  align-items: center;
  padding-top: 0;
  padding-bottom: 0;
}

.detail-form :deep(.el-select__selected-item),
.detail-form :deep(.el-select__input),
.detail-form :deep(.el-range-input) {
  line-height: var(--el-component-size);
}

:deep(.component-upload-image .el-upload--picture-card),
:deep(.component-upload-image .el-upload-list--picture-card .el-upload-list__item) {
  width: 64px;
  height: 64px;
}

:deep(.component-upload-image .el-upload-list--picture-card .el-upload-list__item-thumbnail) {
  width: 64px;
  height: 64px;
}
</style>
