<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryRef" inline label-width="80px">
        <el-form-item label="拜访人" prop="callPeopleName" class="custom-form-item">
          <el-input v-model="queryParams.callPeopleName" placeholder="请输入拜访人" clearable />
        </el-form-item>
        <el-form-item label="拜访日期" prop="callDate" class="custom-form-item">
          <el-date-picker v-model="queryParams.callDate" type="date" placeholder="请选择" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="日程状态" prop="scheduleStatus" class="custom-form-item">
          <el-select v-model="queryParams.scheduleStatus" placeholder="请选择" clearable>
            <el-option
              v-for="dict in scheduleStatusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <div class="search-btns-area">
          <el-button icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['visit:routine:add']">新增</el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 列表标题 -->
    <div class="filter-action-bar">
      <div class="page-title">拜访日程信息列表</div>
    </div>

    <!-- 列表区域 -->
    <el-card shadow="never" class="table-card">
      <el-table v-loading="loading" :data="dataList" border class="standard-table">
        <el-table-column label="日程编号" align="center" width="140" fixed>
          <template #default="scope">
            <span class="link-text-emphasize" @click="handleDetail(scope.row)">{{ scope.row.scheduleNo?.replace('RC', '') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="关联计划" align="center" prop="planNo" width="140" show-overflow-tooltip />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="200" show-overflow-tooltip />
        <el-table-column label="拜访人" align="center" width="100">
          <template #default="scope">
            <span>{{ findStaffName(scope.row.callPeopleNo || scope.row.callPeopleName) }}</span>
          </template>
        </el-table-column>
        <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" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.followPeopleName || scope.row.followPeople || '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="关联对象" align="center" prop="objectName" width="160" show-overflow-tooltip />
        <el-table-column label="状态" align="center" width="90">
          <template #default="scope">
            <dict-tag :options="scheduleStatusOptions" :value="scope.row.scheduleStatus" />
          </template>
        </el-table-column>
        <el-table-column label="关联类型" align="center" width="100">
           <template #default="scope">
             <span>{{ String(scope.row.relevanceType) === '0' ? '客户' : (String(scope.row.relevanceType) === '1' ? '项目商机' : '年度入围') }}</span>
           </template>
        </el-table-column>
        <el-table-column label="紧要程度" align="center" width="100">
          <template #default="scope">
            <dict-tag :options="importanceOptions" :value="scope.row.importantLevel" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #header>
            <div class="op-header">
              <span>操作</span>
              <el-icon class="setting-icon"><Setting /></el-icon>
            </div>
          </template>
          <template #default="scope">
            <el-button link class="op-btn" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link class="op-btn" @click="handleUpdate(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>

    <!-- 新增组件 -->
    <AddRoutine v-model="addOpen" @success="getList" />
    
    <!-- 编辑组件 -->
    <EditRoutine v-model="editOpen" :id="activeId" @success="getList" />
    
    <!-- 详情组件 -->
    <DetailRoutine v-model="detailOpen" :id="activeId" />
  </div>
</template>

<script setup name="VisitRoutine">
import { ref, reactive, onMounted, getCurrentInstance, toRefs } from 'vue';
import { listRoutine, delRoutine } from "@/api/visit/routine";
import { listComStaff } from "@/api/system/comStaff/index";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import { listCustomerInfo } from "@/api/customer/customerInfo/index";
import { Setting } from '@element-plus/icons-vue';
import AddRoutine from './add.vue';
import EditRoutine from './edit.vue';
import DetailRoutine from './detail.vue';

const proxy = getCurrentInstance().proxy;
const { 
  importance_level: importanceOptions, 
  schedule_status: scheduleStatusOptions, 
  relevance_type: relevanceOptions 
} = toRefs(reactive(proxy.useDict("importance_level", "schedule_status", "relevance_type")));

const staffOptions = ref([]);
const industryOptions = ref([]);
const customerList = ref([]);

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

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  callPeopleName: undefined,
  callDate: undefined,
  scheduleStatus: undefined,
  orderByColumn: 'createTime',
  isAsc: 'desc'
});

const addOpen = ref(false);
const editOpen = ref(false);
const detailOpen = ref(false);
const activeId = ref(null);

const getList = () => {
  loading.value = true;
  listRoutine(queryParams).then(response => {
    dataList.value = response.rows || [];
    total.value = response.total || 0;
    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 findStaffDept = (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.deptName : '';
};

// 通过客户名称/编号反查行业和业务员
const findCustomerAttr = (row, attr) => {
  const customerName = row.customerName;
  const customerNo = row.customerNo;
  if (!customerName && !customerNo) return '';
  
  const customer = customerList.value.find(c => 
    (customerNo && String(c.customerNo) === String(customerNo)) || 
    (customerName && c.customerName === customerName)
  );
  if (!customer) return '';
  
  if (attr === 'industry') {
    return customer.industryName || customer.industryCategory || '';
  }
  if (attr === 'salesman') {
    return customer.salesPersonName || customer.leaderName || customer.salesman || '';
  }
  return '';
};

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

const resetQuery = () => {
  if (queryRef.value) {
    queryRef.value.resetFields();
  }
  handleQuery();
};

const handleAdd = () => {
  addOpen.value = true;
};

const handleUpdate = (row) => {
  activeId.value = row.id;
  editOpen.value = true;
};

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

const handleDelete = (row) => {
  const ids = row.id;
  const scheduleNo = row.scheduleNo || ids;
  proxy.$modal.confirm(`确认删除日程编号为"${scheduleNo}"的数据项吗？`).then(() => {
    return delRoutine(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};

const getOptions = () => {
  listComStaff({ pageSize: 1000 }).then(res => { staffOptions.value = res.rows || res.data || []; });
  listIndustryCategory({ pageSize: 1000 }).then(res => { industryOptions.value = res.data || res.rows || []; });
  listCustomerInfo({ pageNum: 1, pageSize: 500, isHighSeas: 'all' }).then(res => { customerList.value = res.rows || []; });
};

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

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

.search-card {
  border: none;
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

:deep(.el-form--inline) {
  display: flex;
  align-items: center;
}

.custom-form-item {
  margin-bottom: 0 !important;
  margin-right: 0px;
  :deep(.el-form-item__label) {
    padding-right: 12px;
    color: #606266;
    font-weight: normal;
  }
  :deep(.el-input), :deep(.el-select), :deep(.el-date-editor) {
    width: 220px;
  }
}

.search-btns-area {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-container {
  padding: 15px 20px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  border-radius: 4px 4px 0 0;
  .list-title { font-size: 15px; color: #333; font-weight: normal; }
}

.table-card {
  border: none;
  border-radius: 0 0 4px 4px;
  :deep(.el-card__body) { padding: 10px 20px 20px; }
}

:deep(.el-table__header th .cell) {
  font-weight: normal;
}

:deep(.el-button--primary.is-link) {
  color: #409eff;
}
:deep(.el-button--danger.is-link) {
  color: #f56c6c;
}

.link-text { color: #409eff; cursor: pointer; }
.link-text-emphasize { color: #409eff; cursor: pointer; } /* 蓝色强调 */

.op-header {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  .setting-icon { font-size: 14px; cursor: pointer; color: #909399; }
}

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