<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>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oa/crm:customerInfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oa/crm:customerInfo:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oa/crm:customerInfo:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/crm:customerInfo:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </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="250" v-if="columns[2].visible" show-overflow-tooltip>
          <template #default="scope">
            <el-link type="primary" underline @click="handleDetail(scope.row)">
              {{ scope.row.customerName }}
            </el-link>
          </template>
        </el-table-column>
        <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="taxNumber" width="150" v-if="columns[16].visible" show-overflow-tooltip />
        <el-table-column label="单位地址" align="center" prop="registeredAddress" width="200" v-if="columns[28].visible" show-overflow-tooltip />
        <el-table-column label="电话号码" align="center" prop="phoneNumber" width="150" v-if="columns[33].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="商务联系人" align="center" prop="businessContact" width="120" v-if="columns[29].visible" show-overflow-tooltip />
        <el-table-column
          label="商务联系人电话"
          align="center"
          prop="businessContactPhone"
          width="150"
          v-if="columns[30].visible"
          show-overflow-tooltip
        />
        <el-table-column label="技术联系人" align="center" prop="technicalContact" width="120" v-if="columns[31].visible" show-overflow-tooltip />
        <el-table-column
          label="技术联系人电话"
          align="center"
          prop="technicalContactPhone"
          width="150"
          v-if="columns[32].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="附件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="220" 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="Tickets" @click="handleTripHistory(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-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="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="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-col :span="12">-->
<!--            <el-form-item label="营业执照号码" prop="businessLicenseNumber">-->
<!--              <el-input v-model="form.businessLicenseNumber" placeholder="请输入营业执照号码" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="税号" prop="taxNumber">
              <el-input v-model="form.taxNumber" placeholder="请输入税号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位地址" prop="registeredAddress">
              <el-input v-model="form.registeredAddress" placeholder="请输入单位地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话号码" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入电话号码" />
            </el-form-item>
          </el-col>
          <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-col :span="12">
            <el-form-item label="法定代表人" prop="legalRepresentative">
              <el-input v-model="form.legalRepresentative" placeholder="请输入法定代表人" />
            </el-form-item>
          </el-col>
          <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="开票附件" prop="ossId">
              <div>
                <FileUpload
                  v-model="ossIdString"
                  :limit="5"
                  :fileType="['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'pdf', 'zip', 'rar', 'jpg', 'jpeg', 'png']"
                />
                <div style="margin-top: 4px; color: #909399; font-size: 20px">
                  请及时上传营业执照与开票资料！
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
          <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="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="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-col :span="12">
            <el-form-item label="客户关系" prop="customerRelationship">
              <el-input v-model="form.customerRelationship" placeholder="请输入客户关系" />
            </el-form-item>
          </el-col>
          <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>
  </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';

const router = useRouter();

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

const customerInfoList = ref<CustomerInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
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>();

// 附件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 },
  { key: 28, label: `单位地址`, visible: true },
  { key: 29, label: `商务联系人`, visible: true },
  { key: 30, label: `商务联系人电话`, visible: true },
  { key: 31, label: `技术联系人`, visible: true },
  { key: 32, label: `技术联系人电话`, visible: true },
  { key: 33, label: `电话号码`, visible: true }
]);

const initFormData: CustomerInfoForm = {
  customerId: undefined,
  customerName: undefined,
  mnemonicName: undefined,
  industryId: undefined,
  customerType: undefined,
  customerStatus: undefined,
  customerLevel: undefined,
  customerSource: undefined,
  ownerId: undefined,
  registeredAddress: undefined,
  phoneNumber: undefined,
  detailedAddress: undefined,
  businessContact: undefined,
  businessContactPhone: undefined,
  technicalContact: undefined,
  technicalContactPhone: 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,
    registeredAddress: undefined,
    detailedAddress: undefined,
    businessContact: undefined,
    businessContactPhone: undefined,
    technicalContact: undefined,
    technicalContactPhone: undefined,
    customerScale: undefined,
    parentCustomerId: undefined,
    customerRelationship: undefined,
    legalRepresentative: undefined,
    businessLicenseNumber: undefined,
    taxNumber: undefined,
    bankAccountOpening: undefined,
    bankNumber: undefined,
    ossId: undefined,
    activeFlag: undefined,
    ourCompanyFlag: '0',
    params: {}
  },
  rules: {
    customerName: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }]
  }
});

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 handleDetail = (row: CustomerInfoVO) => {
  router.push({
    path: `/oa/crm/customerDetail/${row.customerId}`
  });
};

/** 查看客户出差交流记录 */
const handleTripHistory = (row: CustomerInfoVO) => {
  router.push({
    path: '/customer/tripHistory',
    query: {
      customerId: row.customerId,
      customerName: row.customerName
    }
  });
};

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