<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="公司名称" prop="customerName">
              <el-input v-model="queryParams.customerName" placeholder="请输入公司名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="助记名称" prop="mnemonicName">
              <el-input v-model="queryParams.mnemonicName" placeholder="请输入助记名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="所属行业" prop="industryId">
              <el-select v-model="queryParams.industryId" placeholder="请选择所属行业" clearable>
                <el-option v-for="dict in industry_id" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="公司类型" prop="customerType">
              <el-select v-model="queryParams.customerType" placeholder="请选择公司类型" clearable>
                <el-option v-for="dict in customer_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="公司状态" prop="customerStatus">
              <el-select v-model="queryParams.customerStatus" placeholder="请选择公司状态" clearable>
                <el-option v-for="dict in customer_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="公司级别" prop="customerLevel">
              <el-select v-model="queryParams.customerLevel" placeholder="请选择公司级别" clearable>
                <el-option v-for="dict in customer_level" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="公司来源" prop="customerSource">
              <el-select v-model="queryParams.customerSource" placeholder="请选择公司来源" clearable>
                <el-option v-for="dict in customer_source" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="企业规模" prop="customerScale">
              <el-select v-model="queryParams.customerScale" placeholder="请选择企业规模" clearable>
                <el-option v-for="dict in customer_scale" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <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-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <div style="font-size: 16px; font-weight: bold; color: #303133">公司信息</div>
      </template>

      <el-table v-loading="loading" border :data="customerInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="公司ID" align="center" prop="customerId" width="80" v-if="columns[0].visible" />
        <el-table-column label="公司名称" align="center" prop="customerName" width="200" v-if="columns[2].visible" show-overflow-tooltip />
        <el-table-column label="助记名称" align="center" prop="mnemonicName" width="130" v-if="columns[3].visible" show-overflow-tooltip />
        <el-table-column label="所属行业" align="center" prop="industryId" width="110" v-if="columns[4].visible">
          <template #default="scope">
            <dict-tag :options="industry_id" :value="scope.row.industryId" />
          </template>
        </el-table-column>
        <el-table-column label="公司类型" align="center" prop="customerType" width="110" v-if="columns[5].visible">
          <template #default="scope">
            <dict-tag :options="customer_type" :value="scope.row.customerType" />
          </template>
        </el-table-column>
        <el-table-column label="公司状态" align="center" prop="customerStatus" width="120" v-if="columns[6].visible">
          <template #default="scope">
            <dict-tag :options="customer_status" :value="scope.row.customerStatus" />
          </template>
        </el-table-column>
        <el-table-column label="公司级别" align="center" prop="customerLevel" width="110" v-if="columns[7].visible">
          <template #default="scope">
            <dict-tag :options="customer_level" :value="scope.row.customerLevel" />
          </template>
        </el-table-column>
        <el-table-column label="公司来源" align="center" prop="customerSource" width="130" v-if="columns[8].visible">
          <template #default="scope">
            <dict-tag :options="customer_source" :value="scope.row.customerSource" />
          </template>
        </el-table-column>
        <el-table-column label="公司经理" align="center" prop="ownerName" width="120" v-if="columns[9].visible" show-overflow-tooltip />
        <el-table-column label="详细地址" align="center" prop="detailedAddress" width="200" v-if="columns[10].visible" show-overflow-tooltip />
        <el-table-column label="企业规模" align="center" prop="customerScale" width="120" v-if="columns[11].visible">
          <template #default="scope">
            <dict-tag :options="customer_scale" :value="scope.row.customerScale" />
          </template>
        </el-table-column>
        <el-table-column label="上级公司" align="center" prop="parentCustomerId" width="100" v-if="columns[12].visible" />
        <el-table-column label="公司关系" align="center" prop="customerRelationship" width="120" v-if="columns[13].visible" show-overflow-tooltip />
        <el-table-column label="法定代表人" align="center" prop="legalRepresentative" width="130" v-if="columns[14].visible" show-overflow-tooltip />
        <el-table-column
          label="营业执照号码"
          align="center"
          prop="businessLicenseNumber"
          width="150"
          v-if="columns[15].visible"
          show-overflow-tooltip
        />
        <el-table-column label="税号" align="center" prop="taxNumber" width="150" v-if="columns[16].visible" show-overflow-tooltip />
        <el-table-column label="开户银行" align="center" prop="bankAccountOpening" width="180" v-if="columns[17].visible" show-overflow-tooltip />
        <el-table-column label="银行账号" align="center" prop="bankNumber" width="180" v-if="columns[18].visible" show-overflow-tooltip />
        <el-table-column label="附件ID" align="center" prop="ossId" width="100" v-if="columns[19].visible" />
        <el-table-column label="备注" align="center" prop="remark" width="200" v-if="columns[20].visible" show-overflow-tooltip />
        <el-table-column label="激活标识" align="center" prop="activeFlag" width="100" v-if="columns[21].visible">
          <template #default="scope">
            <dict-tag :options="active_flag" :value="scope.row.activeFlag" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <!--            <el-tooltip content="公司关系" placement="top">-->
            <!--              <el-button link type="primary" icon="Connection" @click="handleViewRelation(scope.row)"></el-button>-->
            <!--            </el-tooltip>-->
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/crm:customerInfo:edit']"></el-button>
            </el-tooltip>
            <!--            <el-tooltip content="删除" placement="top">-->
            <!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['oa/crm:customerInfo: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-card>

    <!-- 付款账户表格 -->
    <el-card shadow="never" style="margin-top: 20px">
      <template #header>
        <div style="display: flex; align-items: center; justify-content: space-between">
          <div style="font-size: 16px; font-weight: bold; color: #303133">付款账户</div>
<!--          <el-row :gutter="10" class="mb8">-->
<!--            <el-col :span="1.5">-->
<!--              <el-button type="primary" plain icon="Plus" @click="handleAddPaymentAccount" v-hasPermi="['oa/crm:paymentAccount:add']">新增</el-button>-->
<!--            </el-col>-->
<!--            <el-col :span="1.5">-->
<!--              <el-button type="success" plain icon="Edit" :disabled="paymentAccountSingle" @click="handleUpdatePaymentAccount()" v-hasPermi="['oa/crm:paymentAccount:edit']">修改</el-button>-->
<!--            </el-col>-->
<!--            <el-col :span="1.5">-->
<!--              <el-button type="danger" plain icon="Delete" :disabled="paymentAccountMultiple" @click="handleDeletePaymentAccount()" v-hasPermi="['oa/crm:paymentAccount:remove']">删除</el-button>-->
<!--            </el-col>-->
<!--          </el-row>-->
        </div>
      </template>

      <el-table v-loading="paymentAccountLoading" border :data="paymentAccountList" @selection-change="handlePaymentAccountSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="账户类型" align="center" prop="accountType" width="150">
          <template #default="scope">
            <dict-tag :options="account_type" :value="scope.row.accountType" />
          </template>
        </el-table-column>
        <el-table-column label="账户名称" align="center" prop="accountName" width="200" show-overflow-tooltip />
        <el-table-column label="账户号码" align="center" prop="accountNumber" width="200" show-overflow-tooltip />
        <el-table-column label="开户行名称" align="center" prop="bankName" width="200" show-overflow-tooltip />
        <el-table-column label="开户银行代码" align="center" prop="bankCode" width="150" show-overflow-tooltip />
        <el-table-column label="SWIFT代码" align="center" prop="swiftCode" width="150" show-overflow-tooltip />
        <el-table-column label="货币类型" align="center" prop="currency" width="120">
          <template #default="scope">
            <dict-tag :options="currency_type" :value="scope.row.currency" />
          </template>
        </el-table-column>
        <el-table-column label="排序顺序" align="center" prop="sortOrder" width="100" />
        <el-table-column label="备注" align="center" prop="remark" width="200" show-overflow-tooltip />
        <el-table-column label="操作" align="center" fixed="right" width="150" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdatePaymentAccount(scope.row)" v-hasPermi="['oa/crm:paymentAccount:edit']"></el-button>
            </el-tooltip>
<!--            <el-tooltip content="删除" placement="top">-->
<!--              <el-button link type="primary" icon="Delete" @click="handleDeletePaymentAccount(scope.row)" v-hasPermi="['oa/crm:paymentAccount:remove']"></el-button>-->
<!--            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="paymentAccountTotal > 0" :total="paymentAccountTotal" v-model:page="paymentAccountQueryParams.pageNum" v-model:limit="paymentAccountQueryParams.pageSize" @pagination="getPaymentAccountList" />
    </el-card>

    <!-- 添加或修改公司信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body>
      <el-form ref="customerInfoFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司名称" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入公司名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="助记名称" prop="mnemonicName">
              <el-input v-model="form.mnemonicName" placeholder="请输入助记名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属行业" prop="industryId">
              <el-select v-model="form.industryId" placeholder="请选择所属行业" style="width: 100%">
                <el-option v-for="dict in industry_id" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司类型" prop="customerType">
              <el-select v-model="form.customerType" placeholder="请选择公司类型" style="width: 100%">
                <el-option v-for="dict in customer_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司状态" prop="customerStatus">
              <el-select v-model="form.customerStatus" placeholder="请选择公司状态" style="width: 100%">
                <el-option v-for="dict in customer_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司级别" prop="customerLevel">
              <el-select v-model="form.customerLevel" placeholder="请选择公司级别" style="width: 100%">
                <el-option v-for="dict in customer_level" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司来源" prop="customerSource">
              <el-select v-model="form.customerSource" placeholder="请选择公司来源" style="width: 100%">
                <el-option v-for="dict in customer_source" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司经理" prop="ownerId">
              <el-select
                v-model="form.ownerId"
                placeholder="请选择公司经理"
                filterable
                remote
                :remote-method="remoteUserMethod"
                :loading="userLoading"
                style="width: 100%"
                clearable
              >
                <el-option v-for="user in userOptions" :key="user.userId" :label="user.nickName" :value="user.userId">
                  <span style="float: left">{{ user.nickName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ user.userName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="办公地" prop="detailedAddress">
              <el-input v-model="form.detailedAddress" placeholder="请输入办公地" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="注册地" prop="registeredAddress">
              <el-input v-model="form.registeredAddress" placeholder="请输入注册地" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商务联系人" prop="businessContact">
              <el-input v-model="form.businessContact" placeholder="请输入商务联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商务联系人电话" prop="businessContactPhone">
              <el-input v-model="form.businessContactPhone" placeholder="请输入商务联系人电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="技术联系人" prop="technicalContact">
              <el-input v-model="form.technicalContact" placeholder="请输入技术联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="技术联系人电话" prop="technicalContactPhone">
              <el-input v-model="form.technicalContactPhone" placeholder="请输入技术联系人电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="企业规模" prop="customerScale">
              <el-select v-model="form.customerScale" placeholder="请选择企业规模" style="width: 100%">
                <el-option v-for="dict in customer_scale" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上级公司" prop="parentCustomerId">
              <el-select
                v-model="form.parentCustomerId"
                placeholder="请选择上级公司"
                filterable
                :loading="customerLoading"
                style="width: 100%"
                clearable
              >
                <el-option v-for="customer in customerOptions" :key="customer.customerId" :label="customer.customerName" :value="customer.customerId">
                  <span style="float: left">{{ customer.customerName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ customer.mnemonicName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司关系" prop="customerRelationship">
              <el-input v-model="form.customerRelationship" placeholder="请输入公司关系" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法定代表人" prop="legalRepresentative">
              <el-input v-model="form.legalRepresentative" placeholder="请输入法定代表人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="营业执照号码" prop="businessLicenseNumber">
              <el-input v-model="form.businessLicenseNumber" placeholder="请输入营业执照号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税号" prop="taxNumber">
              <el-input v-model="form.taxNumber" placeholder="请输入税号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开户银行" prop="bankAccountOpening">
              <el-input v-model="form.bankAccountOpening" placeholder="请输入开户银行" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行账号" prop="bankNumber">
              <el-input v-model="form.bankNumber" placeholder="请输入银行账号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="附件" prop="ossId">
              <FileUpload v-model="ossIdString" :limit="5" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-form-item label="激活标识" prop="activeFlag">-->
        <!--          <el-radio-group v-model="form.activeFlag">-->
        <!--            <el-radio-->
        <!--              v-for="dict in active_flag"-->
        <!--              :key="dict.value"-->
        <!--              :value="dict.value"-->
        <!--            >{{dict.label}}</el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 公司关系查看对话框 -->
    <el-dialog title="公司关系" v-model="relationDialog.visible" width="1000px" append-to-body>
      <div v-loading="relationLoading">
        <!-- 当前公司信息卡片 -->
        <el-card shadow="hover" style="margin-bottom: 20px">
          <template #header>
            <div style="display: flex; align-items: center; justify-content: space-between">
              <span style="font-size: 16px; font-weight: bold; color: #409eff"> 当前公司 </span>
            </div>
          </template>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="公司名称" :span="2">
              <strong style="font-size: 16px; color: #303133">{{ currentCustomer.customerName }}</strong>
            </el-descriptions-item>
            <el-descriptions-item label="助记名称">
              {{ currentCustomer.mnemonicName || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="公司类型">
              <dict-tag :options="customer_type" :value="currentCustomer.customerType" />
            </el-descriptions-item>
            <el-descriptions-item label="公司状态">
              <dict-tag :options="customer_status" :value="currentCustomer.customerStatus" />
            </el-descriptions-item>
            <el-descriptions-item label="公司级别">
              <dict-tag :options="customer_level" :value="currentCustomer.customerLevel" />
            </el-descriptions-item>
            <el-descriptions-item label="公司经理">
              {{ currentCustomer.ownerName || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="所属行业">
              <dict-tag :options="industry_id" :value="currentCustomer.industryId" />
            </el-descriptions-item>
            <el-descriptions-item label="企业规模">
              <dict-tag :options="customer_scale" :value="currentCustomer.customerScale" />
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 公司关系结构 -->
        <el-row :gutter="20">
          <!-- 上级公司 -->
          <el-col :span="12">
            <el-card shadow="hover">
              <template #header>
                <div style="display: flex; align-items: center; justify-content: space-between">
                  <span style="font-size: 14px; font-weight: bold"> 上级公司 </span>
                  <el-tag type="success" size="small">{{ parentCustomerList.length }} 个</el-tag>
                </div>
              </template>
              <div v-if="parentCustomerList.length > 0">
                <el-table :data="parentCustomerList" border size="small" max-height="400">
                  <el-table-column label="公司名称" prop="customerName" min-width="150" show-overflow-tooltip>
                    <template #default="scope">
                      <el-link type="primary" @click="handleViewRelation(scope.row)" style="font-weight: 500">
                        {{ scope.row.customerName }}
                      </el-link>
                    </template>
                  </el-table-column>
                  <el-table-column label="助记名称" prop="mnemonicName" width="120" show-overflow-tooltip />
                  <el-table-column label="公司类型" prop="customerType" width="100">
                    <template #default="scope">
                      <dict-tag :options="customer_type" :value="scope.row.customerType" />
                    </template>
                  </el-table-column>
                  <el-table-column label="公司状态" prop="customerStatus" width="100">
                    <template #default="scope">
                      <dict-tag :options="customer_status" :value="scope.row.customerStatus" />
                    </template>
                  </el-table-column>
                  <el-table-column label="公司级别" prop="customerLevel" width="100">
                    <template #default="scope">
                      <dict-tag :options="customer_level" :value="scope.row.customerLevel" />
                    </template>
                  </el-table-column>
                  <el-table-column label="公司经理" prop="ownerName" width="100" show-overflow-tooltip />
                </el-table>
              </div>
              <el-empty v-else description="暂无上级公司" :image-size="60" style="padding: 40px 0">
                <el-text type="info" size="small">该公司没有上级公司</el-text>
              </el-empty>
            </el-card>
          </el-col>

          <!-- 下级公司 -->
          <el-col :span="12">
            <el-card shadow="hover">
              <template #header>
                <div style="display: flex; align-items: center; justify-content: space-between">
                  <span style="font-size: 14px; font-weight: bold"> 下级公司 </span>
                  <el-tag type="warning" size="small">{{ childCustomerList.length }} 个</el-tag>
                </div>
              </template>
              <div v-if="childCustomerList.length > 0">
                <el-table :data="childCustomerList" border size="small" max-height="400">
                  <el-table-column label="公司名称" prop="customerName" min-width="150" show-overflow-tooltip>
                    <template #default="scope">
                      <el-link type="primary" @click="handleViewRelation(scope.row)" style="font-weight: 500">
                        {{ scope.row.customerName }}
                      </el-link>
                    </template>
                  </el-table-column>
                  <el-table-column label="助记名称" prop="mnemonicName" width="120" show-overflow-tooltip />
                  <el-table-column label="公司类型" prop="customerType" width="100">
                    <template #default="scope">
                      <dict-tag :options="customer_type" :value="scope.row.customerType" />
                    </template>
                  </el-table-column>
                  <el-table-column label="公司状态" prop="customerStatus" width="100">
                    <template #default="scope">
                      <dict-tag :options="customer_status" :value="scope.row.customerStatus" />
                    </template>
                  </el-table-column>
                  <el-table-column label="公司级别" prop="customerLevel" width="100">
                    <template #default="scope">
                      <dict-tag :options="customer_level" :value="scope.row.customerLevel" />
                    </template>
                  </el-table-column>
                  <el-table-column label="公司经理" prop="ownerName" width="100" show-overflow-tooltip />
                </el-table>
              </div>
              <el-empty v-else description="暂无下级公司" :image-size="60" style="padding: 40px 0">
                <el-text type="info" size="small">该公司没有下级公司</el-text>
              </el-empty>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="relationDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改付款账户信息对话框 -->
    <el-dialog :title="paymentAccountDialog.title" v-model="paymentAccountDialog.visible" width="500px" append-to-body>
      <el-form ref="paymentAccountFormRef" :model="paymentAccountForm" :rules="paymentAccountRules" label-width="120px">
        <el-form-item label="账户类型" prop="accountType">
          <el-select v-model="paymentAccountForm.accountType" placeholder="请选择账户类型" style="width: 100%">
            <el-option v-for="dict in account_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账户名称" prop="accountName">
          <el-input v-model="paymentAccountForm.accountName" placeholder="请输入账户名称" />
        </el-form-item>
        <el-form-item label="账户号码" prop="accountNumber">
          <el-input v-model="paymentAccountForm.accountNumber" placeholder="请输入账户号码" />
        </el-form-item>
        <el-form-item label="开户行名称" prop="bankName">
          <el-input v-model="paymentAccountForm.bankName" placeholder="请输入开户行名称" />
        </el-form-item>
        <el-form-item label="开户银行代码" prop="bankCode">
          <el-input v-model="paymentAccountForm.bankCode" placeholder="请输入开户银行代码" />
        </el-form-item>
        <el-form-item label="SWIFT代码" prop="swiftCode">
          <el-input v-model="paymentAccountForm.swiftCode" placeholder="请输入SWIFT代码" />
        </el-form-item>
        <el-form-item label="货币类型" prop="currency">
          <el-select v-model="paymentAccountForm.currency" placeholder="请选择货币类型" style="width: 100%">
            <el-option v-for="dict in currency_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序顺序" prop="sortOrder">
          <el-input-number v-model="paymentAccountForm.sortOrder" placeholder="请输入排序顺序" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="paymentAccountForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="paymentAccountButtonLoading" type="primary" @click="submitPaymentAccountForm">确 定</el-button>
          <el-button @click="cancelPaymentAccount">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CustomerInfo" lang="ts">
import {
  listCustomerInfo,
  getCustomerInfo,
  delCustomerInfo,
  addCustomerInfo,
  updateCustomerInfo,
  getCrmCustomerInfoList
} from '@/api/oa/crm/customerInfo';
import { CustomerInfoVO, CustomerInfoQuery, CustomerInfoForm } from '@/api/oa/crm/customerInfo/types';
import { listUser, optionSelect } from '@/api/system/user';
import { UserVO } from '@/api/system/user/types';
import FileUpload from '@/components/FileUpload/index.vue';
import { listPaymentAccount, getPaymentAccount, delPaymentAccount, addPaymentAccount, updatePaymentAccount } from '@/api/oa/crm/paymentAccount';
import { PaymentAccountVO, PaymentAccountQuery, PaymentAccountForm } from '@/api/oa/crm/paymentAccount/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { customer_type, active_flag, industry_id, customer_source, customer_scale, customer_status, customer_level, currency_type, account_type } = toRefs<any>(
  proxy?.useDict('customer_type', 'active_flag', 'industry_id', 'customer_source', 'customer_scale', 'customer_status', 'customer_level', 'currency_type', 'account_type')
);

const customerInfoList = ref<CustomerInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const userOptions = ref<UserVO[]>([]);
const userLoading = ref(false);
const customerOptions = ref<CustomerInfoVO[]>([]);
const customerLoading = ref(false);
const relationLoading = ref(false);
const parentCustomerList = ref<CustomerInfoVO[]>([]);
const childCustomerList = ref<CustomerInfoVO[]>([]);
const currentCustomer = ref<CustomerInfoVO>({} as CustomerInfoVO);

const queryFormRef = ref<ElFormInstance>();
const customerInfoFormRef = ref<ElFormInstance>();
const paymentAccountFormRef = ref<ElFormInstance>();

// 付款账户相关数据
const paymentAccountList = ref<PaymentAccountVO[]>([]);
const paymentAccountLoading = ref(false);
const paymentAccountButtonLoading = ref(false);
const paymentAccountIds = ref<Array<string | number>>([]);
const paymentAccountSingle = ref(true);
const paymentAccountMultiple = ref(true);
const paymentAccountTotal = ref(0);

const paymentAccountDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initPaymentAccountFormData: PaymentAccountForm = {
  paymentAccountId: undefined,
  customerId: 1, // 默认 customer_id 为 1
  accountType: undefined,
  accountName: undefined,
  accountNumber: undefined,
  bankName: undefined,
  bankCode: undefined,
  swiftCode: undefined,
  currency: undefined,
  sortOrder: undefined,
  remark: undefined,
  activeFlag: undefined
};

const paymentAccountData = reactive<PageData<PaymentAccountForm, PaymentAccountQuery>>({
  form: { ...initPaymentAccountFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerId: 1, // 默认 customer_id 为 1
    accountType: undefined,
    currency: undefined,
    params: {}
  },
  rules: {
    accountType: [{ required: true, message: '账户类型不能为空', trigger: 'change' }],
    accountName: [{ required: true, message: '账户名称不能为空', trigger: 'blur' }],
    accountNumber: [{ required: true, message: '账户号码不能为空', trigger: 'blur' }]
  }
});

const { queryParams: paymentAccountQueryParams, form: paymentAccountForm, rules: paymentAccountRules } = toRefs(paymentAccountData);

// 附件ID字符串转换（用于FileUpload组件）
const ossIdString = computed({
  get: () => {
    if (form.value.ossId === undefined || form.value.ossId === null) {
      return '';
    }
    return String(form.value.ossId);
  },
  set: (val: string) => {
    form.value.ossId = val || undefined;
  }
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const relationDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `公司ID`, visible: false },
  { key: 1, label: `租户编号`, visible: false },
  { key: 2, label: `公司名称`, visible: true },
  { key: 3, label: `助记名称`, visible: true },
  { key: 4, label: `所属行业`, visible: true },
  { key: 5, label: `公司类型`, visible: true },
  { key: 6, label: `公司状态`, visible: true },
  { key: 7, label: `公司级别`, visible: true },
  { key: 8, label: `公司来源`, visible: true },
  { key: 9, label: `公司经理`, visible: true },
  { key: 10, label: `详细地址`, visible: true },
  { key: 11, label: `企业规模`, visible: true },
  { key: 12, label: `上级公司`, visible: true },
  { key: 13, label: `公司关系`, visible: true },
  { key: 14, label: `法定代表人`, visible: true },
  { key: 15, label: `营业执照号码`, visible: true },
  { key: 16, label: `税号`, visible: true },
  { key: 17, label: `开户银行`, visible: true },
  { key: 18, label: `银行账号`, visible: true },
  { key: 19, label: `附件ID`, visible: false },
  { key: 20, label: `备注`, visible: false },
  { key: 21, label: `激活标识`, visible: false },
  { key: 22, label: `删除标志`, visible: false },
  { key: 23, label: `创建部门`, visible: false },
  { key: 24, label: `创建人`, visible: false },
  { key: 25, label: `创建时间`, visible: false },
  { key: 26, label: `更新人`, visible: false },
  { key: 27, label: `更新时间`, visible: false }
]);

const initFormData: CustomerInfoForm = {
  customerId: undefined,
  customerName: undefined,
  mnemonicName: undefined,
  industryId: undefined,
  customerType: undefined,
  customerStatus: undefined,
  customerLevel: undefined,
  customerSource: undefined,
  ownerId: undefined,
  detailedAddress: undefined,
  customerScale: undefined,
  parentCustomerId: undefined,
  customerRelationship: undefined,
  legalRepresentative: undefined,
  businessLicenseNumber: undefined,
  taxNumber: undefined,
  bankAccountOpening: undefined,
  bankNumber: undefined,
  ossId: undefined,
  remark: undefined,
  activeFlag: undefined,
  ourCompanyFlag: undefined
};
const data = reactive<PageData<CustomerInfoForm, CustomerInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerName: undefined,
    mnemonicName: undefined,
    industryId: undefined,
    customerType: undefined,
    customerStatus: undefined,
    customerLevel: undefined,
    customerSource: undefined,
    ownerId: undefined,
    detailedAddress: undefined,
    customerScale: undefined,
    parentCustomerId: undefined,
    customerRelationship: undefined,
    legalRepresentative: undefined,
    businessLicenseNumber: undefined,
    taxNumber: undefined,
    bankAccountOpening: undefined,
    bankNumber: undefined,
    ossId: undefined,
    activeFlag: undefined,
    ourCompanyFlag: '1',
    params: {}
  },
  rules: {}
});

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

/** 查询公司信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCustomerInfo(queryParams.value);
  customerInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  customerInfoFormRef.value?.resetFields();
  userOptions.value = [];
  customerOptions.value = [];
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: CustomerInfoVO[]) => {
  ids.value = selection.map((item) => item.customerId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 加载公司列表 */
const loadCustomerList = async () => {
  customerLoading.value = true;
  try {
    const res = await getCrmCustomerInfoList(null);
    // 过滤掉当前正在编辑的公司（避免选择自己作为上级）
    const filteredList = res.data?.filter((customer: CustomerInfoVO) => customer.customerId !== form.value.customerId) || [];
    customerOptions.value = filteredList;
  } catch (error) {
    console.error('加载公司列表失败:', error);
    customerOptions.value = [];
  } finally {
    customerLoading.value = false;
  }
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  userOptions.value = [];
  customerOptions.value = [];
  await loadCustomerList();
  dialog.visible = true;
  dialog.title = '添加公司信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: CustomerInfoVO) => {
  reset();
  const _customerId = row?.customerId || ids.value[0];
  const res = await getCustomerInfo(_customerId);
  Object.assign(form.value, res.data);
  // 加载公司列表
  await loadCustomerList();
  // 如果已选上级公司不在列表中（可能被过滤），需要单独加载
  if (form.value.parentCustomerId) {
    const exists = customerOptions.value.some((customer: CustomerInfoVO) => customer.customerId === form.value.parentCustomerId);
    if (!exists) {
      try {
        const customerRes = await getCustomerInfo(form.value.parentCustomerId);
        if (customerRes.data) {
          customerOptions.value.unshift(customerRes.data);
        }
      } catch (error) {
        console.error('加载已选上级公司失败:', error);
      }
    }
  }
  // 加载已选用户信息
  if (form.value.ownerId) {
    await loadSelectedUser(form.value.ownerId);
  }
  dialog.visible = true;
  dialog.title = '修改公司信息';
};

/** 加载已选用户信息 */
const loadSelectedUser = async (userId: string | number) => {
  try {
    const res = await optionSelect([userId]);
    if (res.data && res.data.length > 0) {
      userOptions.value = res.data;
    }
  } catch (error) {
    console.error('加载用户信息失败:', error);
  }
};

/** 远程搜索用户 */
const remoteUserMethod = async (query: string) => {
  if (query) {
    userLoading.value = true;
    try {
      const res = await listUser({
        pageNum: 1,
        pageSize: 20,
        nickName: query,
        status: '0'
      });
      userOptions.value = res.rows || [];
    } catch (error) {
      console.error('搜索用户失败:', error);
      userOptions.value = [];
    } finally {
      userLoading.value = false;
    }
  } else {
    userOptions.value = [];
    // 如果有已选用户，加载已选用户信息
    if (form.value.ownerId) {
      await loadSelectedUser(form.value.ownerId);
    }
  }
};

/** 提交按钮 */
const submitForm = () => {
  customerInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.customerId) {
        await updateCustomerInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addCustomerInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: CustomerInfoVO) => {
  const _customerIds = row?.customerId || ids.value;
  await proxy?.$modal.confirm('是否确认删除公司信息编号为"' + _customerIds + '"的数据项？').finally(() => (loading.value = false));
  await delCustomerInfo(_customerIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oa/crm/customerInfo/export',
    {
      ...queryParams.value
    },
    `customerInfo_${new Date().getTime()}.xlsx`
  );
};

/** 查看公司关系 */
const handleViewRelation = async (row: CustomerInfoVO) => {
  relationLoading.value = true;
  currentCustomer.value = row;
  parentCustomerList.value = [];
  childCustomerList.value = [];

  try {
    // 查询上级公司（如果有parentCustomerId）
    if (row.parentCustomerId) {
      try {
        const parentRes = await getCustomerInfo(row.parentCustomerId);
        if (parentRes.data) {
          parentCustomerList.value = [parentRes.data];
        }
      } catch (error) {
        console.error('查询上级公司失败:', error);
      }
    }

    // 查询下级公司（parentCustomerId等于当前公司ID的公司）
    const childRes = await getCrmCustomerInfoList({
      parentCustomerId: row.customerId
    });
    // 统一使用 data 字段，如果返回的是 rows 则使用 rows
    const childList = childRes.data || childRes.rows || [];
    if (childList.length > 0) {
      childCustomerList.value = childList;
    }
  } catch (error) {
    console.error('查询公司关系失败:', error);
    proxy?.$modal.msgError('查询公司关系失败');
  } finally {
    relationLoading.value = false;
    relationDialog.visible = true;
  }
};

/** 查询付款账户信息列表 */
const getPaymentAccountList = async () => {
  paymentAccountLoading.value = true;
  try {
    const res = await listPaymentAccount(paymentAccountQueryParams.value);
    paymentAccountList.value = res.rows;
    paymentAccountTotal.value = res.total;
  } catch (error) {
    console.error('查询付款账户列表失败:', error);
  } finally {
    paymentAccountLoading.value = false;
  }
};

/** 付款账户多选框选中数据 */
const handlePaymentAccountSelectionChange = (selection: PaymentAccountVO[]) => {
  paymentAccountIds.value = selection.map((item) => item.paymentAccountId);
  paymentAccountSingle.value = selection.length != 1;
  paymentAccountMultiple.value = !selection.length;
};

/** 新增付款账户按钮操作 */
const handleAddPaymentAccount = () => {
  resetPaymentAccount();
  paymentAccountForm.value.customerId = 1; // 设置默认 customer_id 为 1
  paymentAccountDialog.visible = true;
  paymentAccountDialog.title = '添加付款账户信息';
};

/** 修改付款账户按钮操作 */
const handleUpdatePaymentAccount = async (row?: PaymentAccountVO) => {
  resetPaymentAccount();
  const _paymentAccountId = row?.paymentAccountId || paymentAccountIds.value[0];
  const res = await getPaymentAccount(_paymentAccountId);
  Object.assign(paymentAccountForm.value, res.data);
  paymentAccountDialog.visible = true;
  paymentAccountDialog.title = '修改付款账户信息';
};

/** 付款账户表单重置 */
const resetPaymentAccount = () => {
  paymentAccountForm.value = { ...initPaymentAccountFormData };
  paymentAccountFormRef.value?.resetFields();
};

/** 取消付款账户按钮 */
const cancelPaymentAccount = () => {
  resetPaymentAccount();
  paymentAccountDialog.visible = false;
};

/** 提交付款账户表单 */
const submitPaymentAccountForm = () => {
  paymentAccountFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      paymentAccountButtonLoading.value = true;
      try {
        // 确保 customer_id 为 1
        paymentAccountForm.value.customerId = 1;
        if (paymentAccountForm.value.paymentAccountId) {
          await updatePaymentAccount(paymentAccountForm.value);
        } else {
          await addPaymentAccount(paymentAccountForm.value);
        }
        proxy?.$modal.msgSuccess('操作成功');
        paymentAccountDialog.visible = false;
        await getPaymentAccountList();
      } catch (error) {
        console.error('提交付款账户失败:', error);
      } finally {
        paymentAccountButtonLoading.value = false;
      }
    }
  });
};

/** 删除付款账户按钮操作 */
const handleDeletePaymentAccount = async (row?: PaymentAccountVO) => {
  const _paymentAccountIds = row?.paymentAccountId || paymentAccountIds.value;
  await proxy?.$modal.confirm('是否确认删除付款账户信息编号为"' + _paymentAccountIds + '"的数据项？').finally(() => (paymentAccountLoading.value = false));
  await delPaymentAccount(_paymentAccountIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getPaymentAccountList();
};

onMounted(() => {
  getList();
  getPaymentAccountList();
});
</script>
