<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="queryParams" ref="queryRef" label-width="90px">
        <el-row :gutter="15">
          <el-col :span="6">
            <el-form-item label="归属公司" prop="belongCompanyId">
              <el-select v-model="queryParams.belongCompanyId" placeholder="请选择" clearable class="w100">
                <el-option v-for="item in companyOptions" :key="item.id" :label="item.companyName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户编号" prop="customerNo">
              <el-input v-model="queryParams.customerNo" placeholder="请输入客户编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户等级" prop="customerLevelId">
              <el-select v-model="queryParams.customerLevelId" placeholder="请选择" clearable class="w100">
                <el-option v-for="item in levelOptions" :key="item.id" :label="item.levelName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col :span="6">
            <el-form-item label="行业" prop="industryCategoryId">
              <el-select v-model="queryParams.industryCategoryId" placeholder="请选择" clearable class="w100">
                <el-option v-for="item in industryOptions" :key="item.id" :label="item.industryCategoryName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务负责人" prop="salesPersonId">
              <el-select v-model="queryParams.salesPersonId" placeholder="请选择" clearable class="w100">
                <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">
              <el-select v-model="queryParams.serviceStaffId" placeholder="请选择" clearable class="w100">
                <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">
              <el-input v-model="queryParams.belongingDepartmentId" placeholder="请输入部门" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col :span="6">
            <el-form-item label="合作状态" prop="cooperation">
              <el-select v-model="queryParams.cooperation" placeholder="请选择" clearable class="w100">
                <el-option v-for="item in cooperationOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业类型" prop="enterpriseTypeId">
              <el-select v-model="queryParams.enterpriseTypeId" placeholder="请选择" clearable class="w100">
                <el-option v-for="item in corpTypeOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="search-btn-container">
              <el-button icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" icon="Plus" @click="handleAdd" class="btn-blue">新增</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 列表标题与工具栏 -->
    <div class="list-tool-row">
      <div class="tabs-left">
        <div 
          v-for="tab in tabs" 
          :key="tab.key" 
          :class="['tab-nav-item', activeTab === tab.key ? 'active' : '']"
          @click="handleTabClick(tab.key)"
        >
          {{ tab.label }}
          <el-badge v-if="tab.badge" :value="tab.badge" :max="99" class="count-badge" />
        </div>
      </div>
      <div class="tools-right">
        <el-button type="primary" icon="Back" class="blue-action-btn" @click="handleReturnHighSeas">返回客户公海池</el-button>
        <el-button type="primary" icon="Switch" class="blue-action-btn" @click="handleTransferSales">转移业务员</el-button>
        <el-button type="primary" icon="UserFilled" class="blue-action-btn" @click="handleTransferSupport">转移客服人员</el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-outer">
      <el-table 
        v-loading="loading" 
        :data="dataList" 
        @selection-change="handleSelectionChange"
        border
        fit
        highlight-current-row
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="客户编号" align="center" prop="customerNo" width="100" />
        <el-table-column label="客户名称" align="left" prop="customerName" min-width="280" show-overflow-tooltip>
          <template #default="scope">
            <span class="customer-link" @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="100" />
        <el-table-column label="企业类型" align="center" prop="enterpriseTypeName" width="100" />
        <el-table-column label="合作等级" align="center" prop="creditLevelName" width="100" />
        <el-table-column label="业务负责人" align="center" prop="salesPersonName" width="100" />
        <el-table-column label="客服支持" align="center" prop="serviceStaffName" width="100" />
        <el-table-column label="部门" align="center" prop="deptName" width="100" show-overflow-tooltip />
        <el-table-column label="合作状态" align="center" prop="cooperationName" width="100" />
        <el-table-column label="操作" align="center" width="80" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 客户详情组件 (有效客户专用) -->
    <valid-customer-info ref="detailRef" />
  </div>
</template>

<script setup name="CustomerValid">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { listValidCustomer, releaseToPool, listCompanyOption } from "@/api/customer/customerInfo/index";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import { listLevel } from "@/api/customer/customerLevel";
import { selectStaffOptionList } from "@/api/customer/crmStaff";
import { listDictByType } from "@/api/customer/customerDict";
import ValidCustomerInfo from './ValidCustomerInfo.vue';

const { proxy } = getCurrentInstance();
const router = useRouter();

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

// 选项数据
const industryOptions = ref([]);
const staffOptions = ref([]);
const companyOptions = ref([]);
const levelOptions = ref([]);
const corpTypeOptions = ref([]);
const cooperationOptions = ref([]);

const activeTab = ref('list');
const tabs = [
  { label: '客户信息列表', key: 'list' },
  { label: '我负责的客户', key: 'mine' },
  { label: '我参与的客户', key: 'involved' },
  { label: '全部客户', key: 'all', badge: 99 }
];

const handleTabClick = (key) => {
  activeTab.value = key;
  handleQuery();
};

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  belongCompanyId: undefined,
  customerNo: undefined,
  customerName: undefined,
  customerLevelId: undefined,
  industryCategoryId: undefined,
  salesPersonId: undefined,
  serviceStaffId: undefined,
  belongingDepartmentId: undefined,
  cooperation: undefined,
  enterpriseTypeId: undefined
});

const getList = () => {
  loading.value = true;
  listValidCustomer(queryParams).then(res => {
    dataList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

const handleSelectionChange = (selection) => {
   ids.value = selection.map(item => item.id);
};

const handleReturnHighSeas = () => {
  if (ids.value.length === 0) { proxy.$modal.msgWarning("请选择要操作的数据"); return; }
  proxy.$modal.confirm(`是否将选中的${ids.value.length}个客户退回到客户公海池？`).then(() => {
    loading.value = true;
    const promises = ids.value.map(id => releaseToPool(id, "有效客户退回"));
    Promise.all(promises).then(() => {
      proxy.$modal.msgSuccess("退回成功");
      getList();
    }).catch(() => {
      loading.value = false;
    });
  }).catch(() => {});
};

const handleTransferSales = () => {
  if (ids.value.length === 0) { proxy.$modal.msgWarning("请选择要操作的数据"); return; }
  proxy.$modal.confirm("是否转移选中客户的业务负责人？").then(() => {
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => {});
};

const handleTransferSupport = () => {
  if (ids.value.length === 0) { proxy.$modal.msgWarning("请选择要操作的数据"); return; }
  proxy.$modal.confirm("是否转移选中客户的客服助理？").then(() => {
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => {});
};

const handleQuery = () => { getList(); };
const resetQuery = () => { 
  proxy.resetForm("queryRef"); 
  handleQuery(); 
};
const handleAdd = () => { router.push('/customer/valid-add'); };
const handleDetail = (row) => { detailRef.value.open(row.id); };

const initOptions = async () => {
  listCompanyOption().then(res => companyOptions.value = res.data || []);
  listIndustryCategory().then(res => industryOptions.value = res.data || []);
  listLevel().then(res => levelOptions.value = res.rows || []);
  selectStaffOptionList().then(res => staffOptions.value = res.data || []);
  listDictByType("crm_enterprise_type").then(res => corpTypeOptions.value = res.data || []);
  listDictByType("crm_cooperation_status").then(res => cooperationOptions.value = res.data || []);
};

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

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

/* 搜索容器 */
.search-section {
  background: #fff;
  padding: 24px 20px 4px 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 5px;

  .w100 { width: 100%; }
  
  :deep(.el-form-item) {
    margin-bottom: 20px;
    .el-form-item__label {
      font-weight: 500;
      color: #666;
    }
  }
}

.search-btn-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 12px;
  height: 32px;
  margin-top: 1px;
  
  .el-button {
    height: 32px;
    border-radius: 4px;
    padding: 0 16px;
    font-size: 14px;
    border: 1px solid #dcdfe6;
  }

  .btn-blue {
    background-color: #3b82f6;
    border-color: #3b82f6;
    color: #fff;
    &:hover { background-color: #2563eb; }
  }
}

/* 列表标题栏 */
.list-tool-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background: #fff;
  height: 50px;
  border-radius: 4px 4px 0 0;
  border-bottom: 1px solid #f0f2f5;
}

.tabs-left {
  display: flex;
  gap: 15px;
  height: 100%;

  .tab-nav-item {
    display: flex;
    align-items: center;
    position: relative;
    cursor: pointer;
    font-size: 14px;
    color: #333;
    padding: 0 15px;
    border: 1px solid transparent;
    border-bottom: none;
    margin-bottom: -1px;

    &.active {
      background-color: #fff;
      font-weight: bold;
      border: 1px solid #e4e7ed;
      border-bottom-color: #fff;
      border-radius: 4px 4px 0 0;
    }
  }
  
  .count-badge {
    margin-left: 5px;
    :deep(.el-badge__content) {
      background-color: #f56c6c;
      transform: scale(0.8) translateY(-2px);
    }
  }
}

.tools-right {
  display: flex;
  gap: 10px;

  .blue-action-btn {
    background-color: #3b82f6;
    border-color: #3b82f6;
    height: 30px;
    padding: 0 15px;
    font-size: 13px;
    border-radius: 4px;
  }
}

/* 表格外部容器 */
.table-outer {
  background: #fff;
  padding: 15px 20px 20px 20px;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

  :deep(.el-table__header) {
    th {
      background-color: #f8fafc !important;
      color: #333;
      font-weight: bold;
      height: 44px;
      font-size: 13px;
    }
  }
  
  :deep(.el-table__row) {
    height: 48px;
    td { font-size: 13px; color: #333; }
  }
}

.customer-link {
  color: #ea580c;
  cursor: pointer;
  font-weight: 600;
  
  &:hover {
    text-decoration: underline;
  }
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
