<template>
  <div class="app-container">
    <el-card shadow="never" class="search-card" :body-style="{ padding: '15px 20px 5px' }">
      <el-form :model="queryParams" ref="queryRef" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="所属公司" prop="companyNo">
              <el-select v-model="queryParams.companyNo" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in companyOptions" :key="item.companyCode" :label="item.companyName" :value="item.companyCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称" prop="customerName">
              <el-select 
                v-model="queryParams.customerName" 
                placeholder="请输入客户关键字" 
                style="width: 100%" 
                clearable 
                filterable
              >
                <el-option v-for="item in localCustomerOptions" :key="item.customerNo" :label="item.customerName" :value="item.customerName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="负责人" prop="leader">
              <el-select v-model="queryParams.leader" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in userOptions" :key="item.staffId" :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName" :value="item.staffId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-top: 5px;">
          <el-col :span="6">
            <el-form-item label="部门" prop="deptNo">
              <el-tree-select
                v-model="queryParams.deptNo"
                :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="所属部门"
                check-strictly
                style="width: 100%"
                clearable
                filterable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品支持" prop="productSupport">
              <el-select v-model="queryParams.productSupport" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in userOptions" :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="status">
              <el-select v-model="queryParams.status" style="width: 100%" clearable>
                <el-option v-for="item in saleStatusOptions" :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="timeType">
              <el-select v-model="queryParams.timeType" style="width: 100%" clearable>
                <el-option v-for="item in timeTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-top: 5px;">
          <el-col :span="7">
            <el-form-item label="时间范围" prop="dateRange">
              <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="17">
            <el-form-item label-width="0">
              <div class="search-btns">
                <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-new">新增</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="table-card">
      <div class="summary-stripe-inner">
        <div class="stripe-left">
          <span class="stripe-title">销售线索信息列表</span>
          <span class="stripe-total"><span class="total-label">金额总计</span><span class="red-text">{{ totalAmount.toFixed(2) }}</span> (万)</span>
        </div>
        <div class="stripe-actions">
          <el-button type="primary" size="small" :disabled="ids.length === 0" icon="Switch" @click="handleTransfer">转移给他人</el-button>
          <el-button type="primary" size="small" :disabled="ids.length === 0" icon="Link" @click="handleBatchClaim">批量认领</el-button>
        </div>
      </div>

      <el-table ref="leadsTable" v-loading="loading" :data="leadsList" border class="standard-table" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" fixed />
        
        <!-- 1. 项目名称 -->
        <el-table-column label="项目名称" align="center" min-width="180" show-overflow-tooltip fixed>
          <template #default="scope">
            <span class="project-name-link" @click="handleDetail(scope.row)">{{ scope.row.projectName }}</span>
          </template>
        </el-table-column>

        <!-- 2. 采购内容 -->
        <el-table-column label="采购内容" align="center" prop="purchaseContent" min-width="200" show-overflow-tooltip />

        <!-- 3. 所属公司 -->
        <el-table-column label="所属公司" align="center" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            {{ companyOptions.find(i => i.companyCode == scope.row.companyNo)?.companyName || scope.row.companyNo }}
          </template>
        </el-table-column>

        <!-- 4. 客户名称 -->
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="150" show-overflow-tooltip />

        <!-- 5. 行业 -->
        <el-table-column label="行业" align="center" width="120" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.professionName || industryOptions.find(i => String(i.id) === String(scope.row.profession))?.industryCategoryName || scope.row.profession }}
          </template>
        </el-table-column>

        <!-- 6. 部门 -->
        <el-table-column label="部门" align="center" prop="deptName" width="120" show-overflow-tooltip />

        <!-- 7. 金额（万） -->
        <el-table-column label="金额(万)" align="center" prop="projectBudget" width="100" sortable>
          <template #default="scope"><span>{{ Number(scope.row.projectBudget || 0).toFixed(2) }}</span></template>
        </el-table-column>

        <!-- 8. 赢单率（%） -->
        <el-table-column label="赢单率(%)" align="center" width="100">
          <template #default="scope">
            {{ scope.row.winRate ? scope.row.winRate + '%' : '' }}
          </template>
        </el-table-column>

        <!-- 9. 项目级别 -->
        <el-table-column label="项目级别" align="center" width="100">
          <template #default="scope">
            {{ projectLevelOptions.find(i => i.value == scope.row.projectLevel)?.label || scope.row.projectLevel }}
          </template>
        </el-table-column>

        <!-- 10. 项目负责人 -->
        <el-table-column label="项目负责人" align="center" prop="leaderName" width="110">
          <template #default="scope">
            <span>{{ scope.row.leaderName || findUserName(scope.row.leader) }}</span>
          </template>
        </el-table-column>
        
        <!-- 11. 产品支持 -->
        <el-table-column label="产品支持" align="center" prop="productSupportName" width="110">
          <template #default="scope">
            <span>{{ scope.row.productSupportName || findUserName(scope.row.productSupport) }}</span>
          </template>
        </el-table-column>

        <!-- 12. 创建时间 -->
        <el-table-column label="创建时间" align="center" prop="createTime" width="110">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>

        <!-- 13. 立项时间 -->
        <el-table-column label="立项时间" align="center" prop="approvalDate" width="110">
          <template #default="scope">
            <span>{{ parseTime(scope.row.approvalDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>

        <!-- 14. 成单时间 -->
        <el-table-column label="成单时间" align="center" prop="expectedCompletionTime" width="110">
          <template #default="scope">
            <span>{{ parseTime(scope.row.expectedCompletionTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>

        <!-- 15. 项目状态 -->
        <el-table-column label="项目状态" align="center" prop="statusName" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'primary'">
              {{ scope.row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #default="scope">
            <el-button link type="info" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link type="primary" @click="handleClaim(scope.row)">认领</el-button>
            <el-button link type="danger" @click="handleDelete(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>

    <!-- 弹窗组件 -->
    <LeadsAdd 
      v-model="addVisible" 
      :company-options="companyOptions" 
      :customer-options="customerOptions" 
      :user-options="userOptions" 
      :project-level-options="projectLevelOptions" 
      :procurement-method-options="procurementMethodOptions" 
      :info-source-options="infoSourceOptions" 
      :industry-options="industryOptions"
      @success="getList" 
    />
    <LeadsEdit 
      v-model="editVisible" 
      :id="currentId"
      :company-options="companyOptions" 
      :customer-options="customerOptions" 
      :user-options="userOptions" 
      :project-level-options="projectLevelOptions" 
      :procurement-method-options="procurementMethodOptions" 
      :info-source-options="infoSourceOptions" 
      :industry-options="industryOptions"
      :marketing-activity-options="marketingActivityOptions"
      @success="getList" 
    />
    <LeadsDetail 
      ref="leadsDetailRef"
      v-model="detailVisible" 
      :id="currentId"
      :info-data="currentRow"
      :sale-status-options="saleStatusOptions"
      :company-options="companyOptions"
      :industry-options="industryOptions"
      :project-level-options="projectLevelOptions"
      :procurement-method-options="procurementMethodOptions"
      :info-source-options="infoSourceOptions"
      :user-options="userOptions"
      @edit="onDetailEdit"
    />

    <!-- 转移对话框 -->
    <el-dialog title="是否将选中的项目线索转移给其他负责人？" v-model="transferVisible" width="500px" append-to-body>
      <el-form :model="transferForm" label-width="100px" style="padding: 10px 20px 0;">
        <el-form-item label="新负责人" required>
          <el-select v-model="transferForm.newOwner" placeholder="请选择" style="width:100%" filterable>
            <el-option v-for="u in userOptions" :key="u.staffId" :label="(u.staffCode ? '(' + u.staffCode + ') ' : '') + u.staffName" :value="u.staffId" />
          </el-select>
        </el-form-item>
        <el-form-item label-width="100px">
          <el-checkbox v-model="transferForm.keepAsTeamMember">保留【负责人】为销售机会团队成员</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="padding-top: 10px;">
          <el-button type="primary" @click="submitTransfer" style="background-color: #40a9ff; border-color: #40a9ff;">确 认</el-button>
          <el-button @click="transferVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 认领对话框 -->
    <el-dialog v-model="claimOpen" title="您正在认领销售线索，请分配销售线索认领信息" width="500px" append-to-body>
      <el-form :model="claimForm" label-width="150px">
        <el-form-item label="项目负责人" required>
          <el-select v-model="claimForm.leader" filterable placeholder="请选择" style="width: 100%">
            <el-option v-for="item in computedClaimUserOptions" :key="item.staffId" :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName" :value="item.staffId" />
          </el-select>
        </el-form-item>

        <el-form-item label="产品支持" required>
          <el-select v-model="claimForm.productSupport" filterable placeholder="请选择" style="width: 100%">
            <el-option v-for="item in userOptions" :key="item.staffId" :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName" :value="item.staffId" />
          </el-select>
        </el-form-item>

        <el-form-item label="保留已有项目负责人" required>
          <el-radio-group v-model="claimForm.keepOldManager">
            <el-radio :value="true">是</el-radio>
            <el-radio :value="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <div style="margin-left: 30px; color: #909399; font-size: 13px; margin-top: 20px;">
          <el-icon style="vertical-align: middle; margin-right: 4px;"><InfoFilled /></el-icon>
          <span>销售线索认领后将转到项目商机。</span>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="padding-top: 10px;">
          <el-button type="primary" @click="submitClaim" style="background-color: #40a9ff; border-color: #40a9ff;">确 认</el-button>
          <el-button @click="claimOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SalesLeads">
import { ref, reactive, onMounted, computed, getCurrentInstance, toRefs } from 'vue';
import { listLeads, delLeads, transferLeads, claimLeads } from '@/api/saleManage/leads/index';
import { listComStaff } from "@/api/system/comStaff/index";
import { listCompanyOption, listCustomerInfo } from "@/api/customer/customerInfo/index";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import { deptTreeSelect } from "@/api/system/user";
import { Search, Refresh, Plus, Switch, Link, InfoFilled } from '@element-plus/icons-vue';
import { useUserStore } from "@/store/modules/user";

import LeadsAdd from './add.vue';
import LeadsEdit from './edit.vue';
import LeadsDetail from './detail.vue';

const leadsDetailRef = ref(null);

const proxy = getCurrentInstance().proxy;
const loading = ref(false);
const total = ref(0);
const leadsList = ref([]);
const totalAmount = ref(0);
const ids = ref([]);
const dateRange = ref([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  status: '1',
  companyNo: undefined,
  projectName: undefined,
  customerName: undefined,
  leader: undefined,
  deptNo: undefined,
  productSupport: undefined,
  timeType: '1'
});
const companyOptions = ref([]);
const userOptions = ref([]);
const claimOpen = ref(false);
const claimForm = reactive({
  ids: [],
  leader: undefined,
  currentLeaderName: '',
  keepOldManager: false,
  productSupport: undefined,
  productSupportName: ''
});
const userStore = useUserStore();
const { 
  J0001: saleStatusOptions, 
  time_query_type: timeTypeOptions, 
  L0001: projectLevelOptions, 
  X0001: procurementMethodOptions, 
  X0002: infoSourceOptions 
} = toRefs(reactive(proxy.useDict('J0001', 'time_query_type', 'L0001', 'X0001', 'X0002')));
const customerOptions = ref([]);
const industryOptions = ref([]);
const marketingActivityOptions = ref([]);
const deptOptions = ref([]);

const customerLoading = ref(false);
const localCustomerOptions = ref([]);

const addVisible = ref(false);
const editVisible = ref(false);
const detailVisible = ref(false);
const currentId = ref(undefined);
const currentRow = ref({});

const transferVisible = ref(false);
const transferForm = reactive({ 
  newOwner: '',
  keepAsTeamMember: false
});

// 【修复回显】认领弹窗的负责人选项，确保当前用户或选定负责人在列表中，防止回显 ID
const computedClaimUserOptions = computed(() => {
  // 过滤掉当前登录用户
  let options = userOptions.value.filter(i => String(i.staffId) !== String(userStore.userId));
  
  if (claimForm.leader) {
    const exists = options.some(i => String(i.staffId) === String(claimForm.leader));
    if (!exists) {
      // 只有当选中的负责人不是当前用户时，才手动添加一项以保证姓名回显
      if (String(claimForm.leader) !== String(userStore.userId)) {
        const name = claimForm.currentLeaderName || '未知负责人';
        options.unshift({ staffId: String(claimForm.leader), staffName: name });
      }
    }
  }
  return options;
});

// 联动逻辑：当选择保留已有负责人时，自动切回原负责人 ID
watch(() => claimForm.keepOldManager, (val) => {
  if (val && claimForm.ids.length === 1) {
    // 单个认领时，如果选“是”，则强制回显原负责人
    const row = leadsList.value.find(i => i.id === claimForm.ids[0]);
    if (row && row.leader) {
      claimForm.leader = String(row.leader);
      claimForm.currentLeaderName = row.leaderName || '';
    }
  } else if (!val) {
    // 选“否”时不再默认设为自己
    claimForm.leader = undefined;
  }
});

onMounted(() => {
  getDicts();
  getList();
  remoteLoadCustomers(''); // 初始化加载一部分客户
});

const getDicts = () => {
  listCompanyOption().then(res => companyOptions.value = res.data.map(i => ({ ...i, companyCode: String(i.companyCode) })));
  listComStaff({ pageSize: 1000 }).then(res => {
    const list = res.rows || res.data || [];
    userOptions.value = list.map(i => ({ ...i, staffId: String(i.staffId) }));
  });
  listIndustryCategory().then(res => industryOptions.value = res.data || res.rows || []);
  deptTreeSelect().then(res => deptOptions.value = res.data);
};

const remoteLoadCustomers = (query) => {
  customerLoading.value = true;
  listCustomerInfo({ pageNum: 1, pageSize: 500, isHighSeas: 'all' }).then(res => {
    const list = res.rows || [];
    localCustomerOptions.value = list.map(i => ({ ...i, customerNo: String(i.customerNo) }));
  }).finally(() => {
    customerLoading.value = false;
  });
};

const getList = () => {
  loading.value = true;
  listLeads(proxy.addDateRange(queryParams, dateRange.value)).then(res => {
    leadsList.value = res.rows || [];
    total.value = res.total || 0;
    totalAmount.value = leadsList.value.reduce((acc, cur) => acc + (Number(cur.projectBudget) || 0), 0);
  }).finally(() => { loading.value = false; });
};

const handleQuery = () => { queryParams.pageNum = 1; getList(); };
const resetQuery = () => {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
};
const handleSelectionChange = (selection) => { ids.value = selection.map(item => item.id); };

const handleAdd = () => { addVisible.value = true; };
const handleUpdate = (row) => { currentId.value = row.id; editVisible.value = true; };
const handleDetail = (row) => { currentId.value = row.id; currentRow.value = row; detailVisible.value = true; };
const onDetailEdit = (form) => { detailVisible.value = false; currentId.value = form.id; editVisible.value = true; };

const handleDelete = (row) => {
  const deleteIds = row.id || ids.value;
  proxy.$modal.confirm('确认删除吗？').then(() => {
    delLeads(deleteIds).then(() => { getList(); proxy.$modal.msgSuccess("删除成功"); });
  });
};

const handleTransfer = () => { 
  transferForm.newOwner = '';
  transferForm.keepAsTeamMember = false;
  transferVisible.value = true; 
};
const submitTransfer = () => {
  if (!transferForm.newOwner) {
    proxy.$modal.msgError("请选择新负责人");
    return;
  }
  const leaderName = userOptions.value.find(i => i.staffId == transferForm.newOwner)?.staffName;
  transferLeads({ 
    ids: ids.value, 
    leader: transferForm.newOwner,
    leaderName: leaderName,
    keepAsTeamMember: transferForm.keepAsTeamMember 
  }).then(() => {
    proxy.$modal.msgSuccess("转移成功");
    transferVisible.value = false;
    getList();
  });
};

const handleBatchClaim = () => {
  if (ids.value.length === 0) {
    proxy.$modal.msgWarning("请至少选择一条线索进行认领");
    return;
  }
  claimForm.ids = ids.value;
  claimForm.leader = undefined; // 不再默认回显自己
  claimForm.currentLeaderName = '';
  claimForm.keepOldManager = false;
  claimForm.productSupport = undefined;
  claimForm.productSupportName = '';
  claimOpen.value = true;
};

const handleClaim = (row) => {
  claimForm.ids = [row.id];
  // 如果原负责人是自己，则默认设为空，否则回显原负责人
  const isSelf = String(row.leader) === String(userStore.userId);
  claimForm.leader = (row.leader && !isSelf) ? String(row.leader) : undefined;
  claimForm.currentLeaderName = isSelf ? '' : (row.leaderName || '');
  claimForm.keepOldManager = false;
  claimForm.productSupport = row.productSupport ? String(row.productSupport) : undefined;
  claimForm.productSupportName = row.productSupportName || findUserName(row.productSupport) || '';
  claimOpen.value = true;
};



const submitClaim = () => {
  if (!claimForm.leader) {
    proxy.$modal.msgError("请选择项目负责人");
    return;
  }
  if (!claimForm.productSupport) {
    proxy.$modal.msgError("请选择产品支持");
    return;
  }
  const leaderName = computedClaimUserOptions.value.find(i => String(i.staffId) === String(claimForm.leader))?.staffName;
  const productSupportName = userOptions.value.find(i => String(i.staffId) === String(claimForm.productSupport))?.staffName;
  const params = {
    ...claimForm,
    leaderName,
    productSupportName,
    // 兼容性字段补全
    leaderId: claimForm.leader,
    managerId: claimForm.leader,
    salesPersonId: claimForm.leader, // 增加备选名
    clueIds: claimForm.ids,
    idList: claimForm.ids,
    // 如果是单条认领，带上单条 id
    id: claimForm.ids.length === 1 ? claimForm.ids[0] : undefined,
    clueId: claimForm.ids.length === 1 ? claimForm.ids[0] : undefined,
    // 转换布尔值为数值型或字符串，Ruoyi 后端通常接收 0/1 或 '0'/'1'
    keepOldManager: claimForm.keepOldManager ? 1 : 0,
    keepOwner: claimForm.keepOldManager ? '1' : '0'
  };
  
  claimLeads(params).then(() => {
    proxy.$modal.msgSuccess("认领成功");
    claimOpen.value = false;
    getList();
  });
};

const findUserName = (id) => {
  if (!id) return '';
  const user = userOptions.value.find(u => String(u.staffId || u.userId) === String(id));
  return user ? (user.staffName || user.nickName) : id;
};
</script>

<style scoped lang="scss">
.app-container { background-color: #f0f2f5; padding: 20px; min-height: calc(100vh - 84px); }
.search-card {
  margin-bottom: 15px;
  :deep(.el-form-item) {
    margin-bottom: 10px;
  }
  :deep(.el-form-item__label) {
    font-weight: normal;
  }
}
.search-btns {
  text-align: right;
  .el-button {
    font-weight: normal;
  }
}
.summary-stripe-inner {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0 15px 0;
  .stripe-title {
    font-weight: normal;
    font-size: 15px;
  }
  .stripe-total {
    font-weight: normal;
    margin-left: 20px;
  }
  .red-text {
    color: #f5222d;
    font-weight: normal;
    margin: 0 4px;
  }
}
.table-card {
  border: none;
}
.standard-table {
  :deep(th.el-table__cell) {
    font-weight: normal;
    color: #333;
  }
}
.project-name-link {
  color: #409eff;
  cursor: pointer;
}
</style>
