<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="年份" prop="year">
        <el-date-picker
          v-model="queryParams.year"
          type="year"
          value-format="YYYY"
          placeholder="选择年份"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="季度" prop="quarter">
        <el-select v-model="queryParams.quarter" placeholder="选择季度" style="width: 120px">
          <el-option label="Q1" :value="1" />
          <el-option label="Q2" :value="2" />
          <el-option label="Q3" :value="3" />
          <el-option label="Q4" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-tree-select
          v-model="queryParams.deptId"
          :data="deptOptions"
          :props="{ value: 'id', label: 'label', children: 'children' }"
          value-key="id"
          placeholder="选择部门"
          check-strictly
        />
      </el-form-item>
      <el-form-item label="业务人员" prop="salesUserId">
        <el-select v-model="queryParams.salesUserId" filterable clearable placeholder="业务人员">
          <el-option
            v-for="item in userOptions"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          />
        </el-select>
      </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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 季度任务信息列表表格 - 模仿图片多级表头设计 -->
    <el-table v-loading="loading" :data="quarterlyTaskList" border stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="序号" type="index" width="60" align="center" fixed="left" />
      <el-table-column label="部门" align="center" prop="deptName" width="120" show-overflow-tooltip fixed="left" />
      <el-table-column label="行业条线" align="center" prop="industryLine" width="100" fixed="left" />
      <el-table-column label="业务人员" align="center" prop="salesUserName" width="100" fixed="left" />
      <el-table-column label="客服人员" align="center" prop="serviceUserName" width="100" fixed="left" />

      <!-- 2023年度任务 -->
      <el-table-column :label="queryParams.year + '年度任务'" align="center">
        <el-table-column label="目标任务" align="center" prop="annualTargetTask" width="110">
          <template #default="scope">
            <span>{{ formatMoney(scope.row.annualTargetTask) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="冲刺任务" align="center" prop="annualSprintTask" width="110">
          <template #default="scope">
            <span>{{ formatMoney(scope.row.annualSprintTask) }}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 季度任务 (Qx) (占比%) -->
      <el-table-column :label="'季度任务 (Q' + queryParams.quarter + ') (' + currentQuarterPercent + '%)'" align="center">
        <el-table-column label="目标任务" align="center" prop="targetTask" width="110">
          <template #default="scope">
            <span>{{ formatMoney(scope.row.targetTask) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实绩" align="center" prop="actualAchievement" width="110">
          <template #default="scope">
            <span>{{ formatMoney(scope.row.actualAchievement) }}</span>
          </template>
        </el-table-column>
        <!-- 动态月份列 -->
        <el-table-column :label="monthLabels[0]" align="center" prop="month1Actual" width="100">
          <template #default="scope">
            <span>{{ formatMoney(scope.row.month1Actual) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="monthLabels[1]" align="center" prop="month2Actual" width="100">
          <template #default="scope">
            <span>{{ formatMoney(scope.row.month2Actual) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="monthLabels[2]" align="center" prop="month3Actual" width="100">
          <template #default="scope">
            <span>{{ formatMoney(scope.row.month3Actual) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="达成比" align="center" prop="achievementRate" width="90">
          <template #default="scope">
            <span :class="getRateClass(scope.row.achievementRate)">{{ scope.row.achievementRate }}%</span>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 去年同期实绩 (Q1, Q2, Q3, Q4) -->
      <el-table-column :label="(queryParams.year - 1) + '年实绩'" align="center">
        <el-table-column label="Q1" align="center" prop="lastYearQ1Actual" width="90">
          <template #default="scope">{{ formatMoney(scope.row.lastYearQ1Actual) }}</template>
        </el-table-column>
        <el-table-column label="Q2" align="center" prop="lastYearQ2Actual" width="90">
          <template #default="scope">{{ formatMoney(scope.row.lastYearQ2Actual) }}</template>
        </el-table-column>
        <el-table-column label="Q3" align="center" prop="lastYearQ3Actual" width="90">
          <template #default="scope">{{ formatMoney(scope.row.lastYearQ3Actual) }}</template>
        </el-table-column>
        <el-table-column label="Q4" align="center" prop="lastYearQ4Actual" width="90">
          <template #default="scope">{{ formatMoney(scope.row.lastYearQ4Actual) }}</template>
        </el-table-column>
      </el-table-column>

      <el-table-column label="操作" align="center" fixed="right" width="150" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @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"
    />

    <!-- 添加或修改季度任务信息对话框 (略，可根据需要补充) -->
  </div>
</template>

<script setup name="QuarterlyTask">
import { listQuarterlyTask, getQuarterlyTask, delQuarterlyTask, addQuarterlyTask, updateQuarterlyTask } from "@/api/customer/quarterlyTask";
import { listUser } from "@/api/system/user";
import { deptTreeSelect } from "@/api/system/dept";

const { proxy } = getCurrentInstance();

const quarterlyTaskList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const deptOptions = ref([]);
const userOptions = ref([]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    year: new Date().getFullYear().toString(),
    quarter: Math.floor((new Date().getMonth() + 3) / 3),
    deptId: undefined,
    salesUserId: undefined,
    industryLine: undefined
  }
});

const { queryParams } = toRefs(data);

/** 月度标签映射 */
const monthLabels = computed(() => {
  const qStr = queryParams.value.quarter;
  if (qStr === 1) return ['1月', '2月', '3月'];
  if (qStr === 2) return ['4月', '5月', '6月'];
  if (qStr === 3) return ['7月', '8月', '9月'];
  if (qStr === 4) return ['10月', '11月', '12月'];
  return ['-月', '-月', '-月'];
});

/** 季度占比（演示逻辑，实际可能存库或带出） */
const currentQuarterPercent = computed(() => {
  const map = { 1: 30, 2: 25, 3: 20, 4: 25 };
  return map[queryParams.value.quarter] || 0;
});

/** 查询部门树 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
}

/** 查询用户列表 */
function getUserList() {
  listUser({ pageNum: 1, pageSize: 1000 }).then(response => {
    userOptions.value = response.rows;
  });
}

/** 查询列表 */
function getList() {
  loading.value = true;
  listQuarterlyTask(queryParams.value).then(response => {
    quarterlyTaskList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 格式化金额 (万/元) */
function formatMoney(val) {
  if (val == null) return '-';
  // 按照图片风格，如果是100万，可以简化显示，这里先保留两位小数
  if (val >= 10000) {
    return (val / 10000).toFixed(0) + '万';
  }
  return val;
}

/** 达成比颜色类 */
function getRateClass(rate) {
  if (rate >= 100) return 'text-success';
  if (rate < 60) return 'text-danger';
  return '';
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// ... 增删改的 handle 方法已略 ...

getDeptTree();
getUserList();
getList();
</script>

<style scoped>
.text-success { color: #67C23A; font-weight: bold; }
.text-danger { color: #F56C6C; font-weight: bold; }
/* 优化表头颜色，模仿图片中的浅蓝色调 */
:deep(.el-table th) {
  background-color: #f8faff !important;
  color: #333;
  font-weight: bold;
}
</style>
