<template>
  <div class="company-edit-container">
    <!-- 顶部返回 -->
    <div class="page-header">
      <el-button link @click="handleBack">
        <el-icon><ArrowLeft /></el-icon>
        <span>返回</span>
      </el-button>
      <span class="page-title">完善企业信息</span>
    </div>

    <div class="form-content">
      <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
        <!-- 工商信息 -->
        <div class="section">
          <div class="section-title"><i class="title-bar"></i>工商信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="企业名称" prop="companyName">
                <el-input v-model="form.companyName" placeholder="请输入" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="统一社会信用代码" prop="creditCode">
                <el-input v-model="form.creditCode" placeholder="请输入" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="法人" prop="legalPerson">
                <el-input v-model="form.legalPerson" placeholder="请输入" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="注册资本" prop="registeredCapital">
                <el-input v-model="form.registeredCapital" placeholder="请输入" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="详细地址" prop="detailAddress">
                <el-input v-model="form.detailAddress" placeholder="请输入" maxlength="50" show-word-limit disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="经营范围" prop="businessScope">
                <el-input v-model="form.businessScope" type="textarea" :rows="3" placeholder="请输入" maxlength="300" show-word-limit disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 办公信息 -->
        <div class="section">
          <div class="section-title"><i class="title-bar"></i>办公信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="主要办公地址" prop="provincialCityCounty">
                <el-cascader
                  v-model="form.regionCodes"
                  :options="regionData as any"
                  placeholder="请选择省/市/区"
                  style="width: 100%"
                  @change="handleRegionChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="详细地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属行业" prop="industryCategoryId">
                <el-select v-model="form.industryCategoryId" placeholder="请选择" style="width: 100%">
                  <el-option v-for="item in industryList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业规模" prop="enterpriseScaleId">
                <el-select v-model="form.enterpriseScaleId" placeholder="请选择" style="width: 100%">
                  <el-option v-for="item in scaleList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系方式" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="网址" prop="website">
                <el-input v-model="form.website" placeholder="请输入" maxlength="50" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="营业执照" prop="businessLicense">
                <el-upload
                  class="upload-box"
                  :action="action"
                  :show-file-list="false"
                  :on-success="handleBusinessLicenseSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <div v-if="form.businessLicense" class="upload-preview">
                    <el-image :src="form.businessLicense" fit="cover" />
                  </div>
                  <div v-else class="upload-placeholder">
                    <el-icon :size="24"><Plus /></el-icon>
                    <span>上传</span>
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="法人身份证" prop="legalPersonCardUrl">
                <el-upload
                  class="upload-box"
                  :action="action"
                  :show-file-list="false"
                  :on-success="handleLegalPersonCardUrlSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <div v-if="form.legalPersonCardUrl" class="upload-preview">
                    <el-image :src="form.legalPersonCardUrl" fit="cover" />
                  </div>
                  <div v-else class="upload-placeholder">
                    <el-icon :size="24"><Plus /></el-icon>
                    <span>上传</span>
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <!-- 底部按钮 -->
      <div class="form-footer">
        <el-button type="danger" @click="handleSave">保存</el-button>
        <el-button @click="handleBack">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ArrowLeft, Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { getEnterpriseInfo, updateEnterpriseInfo, getIndustryCategoryList, getEnterpriseScaleList } from '@/api/pc/enterprise';
const action = import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload';
import { regionData } from 'element-china-area-data';
import type { UploadProps } from 'element-plus';
const router = useRouter();
const formRef = ref();

const form = reactive({
  companyName: '',
  creditCode: '',
  legalPerson: '',
  registeredCapital: '',
  detailAddress: '',
  businessScope: '',
  provincialCityCounty: '',
  regionCodes: [],
  regProvincialNo: '',
  regCityNo: '',
  regCountyNo: '',
  address: '',
  industryCategoryId: '',
  enterpriseScaleId: '',
  phone: '',
  email: '',
  website: '',
  businessLicense: '',
  legalPersonCardUrl: ''
});

// 行业列表
const industryList = ref([]);
// 企业规模列表
const scaleList = ref([]);

const rules = {
  companyName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  creditCode: [{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }]
};

// 加载行业分类列表
const loadIndustryList = async () => {
  try {
    const res = await getIndustryCategoryList();
    if (res.code === 200 && res.rows) {
      industryList.value = res.rows.map((item: any) => ({
        label: item.industryCategoryName,
        value: item.id
      }));
    }
  } catch (error) {
    console.error('获取行业分类失败:', error);
  }
};

// 加载企业规模列表
const loadScaleList = async () => {
  try {
    const res = await getEnterpriseScaleList();
    if (res.code === 200 && res.rows) {
      scaleList.value = res.rows.map((item: any) => ({
        label: item.enterpriseScaleName,
        value: item.id
      }));
    }
  } catch (error) {
    console.error('获取企业规模失败:', error);
  }
};

//上传成功
const handleBusinessLicenseSuccess = (res: any) => {
  if (res.code == 200) {
    form.businessLicense = res.data.url;
  } else {
    ElMessage({
      message: res.msg,
      type: 'warning'
    });
  }
  console.log(res);
};

//上传成功
const handleLegalPersonCardUrlSuccess = (res: any) => {
  if (res.code == 200) {
    form.legalPersonCardUrl = res.data.url;
  } else {
    ElMessage({
      message: res.msg,
      type: 'warning'
    });
  }
  console.log(res);
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('不能大于2MB!');
    return false;
  }
  return true;
};

// 加载企业信息
const loadEnterpriseInfo = async () => {
  try {
    const res = await getEnterpriseInfo();
    if (res.code === 200 && res.data) {
      const data = res.data;
      const businessInfo = data.customerBusinessInfoVo || {};

      form.companyName = data.customerName || data.businessCustomerName || '';
      form.creditCode = businessInfo.socialCreditCode || '';
      form.legalPerson = businessInfo.legalPersonName || '';
      form.registeredCapital = businessInfo.registeredCapital || '';
      form.detailAddress = businessInfo.businessAddress || data.address || '';
      form.businessScope = businessInfo.bussinessRange || '';
      form.address = data.address || '';
      form.provincialCityCounty = data.provincialCityCounty || '';
      form.industryCategoryId = data.industryCategoryId || '';
      form.enterpriseScaleId = data.enterpriseScaleId || '';
      form.regionCodes = [data.regProvincialNo, data.regCityNo, data.regCountyNo];
      form.phone = data.landline || '';
      form.email = businessInfo.email || data.fax || '';
      form.website = data.url || '';
      form.businessLicense = businessInfo.businessLicense || '';
      form.legalPersonCardUrl = businessInfo.legalPersonCardUrl || '';

      // 调试映射后的表单数据
      console.log('映射后的detailAddress:', form.detailAddress);
    }
  } catch (error) {
    console.error('加载企业信息失败:', error);
    ElMessage.error('加载企业信息失败');
  }
};

// 处理地区选择变化
const handleRegionChange = (value: string[]) => {
  if (value && value.length === 3) {
    // 根据选中的代码查找对应的名称

    // 根据编码获取名称
    const names: string[] = [];
    if (value[0]) {
      const province = regionData.find((item: any) => item.value === value[0]);
      if (province) {
        names.push(province.label);

        if (value[1] && province.children) {
          const city = province.children.find((item: any) => item.value === value[1]);
          if (city) {
            names.push(city.label);

            if (value[2] && city.children) {
              const county = city.children.find((item: any) => item.value === value[2]);
              if (county) {
                names.push(county.label);
              }
            }
          }
        }
      }
    }

    // 将省市区名称用斜杠连接
    form.provincialCityCounty = names.join('/');
  }
};

onMounted(() => {
  loadIndustryList();
  loadScaleList();
  loadEnterpriseInfo();
});

const handleBack = () => {
  router.push('/enterprise/companyInfo');
};

const handleUpload = (file: any, field: string) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    (form as any)[field] = e.target?.result as string;
  };
  reader.readAsDataURL(file.raw);
};

const handleSave = async () => {
  const valid = await formRef.value?.validate();
  if (!valid) return;

  try {
    // 如果选择了省市区，发送代码
    if (form.regionCodes && form.regionCodes.length === 3) {
      form.regProvincialNo = form.regionCodes[0];
      form.regCityNo = form.regionCodes[1];
      form.regCountyNo = form.regionCodes[2];
      form.provincialCityCounty = form.provincialCityCounty;
    }
    await updateEnterpriseInfo(form as any);
    ElMessage.success('保存成功');
    handleBack();
  } catch (error) {
    ElMessage.error('保存失败');
  }
};
</script>

<style scoped lang="scss">
.company-edit-container {
  background: #f5f5f5;
  min-height: 100%;
  width: 100%;
}

.page-header {
  background: #fff;
  padding: 15px 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #eee;

  .page-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }
}

.form-content {
  padding: 20px;
}

.section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 15px;

  .section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

.title-bar {
  display: inline-block;
  width: 3px;
  height: 16px;
  background: #e60012;
  border-radius: 2px;
}

.upload-box {
  :deep(.el-upload) {
    width: 100px;
    height: 100px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;

    &:hover {
      border-color: #e60012;
    }
  }

  .upload-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #999;
    font-size: 12px;
    gap: 5px;
  }

  .upload-preview {
    width: 100%;
    height: 100%;

    .el-image {
      width: 100%;
      height: 100%;
    }
  }
}

.form-footer {
  text-align: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}
</style>
