<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryRef" label-width="90px">
        <!-- 第一行：客户编号、客户名称、客户等级、行业 -->
        <el-row :gutter="20" class="mt-15">
          <el-col :span="6">
            <el-form-item label="客户编号" prop="customerNo" class="custom-form-item">
              <el-input v-model="queryParams.customerNo" placeholder="请输入客户编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称" prop="customerName" class="custom-form-item">
              <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户等级" prop="customerLevelId" class="custom-form-item">
              <el-select v-model="queryParams.customerLevelId" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in levelOptions" :key="item.id" :label="item.levelName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="行业" prop="industryCategoryId" class="custom-form-item">
              <el-select v-model="queryParams.industryCategoryId" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in industryOptions" :key="item.id" :label="item.industryCategoryName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：业务负责人、客服支持、部门、合作状态 -->
        <el-row :gutter="20" class="mt-15">
          <el-col :span="6">
            <el-form-item label="业务负责人" prop="salesPersonId" class="custom-form-item">
              <el-select v-model="queryParams.salesPersonId" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in staffOptions" :key="item.staffId" :label="item.staffName" :value="item.staffId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客服支持" prop="serviceStaffId" class="custom-form-item">
              <el-select v-model="queryParams.serviceStaffId" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in staffOptions" :key="item.staffId" :label="item.staffName" :value="item.staffId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门" prop="belongingDepartmentId" class="custom-form-item">
              <el-tree-select
                v-model="queryParams.belongingDepartmentId"
                :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="请选择部门"
                check-strictly
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>          <el-col :span="6">
            <el-form-item label="合作状态" prop="status" class="custom-form-item">
              <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in cooperationOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：企业类型 + 操作按钮 -->
        <el-row :gutter="20" class="mt-15">
          <el-col :span="6">
            <el-form-item label="企业类型" prop="enterpriseTypeId" class="custom-form-item">
              <el-select v-model="queryParams.enterpriseTypeId" placeholder="请选择" clearable style="width: 100%">
                <el-option v-for="item in corpTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <div class="search-btns-area">
              <el-button type="default" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <div class="title-container">
      <span class="list-title">客户公海信息列表</span>
    </div>

    <!-- 列表区域 -->
    <el-card shadow="never" class="table-card">
      <el-table ref="tableRef" v-loading="loading" :data="dataList" border class="custom-table">
        <el-table-column label="客户编号" align="center" prop="customerNo" width="100" />
        <el-table-column align="center" min-width="250" show-overflow-tooltip>
          <template #header>
            <span class="required-star"></span>客户名称
          </template>
          <template #default="scope">
            <span class="customer-name-text" @click="handleDetail(scope.row)">{{ scope.row.customerName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="归属公司" align="center" prop="companyName" min-width="180" show-overflow-tooltip />
        <el-table-column label="行业" align="center" prop="industryName" width="120" />
        <el-table-column label="企业类型" align="center" prop="enterpriseTypeName" width="120" />
        <el-table-column label="合作等级" align="center" prop="customerLevelName" width="100" />
        <el-table-column label="业务负责人" align="center" prop="salesPersonName" width="120" />
        <el-table-column align="center" prop="serviceStaffName" width="120">
          <template #header>
            <span class="required-star"></span>客服支持
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" prop="deptName" width="120" />
        <el-table-column label="合作状态" align="center" prop="cooperationName" width="100" />
        <el-table-column label="操作" align="center" width="130" fixed="right">
          <template #default="scope">
            <el-button link type="info" class="op-link detail-link" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link type="primary" class="op-link claim-link" @click="handleClaim(scope.row)">认领</el-button>
          </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>

    <!-- 客户详情侧边栏 -->
    <customer-detail ref="infoRef" @success="getList" />

    <!-- 认领客户对话框 -->
    <el-dialog title="您正在认领公海客户，请录入客户认领信息" v-model="claimOpen" width="550px" append-to-body class="claim-dialog">
      <el-form ref="claimRef" :model="claimForm" :rules="claimRules" label-width="140px">
        <el-form-item label="业务员：" prop="salespersonId">
          <el-select v-model="claimForm.salespersonId" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in staffOptions" :key="item.staffId" :label="item.staffName" :value="item.staffId" />
          </el-select>
        </el-form-item>
        <el-form-item label="客服：" prop="serviceStaffId">
          <el-select v-model="claimForm.serviceStaffId" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in staffOptions" :key="item.staffId" :label="item.staffName" :value="item.staffId" />
          </el-select>
        </el-form-item>
        <el-form-item label="保留已有负责人：" prop="keepOwner">
          <el-radio-group v-model="claimForm.keepOwner">
            <el-radio value="1">是</el-radio>
            <el-radio value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="text-align: right; padding-top: 20px;">
          <el-button @click="cancelClaim" style="width: 80px;">取 消</el-button>
          <el-button type="primary" @click="submitClaimForm" style="width: 80px; background-color: #3b82f6; border-color: #3b82f6;">确 认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CustomerHighSeas">
import { ref, reactive, onMounted, getCurrentInstance, toRefs } from 'vue';
import { useRouter } from 'vue-router';
import { listPool, claimPool } from "@/api/customer/customerPool";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import { listLevel } from "@/api/customer/customerLevel";
import { listComStaff } from "@/api/system/comStaff/index";
import { deptTreeSelect } from "@/api/system/dept";
import { debounce } from 'lodash-es';
import CustomerDetail from "./detail.vue";

const proxy = getCurrentInstance().proxy;
const { Q0001: corpTypeOptions, cooperation_status: cooperationOptions } = toRefs(reactive(proxy.useDict("Q0001", "cooperation_status")));
const router = useRouter();

const loading = ref(false);
const total = ref(0);
const dataList = ref([]);

// 下拉选项数据
const industryOptions = ref([]);
const levelOptions = ref([]);
const staffOptions = ref([]);
const deptOptions = ref([]);
const infoRef = ref(null);
const tableRef = ref(null);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  customerNo: undefined,
  customerName: undefined,
  industryCategoryId: undefined,
  customerLevelId: undefined,
  enterpriseTypeId: undefined,
  salesPersonId: undefined,
  serviceStaffId: undefined,
  belongingDepartmentId: undefined,
  status: undefined,
  enterpriseSource: undefined,
  procurementType: undefined,
  isApprove: undefined,
  platformCode: undefined
});

// 认领相关数据
const claimOpen = ref(false);
const claimRef = ref(null);
const claimForm = reactive({
  customerId: undefined,
  salespersonId: undefined,
  serviceStaffId: undefined,
  keepOwner: '0'
});

const claimRules = {
  salespersonId: [{ required: true, message: "请选择业务员", trigger: "change" }],
  serviceStaffId: [{ required: true, message: "请选择客服", trigger: "change" }],
  keepOwner: [{ required: true, message: "请选择是否保留已有负责人", trigger: "change" }]
};

/** 查询基础下拉选项 */
const getOptions = async () => {
  try {
    const industryRes = await listIndustryCategory();
    industryOptions.value = industryRes.data || [];
    
    const levelRes = await listLevel();
    levelOptions.value = levelRes.rows || [];
    
    const staffRes = await listComStaff({ pageSize: 1000 });
    staffOptions.value = staffRes.rows || staffRes.data || [];

    const deptRes = await deptTreeSelect();
    deptOptions.value = proxy.handleTree(deptRes.data, "deptId");
  } catch (err) {
    console.error('获取选项失败:', err);
  }
};

/** 查询公海列表数据 */
const getList = () => {
  loading.value = true;
  listPool(queryParams).then(response => {
    dataList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  proxy.resetForm("queryRef");
  handleQuery();
};


/** 打开详情侧边栏 */
const handleDetail = (row) => {
  infoRef.value.open(row.id);
};


const handleClaim = (row) => {
  claimForm.customerId = row.id;
  claimForm.salespersonId = undefined;
  claimForm.serviceStaffId = undefined;
  claimForm.keepOwner = '0';
  claimOpen.value = true;
};

const cancelClaim = () => {
  claimOpen.value = false;
  proxy.resetForm("claimRef");
};

const submitClaimForm = () => {
  proxy.$refs["claimRef"].validate(async valid => {
    if (valid) {
      loading.value = true;
      try {
        const data = {
          id: claimForm.customerId,
          salesPersonId: claimForm.salespersonId,
          serviceStaffId: claimForm.serviceStaffId,
          keepOldManager: claimForm.keepOwner
        };
        // 自动带出业务员所属部门
        const selectedStaff = staffOptions.value.find(s => s.staffId === claimForm.salespersonId);
        if (selectedStaff) {
          data.deptId = selectedStaff.deptId;
        }
        await claimPool(data);
        proxy.$modal.msgSuccess("认领成功");
        claimOpen.value = false;
        getList();
      } catch (err) {
        console.error(err);
      } finally {
        loading.value = false;
      }
    }
  });
};

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


<style scoped lang="scss">
.app-container {
  padding: 24px;
  background-color: #f8fafc;
  min-height: 100vh;

  /* 全局强制取消加粗 */
  :deep(*) {
    font-weight: 400 !important;
  }
}

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

.custom-form-item {
  margin-bottom: 0px;
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #475569;
    padding-right: 12px;
  }
  :deep(.el-input__wrapper), :deep(.el-select__wrapper) {
    box-shadow: 0 0 0 1px #cbd5e1 inset !important;
    &:hover, &.is-focus {
      box-shadow: 0 0 0 1px #3b82f6 inset !important;
    }
  }
}

.search-btns-area {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 12px;
  padding-left: 20px;
  .el-button {
    border-radius: 2px;
    height: 32px;
    padding: 0 15px;
    font-size: 14px;
    transition: all 0.2s;
  }
  // 搜索和重置按钮样式
  .el-button--default, .el-button:not(.el-button--primary) {
    border: 1px solid #d1d5db !important;
    color: #374151 !important;
    background-color: #fff;
    &:hover {
      background-color: #f9fafb;
      border-color: #9ca3af !important;
    }
  }
  // 新增按钮样式
  .el-button--primary {
    background-color: #3b82f6 !important;
    border-color: #3b82f6 !important;
    color: #ffffff !important;
    &:hover {
      background-color: #2563eb !important;
      border-color: #2563eb !important;
    }
  }
}

.required-star {
  color: #ea580c;
  margin-right: 4px;
  font-weight: bold;
}

.title-container {
  margin: 20px 0 15px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .list-title {
    font-size: 16px;
    font-weight: normal;
    color: #1e293b;
  }
}

.table-card {
  border-radius: 4px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
  :deep(.el-card__body) {
    padding: 0;
  }
}

.custom-table {
  border-radius: 0;
  overflow: hidden;
  :deep(th.el-table__cell) {
    background-color: #f8fafc !important;
    color: #1e293b;
    font-size: 13px;
    font-weight: normal;
    height: 44px;
  }
  :deep(.el-table__row) {
    height: 48px;
    td {
      font-size: 13px;
      color: #334155;
    }
  }
  // 修复固定列左侧边框缺失问题
  :deep(.el-table__fixed-right) {
    border-left: 1px solid #ebeef5;
    height: 100% !important; // 确保边框高度撑满
  }
  :deep(.el-table__fixed-right-patch) {
    border-left: 1px solid #ebeef5;
    background-color: #f8fafc !important;
  }
}

.customer-name-text {
  color: #409eff; 
  font-weight: normal;
  cursor: pointer;
  transition: all 0.2s;
  &:hover {
    color: #66b1ff;
  }
}

.op-link {
  font-weight: normal;
  margin: 0 6px;
  font-size: 13px;
}

.detail-link {
  color: #909399 !important;
  &:hover {
    color: #606266 !important;
  }
}

.claim-link {
  color: #409eff !important;
  &:hover {
    color: #66b1ff !important;
  }
}

.mt-15 {
  margin-top: 15px;
}

:deep(.claim-dialog) {
  .el-dialog__header {
    margin-right: 0;
    padding: 20px 24px;
    border-bottom: 1px solid #f1f5f9;
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #1e293b;
    }
  }
  .el-dialog__body {
    padding: 30px 40px;
  }
  .el-form-item__label {
    font-weight: 500;
    color: #475569;
    white-space: nowrap;
  }
  .el-radio {
    margin-right: 30px;
  }
}
</style>
