<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="title-container">
      <span class="list-title">拜访日程信息列表</span>
    </div>

    <!-- 列表区域 -->
    <el-card shadow="never" class="table-card">
      <el-table v-loading="loading" :data="dataList" border class="custom-table" :header-cell-style="{ background: '#f8fafc', color: '#333' }">
        <el-table-column label="日程编号" align="center" prop="scheduleNo" width="160">
          <template #default="scope">
            <span class="link-text" @click="handleDetail(scope.row)">{{ scope.row.scheduleNo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="关联计划" align="center" prop="planNo" width="160" />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="200" show-overflow-tooltip />
        <el-table-column label="拜访人" align="center" prop="callPeopleName" width="100">
          <template #default="scope">
            <span>{{ staffOptions.find(s => String(s.staffId) === String(scope.row.callPeopleNo || scope.row.callPeopleName))?.staffName || scope.row.callPeopleName || '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="拜访日期" align="center" prop="callDate" width="120" >
          <template #default="scope">
            <span>{{ parseTime(scope.row.callDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="随访人" align="center" prop="followPeopleName" width="120" />
        <el-table-column label="关联对象" align="center" prop="objectName" width="180" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.objectName || scope.row.customerName || '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="scheduleStatus" width="100">
          <template #default="scope">
            <el-tag :type="String(scope.row.scheduleStatus) === '0' ? 'warning' : (String(scope.row.scheduleStatus) === '1' ? 'success' : 'danger')">
              {{ scheduleStatusOptions.find(d => String(d.value) === String(scope.row.scheduleStatus))?.label || (String(scope.row.scheduleStatus) === '0' ? '未执行' : (String(scope.row.scheduleStatus) === '1' ? '已执行' : '放弃执行')) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关联类型" align="center" prop="relevanceType" width="100">
          <template #default="scope">
            {{ relevanceOptions.find(d => String(d.value) === String(scope.row.relevanceType))?.label || (String(scope.row.relevanceType) === '0' ? '客户' : (String(scope.row.relevanceType) === '1' ? '项目' : '供应商')) }}
          </template>
        </el-table-column>
        <el-table-column label="重要级别" align="center" prop="importantLevel" width="100">
          <template #default="scope">
            <span>{{ importanceOptions.find(d => String(d.value) === String(scope.row.importantLevel))?.label || scope.row.importantLevel || '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['visit:routine:edit']">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['visit:routine:remove']">删除</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 { selectStaffOptionList } from "@/api/customer/crmStaff";
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 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 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 = () => {
  selectStaffOptionList().then(res => { staffOptions.value = res.data || []; });
};

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