<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" class="search-form" label-width="100px">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="客户编号" prop="customerNo" style="width: 100%">
            <el-input v-model="queryParams.customerNo" placeholder="请输入客户编号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="客户名称" prop="customerName" style="width: 100%">
            <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="客户等级" prop="customerLevelId" style="width: 100%">
            <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="industryId" style="width: 100%">
            <el-select v-model="queryParams.industryId" 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="10">
        <el-col :span="6">
          <el-form-item label="业务负责人" prop="managerId" style="width: 100%">
            <el-select v-model="queryParams.managerId" placeholder="搜索并选择负责人" clearable filterable 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="supportId" style="width: 100%">
            <el-select v-model="queryParams.supportId" placeholder="搜索并选择客服" clearable filterable 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="deptId" style="width: 100%">
            <el-input v-model="queryParams.deptId" placeholder="请输入部门" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合作状态" prop="status" style="width: 100%">
            <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 100%">
              <el-option v-for="item in cooperationOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="企业类型" prop="enterpriseTypeId" style="width: 100%">
            <el-select v-model="queryParams.enterpriseTypeId" placeholder="请选择" clearable style="width: 100%">
              <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" :offset="6" style="display: flex; justify-content: flex-end; align-items: center;">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 列表展示 -->
    <el-table v-loading="loading" :data="poolList" border>
      <el-table-column label="客户编号" align="center" prop="customerNo" width="100" />
      <el-table-column label="客户名称" align="center" prop="customerName" min-width="180">
        <template #default="scope">
          <span class="customer-name-link">{{ scope.row.customerName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归属公司" align="center" prop="belongCompanyName" min-width="140" 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="customerLevelName" width="100" />
      <el-table-column label="业务负责人" align="center" prop="managerName" width="120" />
      <el-table-column label="客服支持" align="center" prop="supportName" width="120" />
      <el-table-column label="部门" align="center" prop="deptName" width="120" />
      <el-table-column label="合作状况" align="center" prop="statusName" width="100">
        <template #default="scope">
          <el-tag type="success">
            {{ cooperationOptions.find(o => o.dictValue === scope.row.status)?.dictLabel || scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button link type="primary" icon="StarFilled" @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-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="poolRef" :model="form" :rules="rules" label-width="120px">
        <!-- 第 1 排 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户编号" prop="customerNo">
              <el-input v-model="form.customerNo" placeholder="请输入客户编号" />
            </el-form-item>
          </el-col>
           <el-col :span="8">
            <el-form-item label="所属公司" prop="belongCompanyId">
              <el-select v-model="form.belongCompanyId" placeholder="请选择所属公司" 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-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="客户来源" prop="customerSourceId">
              <el-select v-model="form.customerSourceId" placeholder="请选择来源" style="width: 100%">
                <el-option v-for="item in sourceOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
             <el-form-item label="所属行业" prop="industryId">
              <el-select v-model="form.industryId" placeholder="请选择行业" 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="8">
            <el-form-item label="企业类型" prop="enterpriseTypeId">
              <el-select v-model="form.enterpriseTypeId" placeholder="请选择企业类型" style="width: 100%">
                <el-option v-for="item in corpTypeOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="企业规模" prop="enterpriseScaleId">
              <el-select v-model="form.enterpriseScaleId" placeholder="请选择企业规模" style="width: 100%">
                <el-option v-for="item in scaleOptions" :key="item.id" :label="item.enterpriseScaleName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户类别" prop="customerCategoryId">
              <el-select v-model="form.customerCategoryId" placeholder="请选择类别" style="width: 100%">
                <el-option v-for="item in categoryOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户等级" prop="customerLevelId">
              <el-select v-model="form.customerLevelId" placeholder="请选择等级" 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-divider content-position="left">联系信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="固定电话" prop="telephone">
              <el-input v-model="form.telephone" placeholder="请输入固定电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="传真" prop="fax">
              <el-input v-model="form.fax" placeholder="请输入传真" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="网址" prop="website">
              <el-input v-model="form.website" placeholder="请输入网址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="邮政编码" prop="zipCode">
              <el-input v-model="form.zipCode" placeholder="请输入邮政编码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="省市区" prop="provinceId">
              <el-cascader
                v-model="regionArr"
                :options="regionOptions"
                placeholder="请选择"
                style="width: 100%"
                @change="handleRegionChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="详细地址" prop="detailAddress">
              <el-input v-model="form.detailAddress" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">销售信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="负责人" prop="managerId">
              <el-select v-model="form.managerId" placeholder="请选择业务负责人" clearable filterable 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="8">
            <el-form-item label="客服支持" prop="supportId">
              <el-select v-model="form.supportId" placeholder="请选择客服支持" clearable filterable 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="8">
            <el-form-item label="采购规模" prop="procurementScale">
              <el-input v-model="form.procurementScale" placeholder="请输入采购规模">
                <template #append>万</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="销售目标" prop="salesTarget">
              <el-input v-model="form.salesTarget" placeholder="请输入销售目标">
                <template #append>万</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合作状况" prop="status">
              <el-select v-model="form.status" placeholder="请选择合作状况" style="width: 100%">
                <el-option v-for="item in cooperationOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </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="2" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listPool, claimPool, addPool, updatePool, getPool } from "@/api/customer/customerPool";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import { listEnterpriseScale } from "@/api/customer/enterpriseScale";
import { listDictByType } from "@/api/customer/customerDict";
import { listLevel } from "@/api/customer/customerLevel";
import { selectStaffOptionList } from "@/api/customer/crmStaff";
import { listCompany } from "@/api/system/company";

const { proxy } = getCurrentInstance();

const poolList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const open = ref(false);
const title = ref("");

// 地区数据（示例数据，生产环境下应通过接口获查询）
const regionArr = ref([]);
const regionOptions = ref([
  { value: 1000, label: '广东省', children: [
    { value: 1001, label: '深圳市', children: [
      { value: 10011, label: '南山区' }
    ]}
  ]}
]);

// 下拉选项数据
const industryOptions = ref([]);
const scaleOptions = ref([]);
const sourceOptions = ref([]);
const levelOptions = ref([]);
const corpTypeOptions = ref([]);
const staffOptions = ref([]);
const categoryOptions = ref([]);
const cooperationOptions = ref([]);
const companyOptions = ref([]);

/** 加载选项数据 */
const getOptions = () => {
  listIndustryCategory().then(r => industryOptions.value = r.data).catch(() => {});
  listEnterpriseScale().then(r => scaleOptions.value = r.data).catch(() => {});
  listDictByType("source").then(r => sourceOptions.value = r.data).catch(() => {});
  listLevel().then(r => levelOptions.value = r.rows).catch(() => {});
  listDictByType("enterprise_type").then(r => corpTypeOptions.value = r.data).catch(() => {});
  listDictByType("category").then(r => categoryOptions.value = r.data).catch(() => {});
  // 查询合作状态字典（已合作/未合作）
  listDictByType("cooperation_status").then(r => cooperationOptions.value = r.data).catch(() => {});
  // 查询人员下拉选项，用于业务负责人和客服支持选择器
  selectStaffOptionList().then(res => {
    staffOptions.value = res.data;
  }).catch(() => {});
  // 查询所属公司列表
  listCompany().then(r => companyOptions.value = r.rows || r.data || []).catch(() => {});
};
getOptions();

const data = reactive({
  form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      customerNo: undefined,
      customerName: undefined,
      customerLevelId: undefined,
      industryId: undefined,
      managerId: undefined,
      supportId: undefined,
      deptId: undefined,
      status: undefined,
      enterpriseTypeId: undefined,
    },
  rules: {
    customerName: [
      { required: true, message: "客户名称不能为空", trigger: "blur" }
    ]
  }
});

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


/** 查询客户公海列表 */
function getList() {
  loading.value = true;
  listPool(queryParams.value).then(response => {
    poolList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增客户公海";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getPool(id).then(response => {
    form.value = response.data;
    // 回显省市区
    if (form.value.provinceId && form.value.cityId && form.value.districtId) {
      regionArr.value = [form.value.provinceId, form.value.cityId, form.value.districtId];
    }
    open.value = true;
    title.value = "修改客户公海";
  }).catch(() => {});
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    customerNo: undefined,
    customerName: undefined,
    belongCompanyId: undefined,
    customerSourceId: undefined,
    enterpriseTypeId: undefined,
    enterpriseScaleId: undefined,
    customerCategoryId: undefined,
    industryId: undefined,
    customerLevelId: undefined,
    managerId: undefined,
    supportId: undefined,
    deptId: undefined,
    status: '1',  // 默认未合作
    telephone: undefined,
    fax: undefined,
    website: undefined,
    email: undefined,
    zipCode: undefined,
    provinceId: undefined,
    cityId: undefined,
    districtId: undefined,
    detailAddress: undefined,
    procurementScale: undefined,
    salesTarget: undefined,
    remark: undefined
  };
  regionArr.value = [];
  proxy.resetForm("poolRef");
}

/** 处理地区选择变更 */
function handleRegionChange(val) {
  if (val && val.length === 3) {
    form.value.provinceId = val[0];
    form.value.cityId = val[1];
    form.value.districtId = val[2];
  } else {
    form.value.provinceId = undefined;
    form.value.cityId = undefined;
    form.value.districtId = undefined;
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["poolRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePool(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(() => {});
      } else {
        addPool(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(() => {});
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 详情按钮操作 */
function handleDetail(row) {
  // 跳转到客户公海详情页
  proxy.$router.push({ name: 'CustomerPoolDetail', params: { id: row.id } });
}

/** 认领按钮操作 */
function handleClaim(row) {
  proxy.$modal.confirm('是否确定认领该客户：“' + row.customerName + '”？').then(function() {
    return claimPool(row.id);
  }).then(() => {
    proxy.$modal.msgSuccess("认领成功");
    getList();
  }).catch(() => {});
}

getList();
</script>

<style lang="scss" scoped>
.customer-name-link {
  color: #ff6600; /* 橙红色风格 */
  font-weight: 500;
  cursor: pointer;
}
.search-form {
  margin-bottom: 20px;
}
:deep(.el-divider__text) {
  font-weight: bold;
  font-size: 14px;
  color: #333;
}
</style>
