<template>
  <div class="app-container">
    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="6">
        <el-card class="statistics-card" @click="filterByStatus('all')">
          <div class="statistics-content">
            <div class="statistics-icon total">
              <el-icon><OfficeBuilding /></el-icon>
            </div>
            <div class="statistics-info">
              <div class="statistics-number">{{ statistics.total }}</div>
              <div class="statistics-label">企业总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card" @click="filterByStatus('certified')">
          <div class="statistics-content">
            <div class="statistics-icon certified">
              <el-icon><Medal /></el-icon>
            </div>
            <div class="statistics-info">
              <div class="statistics-number">{{ statistics.certified }}</div>
              <div class="statistics-label">已认证企业</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card" @click="filterByStatus('active')">
          <div class="statistics-content">
            <div class="statistics-icon active">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="statistics-info">
              <div class="statistics-number">{{ statistics.active }}</div>
              <div class="statistics-label">正常企业</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="statistics-card" @click="filterByStatus('inactive')">
          <div class="statistics-content">
            <div class="statistics-icon warning">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="statistics-info">
              <div class="statistics-number">{{ statistics.inactive }}</div>
              <div class="statistics-label">异常企业</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索表单 -->
    <el-card class="search-card mb20">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input
                  v-model="queryParams.enterpriseName"
                  placeholder="请输入企业名称"
                  clearable
                  @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="信用代码" prop="creditCode">
              <el-input
                  v-model="queryParams.creditCode"
                  placeholder="请输入统一社会信用代码"
                  clearable
                  @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="法定代表人" prop="legalPerson">
              <el-input
                  v-model="queryParams.legalPerson"
                  placeholder="请输入法定代表人"
                  clearable
                  @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业状态" prop="enterpriseStatus">
              <el-select v-model="queryParams.enterpriseStatus" placeholder="请选择企业状态" clearable style="width: 180px">
                <el-option
                    v-for="dict in sys_enterprise_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="认证状态" prop="certStatus">
              <el-select v-model="queryParams.certStatus" placeholder="请选择认证状态" clearable style="width: 180px">
                <el-option
                    v-for="dict in sys_cert_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="6">
            <el-form-item label="成立时间" prop="establishDateRange">
              <el-date-picker
                  v-model="queryParams.establishDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  style="width: 180px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="注册资本" prop="capitalRange">
              <el-input-number
                  v-model="queryParams.minCapital"
                  placeholder="最小值"
                  :min="0"
                  style="width: 85px"
              />
              <span style="margin: 0 5px">-</span>
              <el-input-number
                  v-model="queryParams.maxCapital"
                  placeholder="最大值"
                  :min="0"
                  style="width: 85px"
              />
            </el-form-item>
          </el-col>-->
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:enterprise:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:enterprise:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:enterprise:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:enterprise:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['system:enterprise:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Refresh"
            @click="handleRefresh"
        >刷新</el-button>
      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table
        v-loading="loading"
        :data="enterpriseList"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        stripe
        border
        :default-sort="{prop: 'createTime', order: 'descending'}"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="企业名称" align="center" prop="enterpriseName" :show-overflow-tooltip="true" min-width="150" sortable="custom" />
      <el-table-column label="统一社会信用代码" align="center" prop="creditCode" min-width="180" />
      <el-table-column label="法定代表人" align="center" prop="legalPerson" width="100" />
      <el-table-column label="注册资本(万元)" align="center" prop="registeredCapital" width="120" sortable="custom">
        <template #default="scope">
          <span v-if="scope.row.registeredCapital" class="capital-amount">{{ formatNumber(scope.row.registeredCapital) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="成立日期" align="center" prop="establishDate" width="110" sortable="custom" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" width="120" />
      <el-table-column label="企业状态" align="center" prop="enterpriseStatus" width="100">
        <template #default="scope">
          <dict-tag :options="sys_enterprise_status" :value="scope.row.enterpriseStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="认证状态" align="center" prop="certStatus" width="100">
        <template #default="scope">
          <dict-tag :options="sys_cert_status" :value="scope.row.certStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" sortable="custom">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template #default="scope">
          <el-tooltip content="查看详情" placement="top">
            <el-button
                link
                type="primary"
                icon="View"
                @click="handleView(scope.row)"
                v-hasPermi="['system:enterprise:query']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:enterprise:edit']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="复制" placement="top">
            <el-button
                link
                type="success"
                icon="CopyDocument"
                @click="handleCopy(scope.row)"
                v-hasPermi="['system:enterprise:add']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
                link
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:enterprise:remove']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改企业信息对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body destroy-on-close>
      <el-form ref="enterpriseFormRef" :model="form" :rules="rules" label-width="140px">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基础信息 -->
          <el-tab-pane label="基础信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="企业名称" prop="enterpriseName">
                  <el-input v-model="form.enterpriseName" placeholder="请输入企业名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="统一社会信用代码" prop="creditCode">
                  <el-input
                      v-model="form.creditCode"
                      placeholder="请输入统一社会信用代码"
                      @blur="checkCreditCode"
                  />
                </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="请输入法定代表人" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="注册资本(万元)" prop="registeredCapital">
                  <el-input-number
                      v-model="form.registeredCapital"
                      :precision="2"
                      :min="0"
                      :max="999999999"
                      placeholder="请输入注册资本"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="成立日期" prop="establishDate">
                  <el-date-picker
                      v-model="form.establishDate"
                      type="date"
                      value-format="YYYY-MM-DD"
                      placeholder="请选择成立日期"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" placeholder="请输入邮箱" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="官网" prop="website">
                  <el-input v-model="form.website" placeholder="请输入官网地址" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="企业状态">
                  <el-radio-group v-model="form.enterpriseStatus">
                    <el-radio
                        v-for="dict in sys_enterprise_status"
                        :key="dict.value"
                        :label="dict.value"
                    >{{ dict.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="认证状态">
                  <el-radio-group v-model="form.certStatus">
                    <el-radio
                        v-for="dict in sys_cert_status"
                        :key="dict.value"
                        :label="dict.value"
                    >{{ dict.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 地址信息 -->
          <el-tab-pane label="地址信息" name="address">
            <el-row>
              <el-col :span="24">
                <el-form-item label="注册地址" prop="registeredAddress">
                  <el-input
                      v-model="form.registeredAddress"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入注册地址"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="办公地址" prop="officeAddress">
                  <el-input
                      v-model="form.officeAddress"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入办公地址"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item>
                  <el-checkbox v-model="sameAsRegistered" @change="copyRegisteredAddress">
                    办公地址与注册地址相同
                  </el-checkbox>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 经营信息 -->
          <el-tab-pane label="经营信息" name="business">
            <el-row>
              <el-col :span="24">
                <el-form-item label="经营范围" prop="businessScope">
                  <el-input
                      v-model="form.businessScope"
                      type="textarea"
                      :rows="5"
                      placeholder="请输入经营范围"
                      show-word-limit
                      maxlength="1000"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input
                      v-model="form.remark"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入备注信息"
                      show-word-limit
                      maxlength="500"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 企业信息详情对话框 -->
    <el-dialog title="企业信息详情" v-model="viewOpen" width="900px" append-to-body>
      <el-descriptions :column="2" border size="large">
        <el-descriptions-item label="企业名称" label-class-name="desc-label">
          <span class="desc-value">{{ viewForm.enterpriseName }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="统一社会信用代码" label-class-name="desc-label">
          <span class="desc-value">{{ viewForm.creditCode }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="法定代表人" label-class-name="desc-label">
          <span class="desc-value">{{ viewForm.legalPerson }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="注册资本" label-class-name="desc-label">
          <span class="desc-value">{{ formatNumber(viewForm.registeredCapital) }}万元</span>
        </el-descriptions-item>
        <el-descriptions-item label="成立日期" label-class-name="desc-label">
          <span class="desc-value">{{ viewForm.establishDate }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="联系电话" label-class-name="desc-label">
          <span class="desc-value">{{ viewForm.contactPhone }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="邮箱" label-class-name="desc-label">
          <span class="desc-value">{{ viewForm.email }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="官网" label-class-name="desc-label">
          <el-link :href="viewForm.website" target="_blank" type="primary" v-if="viewForm.website">
            {{ viewForm.website }}
          </el-link>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="企业状态" label-class-name="desc-label">
          <dict-tag :options="sys_enterprise_status" :value="viewForm.enterpriseStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="认证状态" label-class-name="desc-label">
          <dict-tag :options="sys_cert_status" :value="viewForm.certStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="注册地址" :span="2" label-class-name="desc-label">
          <span class="desc-value">{{ viewForm.registeredAddress }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="办公地址" :span="2" label-class-name="desc-label">
          <span class="desc-value">{{ viewForm.officeAddress }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="经营范围" :span="2" label-class-name="desc-label">
          <div class="business-scope">{{ viewForm.businessScope }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2" label-class-name="desc-label">
          <span class="desc-value">{{ viewForm.remark || '-' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" label-class-name="desc-label">
          <span class="desc-value">{{ parseTime(viewForm.createTime) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="更新时间" label-class-name="desc-label">
          <span class="desc-value">{{ parseTime(viewForm.updateTime) }}</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog title="企业信息导入" v-model="importOpen" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />
              是否更新已经存在的企业数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="importOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Enterprise">
import {
  listEnterprise,
  getEnterprise,
  delEnterprise,
  addEnterprise,
  updateEnterprise,
  getEnterpriseStatistics
} from "@/api/enterpriseInfo/enterprise";
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();
const { sys_enterprise_status, sys_cert_status } = proxy.useDict('sys_enterprise_status', 'sys_cert_status');

const enterpriseList = ref([]);
const open = ref(false);
const viewOpen = ref(false);
const importOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const activeTab = ref("basic");
const sameAsRegistered = ref(false);
const submitLoading = ref(false);

// 统计数据
const statistics = ref({
  total: 0,
  certified: 0,
  active: 0,
  inactive: 0
});

const queryFormRef = ref();
const enterpriseFormRef = ref();
const uploadRef = ref();

// 上传参数
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  updateSupport: 0,
  headers: { Authorization: "Bearer " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/system/enterprise/importData"
});

const initFormData = {
  enterpriseId: null,
  enterpriseName: null,
  creditCode: null,
  legalPerson: null,
  registeredCapital: null,
  establishDate: null,
  businessScope: null,
  registeredAddress: null,
  officeAddress: null,
  contactPhone: null,
  email: null,
  website: null,
  enterpriseStatus: "0",
  certStatus: "0",
  remark: null
}

const data = reactive({
  form: { ...initFormData },
  viewForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    enterpriseName: null,
    creditCode: null,
    legalPerson: null,
    enterpriseStatus: null,
    certStatus: null,
    establishDateRange: null,
    minCapital: null,
    maxCapital: null,
    orderByColumn: 'createTime',
    isAsc: 'desc'
  },
  rules: {
    enterpriseName: [
      { required: true, message: "企业名称不能为空", trigger: "blur" },
      { min: 2, max: 100, message: "企业名称长度在2到100个字符", trigger: "blur" }
    ],
    creditCode: [
      { required: true, message: "统一社会信用代码不能为空", trigger: "blur" },
      {
        pattern: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/,
        message: "统一社会信用代码格式不正确",
        trigger: "blur"
      }
    ],
    legalPerson: [
      { required: true, message: "法定代表人不能为空", trigger: "blur" },
      { min: 2, max: 50, message: "法定代表人长度在2到50个字符", trigger: "blur" }
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"]
      }
    ],
    contactPhone: [
      {
        pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/,
        message: "请输入正确的联系电话",
        trigger: "blur"
      }
    ],
    website: [
      {
        pattern: /^https?:\/\/.+/,
        message: "请输入正确的网址格式",
        trigger: "blur"
      }
    ]
  }
});

const { queryParams, form, viewForm, rules } = toRefs(data);

/** 查询企业信息列表 */
function getList() {
  loading.value = true;
  listEnterprise(queryParams.value).then(response => {
    enterpriseList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

/** 获取统计数据 */
function getStatistics() {
  getEnterpriseStatistics().then(response => {
    statistics.value = response.data;
  }).catch(() => {
    console.error('获取统计数据失败');
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = { ...initFormData };
  activeTab.value = "basic";
  sameAsRegistered.value = false;
  enterpriseFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    enterpriseName: null,
    creditCode: null,
    legalPerson: null,
    enterpriseStatus: null,
    certStatus: null,
    establishDateRange: null,
    minCapital: null,
    maxCapital: null,
    orderByColumn: 'createTime',
    isAsc: 'desc'
  };
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.enterpriseId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加企业信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const enterpriseId = row.enterpriseId || ids.value[0];
  getEnterprise(enterpriseId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改企业信息";
  });
}

/** 查看按钮操作 */
function handleView(row) {
  getEnterprise(row.enterpriseId).then(response => {
    viewForm.value = response.data;
    viewOpen.value = true;
  });
}

/** 复制按钮操作 */
function handleCopy(row) {
  getEnterprise(row.enterpriseId).then(response => {
    const copyData = { ...response.data };
    // 清除主键和唯一字段
    delete copyData.enterpriseId;
    copyData.enterpriseName = copyData.enterpriseName + "_副本";
    copyData.creditCode = "";
    form.value = copyData;
    open.value = true;
    title.value = "复制企业信息";
  });
}

/** 复制注册地址到办公地址 */
function copyRegisteredAddress(checked) {
  if (checked && form.value.registeredAddress) {
    form.value.officeAddress = form.value.registeredAddress;
  } else if (!checked) {
    form.value.officeAddress = '';
  }
}

/** 统一社会信用代码校验 */
function checkCreditCode() {
  if (form.value.creditCode && form.value.creditCode.length === 18) {
    // 这里可以添加更复杂的校验逻辑
    console.log("校验统一社会信用代码:", form.value.creditCode);
  }
}

/** 提交按钮 */
function submitForm() {
  enterpriseFormRef.value?.validate(valid => {
    if (valid) {
      submitLoading.value = true;

      // 确保新增时不传递 enterpriseId
      const submitData = { ...form.value };
      if (!submitData.enterpriseId) {
        delete submitData.enterpriseId;
      }

      if (form.value.enterpriseId != null) {
        updateEnterprise(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
          getStatistics(); // 刷新统计数据
        }).finally(() => {
          submitLoading.value = false;
        });
      } else {
        addEnterprise(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
          getStatistics(); // 刷新统计数据
        }).finally(() => {
          submitLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const enterpriseIds = row.enterpriseId || ids.value;
  const enterpriseNames = row.enterpriseName || enterpriseList.value.filter(item => ids.value.includes(item.enterpriseId)).map(item => item.enterpriseName).join('、');

  proxy.$modal.confirm(`是否确认删除企业"${enterpriseNames}"的数据项？`).then(function() {
    return delEnterprise(enterpriseIds);
  }).then(() => {
    getList();
    getStatistics(); // 刷新统计数据
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/enterprise/export', {
    ...queryParams.value
  }, `enterprise_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
function handleImport() {
  importOpen.value = true;
}

/** 刷新按钮操作 */
function handleRefresh() {
  getList();
  getStatistics(); // 同时刷新统计数据
  proxy.$modal.msgSuccess("刷新成功");
}

/** 下载模板 */
function importTemplate() {
  proxy.download('system/enterprise/importTemplate', {}, `enterprise_template_${new Date().getTime()}.xlsx`)
}

/** 文件上传中处理 */
function handleFileUploadProgress(event, file, fileList) {
  upload.isUploading = true;
}

/** 文件上传成功处理 */
function handleFileSuccess(response, file, fileList) {
  upload.isUploading = false;
  if (response.code === 200) {
    importOpen.value = false;
    proxy.$alert(
        `<div style="overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;">
        <p>数据导入成功！</p>
        <p>新增：${response.data.addCount} 条</p>
        <p>更新：${response.data.updateCount} 条</p>
        <p>失败：${response.data.failureCount} 条</p>
        ${response.data.failureList && response.data.failureList.length > 0 ?
            '<p>失败数据：</p>' + response.data.failureList.map(item => `<p>${item}</p>`).join('') : ''}
      </div>`,
        "导入结果",
        { dangerouslyUseHTMLString: true }
    );
    getList();
    getStatistics(); // 刷新统计数据
  } else {
    proxy.$modal.msgError(response.msg);
  }
  uploadRef.value?.clearFiles();
}

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

/** 表格排序 */
function handleSortChange({ column, prop, order }) {
  queryParams.value.orderByColumn = prop;
  queryParams.value.isAsc = order === 'ascending' ? 'asc' : 'desc';
  getList();
}

/** 统计卡片点击筛选 */
function filterByStatus(type) {
  // 重置查询参数但不立即查询
  queryFormRef.value?.resetFields();
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    enterpriseName: null,
    creditCode: null,
    legalPerson: null,
    enterpriseStatus: null,
    certStatus: null,
    establishDateRange: null,
    minCapital: null,
    maxCapital: null,
    orderByColumn: 'createTime',
    isAsc: 'desc'
  };

  // 根据类型设置对应的查询条件
  switch (type) {
    case 'certified':
      queryParams.value.certStatus = '1';
      break;
    case 'active':
      queryParams.value.enterpriseStatus = '0';
      break;
    case 'inactive':
      queryParams.value.enterpriseStatus = '1';
      break;
    default:
      break;
  }

  // 执行查询
  handleQuery();
}

// 格式化数字
function formatNumber(num) {
  if (!num) return '0';
  return parseFloat(num).toLocaleString();
}

onMounted(() => {
  getList();
  getStatistics(); // 页面加载时获取统计数据
});
</script>

<style scoped>
.statistics-card {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 8px;
  overflow: hidden;
}

.statistics-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.statistics-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.statistics-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.statistics-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.statistics-icon.certified {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.statistics-icon.active {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.statistics-icon.warning {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.statistics-info {
  flex: 1;
}

.statistics-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.statistics-label {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-card .el-card__body {
  padding: 20px;
}

.mb20 {
  margin-bottom: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.text-center {
  text-align: center;
}

.capital-amount {
  font-weight: 600;
  color: #409eff;
}

.desc-label {
  font-weight: bold;
  color: #606266;
  background-color: #f5f7fa;
}

.desc-value {
  color: #303133;
  font-weight: 500;
}

.business-scope {
  max-height: 120px;
  overflow-y: auto;
  line-height: 1.8;
  word-break: break-all;
  padding: 8px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

:deep(.el-descriptions__label) {
  width: 140px;
}

:deep(.el-table .cell) {
  word-break: break-all;
}

:deep(.el-dialog__body) {
  padding: 10px 20px;
}

:deep(.el-tabs--border-card > .el-tabs__content) {
  padding: 20px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table tr:hover > td) {
  background-color: #f5f7fa;
}

:deep(.el-card) {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-date-editor.el-input) {
  border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .statistics-content {
    padding: 15px;
  }

  .statistics-icon {
    width: 50px;
    height: 50px;
    font-size: 20px;
    margin-right: 15px;
  }

  .statistics-number {
    font-size: 24px;
  }

  .search-card .el-card__body {
    padding: 15px;
  }
}

/* 动画效果 */
.el-table tbody tr {
  transition: all 0.3s ease;
}

.statistics-card {
  position: relative;
  overflow: hidden;
}

.statistics-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.statistics-card:hover::before {
  left: 100%;
}
</style>
