<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="card-title">{{ customerName }} - 市场交流出差记录</span>
          <el-button type="primary" plain icon="Back" @click="goBack">返回客户列表</el-button>
        </div>
      </template>

      <!-- 筛选表单 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="margin-bottom: 15px">
        <el-form-item label="申请人" prop="applicantId">
          <el-select v-model="queryParams.applicantId" placeholder="请选择申请人" clearable filterable style="width: 200px">
            <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="出差日期" prop="dateRange">
          <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" border :data="tripList">
        <el-table-column label="申请编号" align="center" prop="applyCode" width="140" />
        <el-table-column label="申请人" align="center" prop="applicantName" width="100" />
        <el-table-column label="部门" align="center" prop="deptName" width="120" />
        <el-table-column label="出差地点" align="center" prop="tripLocation" width="150" />
        <el-table-column label="开始日期" align="center" prop="startTime" width="110">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束日期" align="center" prop="endTime" width="110">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时长(天)" align="center" prop="durationDays" width="80" />
        <el-table-column label="业务方向" align="center" prop="businessDirection" width="120">
          <template #default="scope">
            <dict-tag :options="business_direction" :value="scope.row.businessDirection" />
          </template>
        </el-table-column>
        <el-table-column label="交流目的" align="center" prop="exchangePurpose" width="150" show-overflow-tooltip />
        <el-table-column label="交流过程简述" align="center" prop="exchangeProcess" width="200" show-overflow-tooltip />
        <el-table-column label="结果反馈" align="center" prop="feedback" width="200" show-overflow-tooltip />
        <!-- <el-table-column label="流程状态" align="center" prop="flowStatus" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.flowStatus === 'finish'" type="success">已完成</el-tag>
            <el-tag v-else-if="scope.row.flowStatus === 'running'" type="warning">审批中</el-tag>
            <el-tag v-else-if="scope.row.flowStatus === 'draft'" type="info">草稿</el-tag>
            <el-tag v-else-if="scope.row.flowStatus === 'back'" type="danger">已退回</el-tag>
            <el-tag v-else type="info">{{ scope.row.flowStatus }}</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="备注" align="center" prop="remark" width="200" show-overflow-tooltip />
        <el-table-column label="操作" align="center" fixed="right" width="100">
          <template #default="scope">
            <el-button link type="primary" @click="handleView(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>
  </div>
</template>

<script setup name="CustomerTripHistory" lang="ts">
import { listBusinessTripApply } from '@/api/oa/crm/businessTripApply';
import { BusinessTripApplyVO } from '@/api/oa/crm/businessTripApply/types';
import { getUserList } from '@/api/system/user';
import { UserVO } from '@/api/system/user/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();
const { business_direction } = toRefs<any>(proxy?.useDict('business_direction'));

const loading = ref(false);
const tripList = ref<BusinessTripApplyVO[]>([]);
const total = ref(0);
const customerId = ref<string | number>('');
const customerName = ref<string>('');
const dateRange = ref<string[]>([]);
const queryFormRef = ref<ElFormInstance>();
const userList = ref<UserVO[]>([]);

const queryParams = ref({
  pageNum: 1,
  pageSize: 20,
  tripType: '2', // 市场交流类型
  customerId: undefined as string | number | undefined,
  applicantId: undefined as string | number | undefined,
  startTime: undefined as string | undefined,
  endTime: undefined as string | undefined
});

/** 获取出差记录列表 */
const getList = async () => {
  loading.value = true;
  try {
    // 处理日期范围参数
    if (dateRange.value && dateRange.value.length === 2) {
      queryParams.value.startTime = dateRange.value[0];
      queryParams.value.endTime = dateRange.value[1];
    } else {
      queryParams.value.startTime = undefined;
      queryParams.value.endTime = undefined;
    }
    const res = await listBusinessTripApply(queryParams.value);
    tripList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('查询出差记录失败:', error);
  } finally {
    loading.value = false;
  }
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  dateRange.value = [];
  queryParams.value.applicantId = undefined;
  queryParams.value.startTime = undefined;
  queryParams.value.endTime = undefined;
  handleQuery();
};

/** 查看详情 */
const handleView = (row: BusinessTripApplyVO) => {
  router.push({
    path: '/tripapply/businessTripApply/edit',
    query: {
      id: row.tripId,
      type: 'view'
    }
  });
};

/** 返回客户列表 */
const goBack = () => {
  router.push('/crm/customerInfo');
};

onMounted(async () => {
  // 加载用户列表
  const userRes = await getUserList(undefined);
  userList.value = userRes.data;
  // 获取路由参数
  customerId.value = route.query.customerId as string;
  customerName.value = (route.query.customerName as string) || '未知客户';
  queryParams.value.customerId = customerId.value;

  if (customerId.value) {
    getList();
  }
});
</script>
