<template>
  <div class="app-container">
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryRef" label-width="110px">
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="归属公司" prop="belongCompanyId" class="custom-form-item">
              <el-select v-model="queryParams.belongCompanyId" placeholder="请选择" clearable style="width: 100%">
                <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" 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-row>

        <!-- 第二行 -->
        <el-row :gutter="20" class="mt-15">
          <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-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.staffCode ? '(' + item.staffCode + ') ' : '') + 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.staffCode ? '(' + item.staffCode + ') ' : '') + 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-row>

        <!-- 第三行 -->
        <el-row :gutter="20" class="mt-15">
          <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-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="12">
            <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>

    <el-card shadow="never" class="table-card">
      <div class="list-tool-row">
        <div class="tabs-left">
          <span class="list-main-title">客户信息列表</span>
          <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-btn" @click="handleReturnHighSeas">退回到客户公海池</el-button>
          <el-button type="primary" icon="Switch" class="blue-btn" @click="handleTransferSales">转移业务员</el-button>
          <el-button type="primary" icon="UserFilled" class="blue-btn" @click="handleTransferSupport">转移客服人员</el-button>
        </div>
      </div>

      <el-table 
        v-loading="loading" 
        :data="dataList" 
        @selection-change="handleSelectionChange"
        border
        class="custom-table"
      >
        <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" min-width="250" show-overflow-tooltip>
          <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 label="客服支持" align="center" prop="serviceStaffName" width="120" />
        <el-table-column label="部门" align="center" prop="deptName" width="120" show-overflow-tooltip />
        <el-table-column label="合作状况" align="center" prop="cooperationName" width="100" />
        <el-table-column label="操作" align="center" width="100" fixed="right">
          <template #default="scope">
            <el-button link type="info" class="op-link detail-link" @click="handleDetail(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" 
        layout="total, sizes, prev, pager, next, jumper"
        @pagination="getList" 
      />
    </el-card>

    <!-- 转移人员弹窗 -->
    <el-dialog :title="transferDialog.title" v-model="transferDialog.visible" width="400px" append-to-body>
      <el-form ref="transferRef" :model="transferForm" :rules="transferRules" label-width="100px">
        <el-form-item label="选择人员：" prop="staffId">
          <template #label>
            选择人员：
          </template>
          <el-select v-model="transferForm.staffId" placeholder="请选择" filterable style="width: 100%">
            <el-option v-for="item in staffOptions" :key="item.staffId" :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName" :value="item.staffId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="transferDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitTransfer">确 认</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 客户详情抽屉 -->
    <customer-detail ref="detailRef" @success="getList" />

    <!-- 子路由出口：用于显示其他可能的子页面 -->
    <router-view />
  </div>
</template>

<script setup name="CustomerValid">
import { ref, reactive, onMounted, getCurrentInstance, toRefs } from 'vue';
import { useRouter } from 'vue-router';
import { listMineCustomer, listInvolvedCustomer, listAllCustomer, releaseToPool, listCompanyOption, transferSalesPerson, transferServiceStaff } 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 { useUserStore } from "@/store/modules/user";
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 userStore = useUserStore();

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 deptOptions = ref([]);

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

const handleTabClick = (key) => {
  activeTab.value = key;
  queryParams.activeTab = key;
  // 重置负责人相关的过滤参数
  queryParams.salesPersonId = undefined;
  queryParams.serviceStaffId = undefined;
  handleQuery();
};

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

const getList = () => {
  loading.value = true;
  let req = null;
  if (activeTab.value === 'mine') {
    req = listMineCustomer(queryParams);
  } else if (activeTab.value === 'involved') {
    req = listInvolvedCustomer(queryParams);
  } else {
    req = listAllCustomer(queryParams);
  }
  
  req.then(res => {
    dataList.value = res.rows || [];
    total.value = res.total || 0;
    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;
    // 一次性调用批量接口
    releaseToPool(ids.value, "有效客户退回").then(() => {
      proxy.$modal.msgSuccess("退回成功");
      // 跳转到公海池页面
      router.push('/customer/highseas');
    }).catch(() => {
      loading.value = false;
    });
  }).catch(() => {});
};

const transferDialog = reactive({
  visible: false,
  title: '',
  type: '' // 'sales' 或 'support'
});
const transferForm = reactive({
  staffId: undefined
});
const transferRules = {
  staffId: [{ required: true, message: '请选择人员', trigger: 'change' }]
};
const transferRef = ref(null);

const handleTransferSales = () => {
  if (ids.value.length === 0) { proxy.$modal.msgWarning("请选择要操作的数据"); return; }
  transferDialog.title = '转移业务员';
  transferDialog.type = 'sales';
  transferForm.staffId = undefined;
  if (transferRef.value) transferRef.value.clearValidate();
  transferDialog.visible = true;
};

const handleTransferSupport = () => {
  if (ids.value.length === 0) { proxy.$modal.msgWarning("请选择要操作的数据"); return; }
  transferDialog.title = '转移客服人员';
  transferDialog.type = 'support';
  transferForm.staffId = undefined;
  if (transferRef.value) transferRef.value.clearValidate();
  transferDialog.visible = true;
};

const submitTransfer = () => {
  transferRef.value.validate(valid => {
    if (valid) {
      const data = { customerIds: ids.value };
      let apiCall = null;
      if (transferDialog.type === 'sales') {
        data.salesPersonId = transferForm.staffId;
        apiCall = transferSalesPerson(data);
      } else {
        data.serviceStaffId = transferForm.staffId;
        apiCall = transferServiceStaff(data);
      }
      
      apiCall.then(() => {
        proxy.$modal.msgSuccess("转移成功");
        transferDialog.visible = false;
        getList();
      });
    }
  });
};

const handleQuery = debounce(() => { 
  queryParams.pageNum = 1;
  getList(); 
}, 300);
const resetQuery = () => { 
  proxy.resetForm("queryRef"); 
  // 手动重置所有查询参数为初始值，确保重置彻底
  Object.keys(queryParams).forEach(key => {
    if (key !== 'pageNum' && key !== 'pageSize') {
      queryParams[key] = undefined;
    }
  });
  queryParams.pageNum = 1;
  getList(); // 重置后直接刷新列表，不再等待防抖
};

const handleDetail = debounce((row) => { 
  detailRef.value.open(row.id);
}, 200);

const initOptions = async () => {
  listCompanyOption().then(res => companyOptions.value = res.data || []);
  listIndustryCategory().then(res => industryOptions.value = res.data || res.rows || []);
  listLevel().then(res => levelOptions.value = res.rows || []);
  listComStaff({ pageSize: 1000 }).then(res => staffOptions.value = res.rows || res.data || []);
  deptTreeSelect().then(res => deptOptions.value = proxy.handleTree(res.data, "deptId"));
};

onMounted(() => {
  initOptions();
  getList();
});
</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: normal !important;
    color: #475569;
    padding-right: 12px;
    white-space: nowrap !important;
  }
  :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;
    }
  }
}

.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;
  }
}

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

.tabs-left {
  display: flex;
  gap: 12px;
  height: 100%;
  align-items: center;

  .list-main-title {
    font-size: 15px;
    font-weight: normal;
    color: #1e293b;
    margin-right: 20px;
  }

  .tab-nav-item {
    display: flex;
    align-items: center;
    cursor: pointer;
    font-size: 14px;
    color: #333;
    padding: 6px 16px;
    border: 1px solid #e2e8f0;
    border-radius: 2px;
    transition: all 0.2s;
    background-color: #fff;

    &.active {
      color: #409eff;
      font-weight: normal;
      border-color: #409eff;
    }
    &:hover:not(.active) {
      border-color: #cbd5e1;
    }
  }
  
  .count-badge {
    margin-left: 5px;
    :deep(.el-badge__content) {
      background-color: #ef4444;
      transform: scale(0.8) translateY(-4px);
    }
  }
}

.tools-right {
  display: flex;
  gap: 12px;
  .blue-btn {
    background-color: #409eff !important;
    border-color: #409eff !important;
    height: 36px;
    padding: 0 16px;
    font-size: 14px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    gap: 6px;
    &:hover {
      background-color: #66b1ff !important;
    }
  }
}

.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: 48px;
  }
  :deep(.el-table__row) {
    height: 52px;
    td {
      font-size: 13px;
      color: #334155;
    }
  }
  :deep(.el-table__fixed-right) {
    border-left: 1px solid #ebeef5;
    height: 100% !important;
  }
}

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

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

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

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

/* 移除所有文字下划线 */
:deep(*) {
  text-decoration: none !important;
}
</style>
