<template>
  <div class="app-container">
    <el-card shadow="never" class="search-card" style="min-width: 1600px !important; width: 100% !important;">
      <!-- 搜索条件 -->
      <el-form :model="queryParams" ref="queryForm" class="search-form">
        <el-form-item label="岗位等级" prop="grade">
          <el-select v-model="queryParams.grade" placeholder="全部" clearable style="width: 180px">
            <el-option
              v-for="dict in main_position_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="测评状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 180px">
            <el-option
              v-for="dict in evaluationStatusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="岗位类型" prop="positionType">
          <el-select v-model="queryParams.positionType" placeholder="全部" clearable style="width: 180px">
            <el-option
              v-for="dict in main_position_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格区间">
          <div class="price-range">
            <el-input-number
              v-model="queryParams.minPrice"
              placeholder="最低价"
              :controls="false"
              :precision="2"
              style="width: 100px"
            />
            <span class="range-separator">-</span>
            <el-input-number
              v-model="queryParams.maxPrice"
              placeholder="最高价"
              :controls="false"
              :precision="2"
              style="width: 100px"
            />
          </div>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="createTimeRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="测评名称/ID" prop="evaluationName">
          <el-input
            v-model="queryParams.evaluationName"
            placeholder="请输入"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <div class="search-buttons">
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </el-form>

      <!-- 操作按钮 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button @click="handleSelectAll">全选</el-button>
          <el-button @click="handleBatchDelete">批量删除</el-button>
          <el-button @click="handleBatchDownload">批量下架</el-button>
          <el-button @click="handleBatchPublish">批量上架</el-button>
        </div>
        <div class="toolbar-right">
          <el-button @click="handleExport">导出数据</el-button>
          <el-button @click="getList">刷新</el-button>
          <el-button @click="handleSyncToCompany">同步至单位</el-button>
          <el-button @click="handleSyncToEmployee">同步至员工</el-button>
          <el-button type="primary" @click="handleAdd">新增测评</el-button>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card modern-card">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="assessmentList"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="测评图片" align="center" width="100">
          <template #default="scope">
            <el-image
              :src="scope.row.mainImageUrl"
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 4px"
            />
          </template>
        </el-table-column>
        <el-table-column label="测评信息" min-width="200">
          <template #default="scope">
            <div class="assessment-info">
              <div class="name">{{ scope.row.evaluationName }}</div>
              <div class="code">{{ scope.row.id }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="岗位" prop="positionName" align="center" width="150" show-overflow-tooltip />
        <el-table-column label="岗位类型" prop="positionType" align="center" width="120">
          <template #default="scope">
            <dict-tag :options="main_position_type" :value="scope.row.positionType" />
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" width="120">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-switch 
              v-model="scope.row.status" 
              active-value="1" 
              inactive-value="2"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="销量" align="center" width="100">
          <template #default="scope">
            <el-button link type="primary" @click="handleSalesClick(scope.row)">
              {{ scope.row.salesVolume }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="通过率" align="center" width="100">
          <template #default="scope">
            {{ scope.row.passRate || 0 }}%
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center" width="180" />
        <el-table-column label="业务状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getBusinessStatus(scope.row).type">{{ getBusinessStatus(scope.row).text }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="primary" @click="handleEdit(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 lang="ts" name="Assessment">
import { 
  listEvaluation, 
  delEvaluation,
  updateStatus,
  syncToCompany,
  syncToEmployee
} from '@/api/main/evaluation';
import { useRouter, useRoute } from 'vue-router';
import { getCurrentInstance, ref, onMounted, toRefs, watch } from 'vue';

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

// 测评状态
const evaluationStatusOptions = [
  { label: '草稿', value: '0' },
  { label: '在售', value: '1' },
  { label: '已下架', value: '2' }
];

// 价格区间
const priceRangeOptions = [
  { label: '0-100', value: '0-100' },
  { label: '100-500', value: '100-500' },
  { label: '500-1000', value: '500-1000' },
  { label: '1000以上', value: '1000-0' }
];

const loading = ref(false);
const assessmentList = ref<any[]>([]);
const total = ref(0);
const selectedRows = ref<any[]>([]);
const tableRef = ref();
const createTimeRange = ref<any>([]);

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  grade: '',
  status: '',
  positionType: '',
  minPrice: undefined,
  maxPrice: undefined,
  evaluationName: ''
});

/** 销量点击跳转 */
const handleSalesClick = (row: any) => {
  router.push({
    name: 'AssessmentApplicantList',
    query: { assessmentId: row.id }
  });
};

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params: any = { ...queryParams.value };
    if (createTimeRange.value && createTimeRange.value.length === 2) {
      params['params[beginTime]'] = createTimeRange.value[0];
      params['params[endTime]'] = createTimeRange.value[1];
    }
    const res = await listEvaluation(params);
    assessmentList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('查询列表失败:', error);
    assessmentList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

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

/** 重置 */
const handleReset = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    grade: '',
    status: '',
    positionType: '',
    minPrice: undefined,
    maxPrice: undefined,
    evaluationName: ''
  };
  createTimeRange.value = [];
  proxy?.$refs['queryForm']?.resetFields();
  getList();
};

/** 全选 */
const handleSelectAll = () => {
  assessmentList.value.forEach(row => {
    tableRef.value?.toggleRowSelection(row, true);
  });
};

/** 批量删除 */
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    proxy?.$modal.msgWarning('请选择要删除的数据');
    return;
  }
  
  const ids = selectedRows.value.map(row => row.id);
  await proxy?.$modal.confirm('是否确认删除选中的' + ids.length + '条数据？');
  
  try {
    loading.value = true;
    await delEvaluation(ids.join(','));
    proxy?.$modal.msgSuccess('批量删除成功');
    getList();
  } catch (error) {
    console.error('批量删除失败:', error);
  } finally {
    loading.value = false;
  }
};

/** 批量下架 */
const handleBatchDownload = async () => {
  if (selectedRows.value.length === 0) {
    proxy?.$modal.msgWarning('请选择要下架的数据');
    return;
  }
  
  const ids = selectedRows.value.map(row => row.id);
  await proxy?.$modal.confirm('是否确认下架选中的' + ids.length + '条数据？');
  
  try {
    loading.value = true;
    await updateStatus(ids, '2');
    proxy?.$modal.msgSuccess('批量下架成功');
    getList();
  } catch (error) {
    console.error('批量下架失败:', error);
  } finally {
    loading.value = false;
  }
};

/** 批量上架 */
const handleBatchPublish = async () => {
  if (selectedRows.value.length === 0) {
    proxy?.$modal.msgWarning('请选择要上架的数据');
    return;
  }
  
  const ids = selectedRows.value.map(row => row.id);
  await proxy?.$modal.confirm('是否确认上架选中的' + ids.length + '条数据？');
  
  try {
    loading.value = true;
    await updateStatus(ids, '1');
    proxy?.$modal.msgSuccess('批量上架成功');
    getList();
  } catch (error) {
    console.error('批量上架失败:', error);
  } finally {
    loading.value = false;
  }
};

/** 导出数据 */
const handleExport = () => {
  proxy?.download(
    'main/evaluation/export',
    {
      ...queryParams.value
    },
    `evaluation_${new Date().getTime()}.xlsx`
  );
};

/** 同步至单位 */
const handleSyncToCompany = async () => {
  if (selectedRows.value.length === 0) {
    proxy?.$modal.msgWarning('请选择要同步的数据');
    return;
  }
  
  if (selectedRows.value.length > 1) {
    proxy?.$modal.msgWarning('只能选择一条数据进行同步');
    return;
  }
  
  try {
    const id = selectedRows.value[0].id;
    await syncToCompany(id);
    proxy?.$modal.msgSuccess('同步至单位成功');
  } catch (error) {
    console.error('同步至单位失败:', error);
  }
};

/** 同步至员工 */
const handleSyncToEmployee = async () => {
  if (selectedRows.value.length === 0) {
    proxy?.$modal.msgWarning('请选择要同步的数据');
    return;
  }
  
  if (selectedRows.value.length > 1) {
    proxy?.$modal.msgWarning('只能选择一条数据进行同步');
    return;
  }
  
  try {
    const id = selectedRows.value[0].id;
    await syncToEmployee(id);
    proxy?.$modal.msgSuccess('同步至员工成功');
  } catch (error) {
    console.error('同步至员工失败:', error);
  }
};


/** 新增 */
const handleAdd = () => {
  router.push({
    path: '/system/assessment/detail',
    query: { t: Date.now() }
  });
};

/** 查看 */
const handleView = (row: any) => {
  router.push({
    path: '/system/assessment/detail',
    query: { id: row.id, mode: 'view' }
  });
};

/** 编辑 */
const handleEdit = (row: any) => {
  router.push({
    path: '/system/assessment/detail',
    query: { id: row.id }
  });
};

/** 状态切换 */
const handleStatusChange = async (row: any) => {
  const text = row.status === '1' ? '上架' : '下架';
  try {
    await updateStatus([row.id], row.status);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch (error) {
    // 如果切换失败，恢复原状态
    row.status = row.status === '1' ? '2' : '1';
    console.error('状态切换失败:', error);
  }
};

/** 多选 */
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 监听路由query变化，从编辑页返回时刷新列表
watch(
  () => route.query.t,
  (newVal) => {
    if (newVal) {
      getList();
    }
  }
);

onMounted(() => {
  getList();
});

/** 获取业务状态 */
const getBusinessStatus = (row: any) => {
  // 状态：0=草稿, 1=已发布, 2=已下架
  // delFlag: 0=正常, 1=删除

  if (row.delFlag == '1') {
    return { text: '删除', type: 'danger' as const };
  }

  if (row.status == '0') {
    return { text: '草稿', type: 'info' as const };
  }

  if (row.status == '2') {
    return { text: '已下架', type: 'info' as const };
  }

  if (row.status == '1') {
    const now = new Date();
    const onTime = row.onTime ? new Date(row.onTime) : null;
    const downTime = row.downTime ? new Date(row.downTime) : null;

    if (onTime && now < onTime) {
      return { text: '待上架', type: 'warning' as const };
    }
    if (downTime && now > downTime) {
      return { text: '已下架', type: 'info' as const };
    }
    return { text: '在售', type: 'success' as const };
  }

  return { text: '未知', type: 'info' as const };
};
</script>

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

.search-card {
  margin-bottom: 8px;
  min-width: 1600px !important;
  width: 100% !important;
  
  :deep(.el-card__body) {
    padding: 16px;
  }
  
  .search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;

    .price-range {
      display: flex;
      align-items: center;
      gap: 4px;

      .range-separator {
        color: #dcdfe6;
      }
    }
    
    .search-buttons {
      display: flex;
      gap: 8px;
      margin-top: 8px;
      width: 100%;
    }
  }
  
  .el-form {
    margin-bottom: 0;
    
    .el-form-item {
      margin-bottom: 12px;
    }
  }
  
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px solid #e4e7ed;
    
    .toolbar-left,
    .toolbar-right {
      display: flex;
      gap: 8px;
    }
  }
}

.table-card {
  :deep(.el-card__body) {
    padding: 16px;
  }
  
  .assessment-info {
    .name {
      font-size: 14px;
      color: #303133;
      margin-bottom: 4px;
    }
    
    .code {
      font-size: 12px;
      color: #909399;
    }
  }
}
</style>
