<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryRef" inline label-width="70px">
        <el-form-item label="客户名称" prop="customerName" class="custom-form-item">
          <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable style="width: 240px" />
        </el-form-item>
        <el-form-item label="拜访人" prop="visitor" class="custom-form-item">
          <el-input v-model="queryParams.visitor" placeholder="请输入拜访人" clearable style="width: 240px" />
        </el-form-item>
        <el-form-item label="拜访日期" class="custom-form-item">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button icon="Search" @click="handleQuery" class="btn-search">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery" class="btn-reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表标题 -->
    <div class="filter-action-bar">
      <div class="page-title">跟进记录信息列表</div>
    </div>

    <!-- 表格区域 -->
    <el-card shadow="never" class="table-card">
      <el-table ref="tableRef" v-loading="loading" :data="dataList" border class="standard-table">
        <el-table-column label="编号" align="center" prop="recordsNo" width="140" fixed>
          <template #default="scope">
            <span class="link-text" @click="handleDetail(scope.row)">{{ scope.row.recordsNo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="250" show-overflow-tooltip />
        <el-table-column label="部门" align="center" width="120">
          <template #default="scope">
            <span>{{ scope.row.visitorDeptName || scope.row.deptName || scope.row.department || '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="行业" align="center" width="100">
          <template #default="scope">
            <span>{{ industryOptions.find(o => String(o.id) === String(scope.row.profession))?.industryCategoryName || scope.row.profession || '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="负责人" align="center" prop="salesman" width="100" show-overflow-tooltip />
        <el-table-column label="对象类型" align="center" width="120">
           <template #default="scope">
             <el-tag v-if="String(scope.row.dataType) === '1'" type="primary" size="small">项目商机</el-tag>
             <el-tag v-else-if="String(scope.row.dataType) === '2'" type="success" size="small">项目筛选</el-tag>
             <el-tag v-else-if="String(scope.row.dataType) === '3'" type="warning" size="small">年度入围</el-tag>
             <el-tag v-else type="info" size="small">通用</el-tag>
           </template>
        </el-table-column>
        <el-table-column label="拜访对象" align="center" prop="goalObject" width="160" show-overflow-tooltip />
        <el-table-column label="拜访人" align="center" width="100">
          <template #default="scope">
            <span>{{ findStaffName(scope.row.visitor || scope.row.visitorNo || scope.row.visitorName) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="随访人" align="center" prop="followPeopleName" width="100" />
        <el-table-column label="拜访日期" align="center" prop="callDate" width="110">
          <template #default="scope">
            <span>{{ parseTime(scope.row.callDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="scope">
            <el-button link class="op-btn" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link class="op-btn-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>

    <!-- 详情抽屉组件 -->
    <Detail v-model="detailOpen" :id="selectedId" />

  </div>
</template>

<script setup name="VisitRecord">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { listRecord, delRecord } from "@/api/visit/record";
import { listComStaff } from "@/api/system/comStaff/index";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import Detail from './detail.vue';

const proxy = getCurrentInstance().proxy;

const loading = ref(false);
const dataList = ref([]);
const total = ref(0);
const detailOpen = ref(false);
const selectedId = ref(null);
const staffOptions = ref([]);
const industryOptions = ref([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  recordsNo: undefined,
  customerName: undefined,
  visitor: undefined,
  callDate: undefined
});

const dateRange = ref([]);

const getList = () => {
  loading.value = true;
  let params = { ...queryParams };
  if (dateRange.value && dateRange.value.length === 2) {
    params.beginTime = dateRange.value[0];
    params.endTime = dateRange.value[1];
  }
  listRecord(params).then(response => {
    // 仅保留纯数字编号的记录，过滤掉带有 RC 前缀的日程同步数据
    dataList.value = (response.rows || []).filter(r => {
      const no = String(r.recordsNo || '');
      return !no || /^\d+$/.test(no);
    });
    total.value = dataList.value.length; // 注意：前端过滤后总数会变，如果后端不支持过滤建议这样处理或联系后端
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

const findStaffName = (val) => {
  if (!val) return '';
  const staff = staffOptions.value.find(s => String(s.staffId) === String(val) || String(s.userId) === String(val) || String(s.staffName) === String(val));
  return staff ? staff.staffName : val;
};

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

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

const handleDetail = (row) => {
  selectedId.value = row.id;
  detailOpen.value = true;
};

const handleDelete = (row) => {
  proxy.$modal.confirm(`确认删除数据?`).then(() => {
    return delRecord(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};

onMounted(() => { 
  getList(); 
  listComStaff({ pageSize: 1000 }).then(res => {
    staffOptions.value = res.rows || res.data || [];
  });
  
  listIndustryCategory().then(res => {
    const flatten = (list) => {
      let result = [];
      list.forEach(item => {
        result.push(item);
        if (item.children) result = result.concat(flatten(item.children));
      });
      return result;
    };
    industryOptions.value = flatten(res.data || res.rows || []);
  });
});
</script>

<style scoped lang="scss">
.app-container {
  padding: 10px 20px;
  background-color: #fcfcfc;
  min-height: calc(100vh - 84px);
}

/* 搜索栏样式重构 */
.search-card {
  border: none;
  background-color: #fff;
  :deep(.el-card__body) {
    padding: 15px 20px;
  }
  border-bottom: 1px solid #efefef;
  margin-bottom: 0;
}

.custom-form-item {
  margin-bottom: 10px !important;
  margin-right: 20px;
  :deep(.el-form-item__label) {
    font-size: 13px;
    color: #333;
    font-weight: normal; /* 不加粗 */
  }
  :deep(.el-input__wrapper) {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    height: 36px;
  }
}

.btn-search {
  background: #409eff;
  border: 1px solid #409eff;
  color: #fff;
  &:hover { background: #66b1ff; border-color: #66b1ff; }
}
.btn-reset {
  background: #fff;
  color: #333;
  border: 1px solid #dcdfe6;
  &:hover { background: #f5f7fa; }
}

/* 操作栏样式 */
.filter-action-bar {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 15px 20px;
  margin-bottom: 0;

  .page-title {
    font-size: 14px;
    color: #333;
    font-weight: normal; /* 不加粗 */
  }
}

/* 标准表格样式 */
.standard-table {
  width: 100%;
  :deep(.el-table__header-wrapper) {
    th {
      background-color: #f8fafc !important;
      color: #475569;
      font-weight: normal; /* 不加粗 */
      font-size: 13px;
      padding: 12px 0;
    }
  }
  :deep(.el-table__row) {
    td {
      padding: 10px 0;
      font-size: 13px;
      color: #1e293b;
    }
  }
}

/* 品牌蓝色记录编号链接 */
.link-text {
  color: #409eff;
  cursor: pointer;
  transition: all 0.2s;
  &:hover { 
    color: #66b1ff; 
    text-decoration: none; 
    opacity: 0.8; 
  }
}

.op-btn {
  color: #409eff;
  font-weight: normal;
  &:hover { opacity: 0.8; }
}

.op-btn-danger {
  color: #f56c6c;
  font-weight: normal;
  margin-left: 12px;
  &:hover { opacity: 0.8; }
}

.table-card {
  border: none;
  background-color: #fff;
  :deep(.el-card__body) {
    padding: 10px 20px 0px;
  }
}

:deep(.pagination-container) {
  margin-top: 0px !important;
  padding: 10px 0 !important;
  background-color: transparent;
}
</style>
