<template>
  <div class="app-container">
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryRef" label-width="80px" v-show="showSearch">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="部门" prop="deptId">
              <el-tree-select
                v-model="queryParams.deptId"
                :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="请选择部门"
                clearable
                check-strictly
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="行业条线" prop="industryLine">
              <el-input v-model="queryParams.industryLine" placeholder="请输入行业条线" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务员" prop="salesName">
              <el-input v-model="queryParams.salesName" placeholder="请输入业务人员" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客服人员" prop="csName">
              <el-input v-model="queryParams.csName" placeholder="请输入客服人员" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-top: 15px;">
          <el-col :span="6">
            <el-form-item label="选择年份" prop="year">
              <el-date-picker v-model="queryParams.year" type="year" value-format="YYYY" placeholder="请选择年份" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="季度" prop="quarterValue">
              <el-popover placement="bottom-start" :width="320" trigger="click" v-model:visible="quarterPopoverVisible">
                <template #reference>
                  <el-input 
                    readonly 
                    :value="displayQuarterText" 
                    placeholder="请选择季度" 
                    style="width: 100%"
                    clearable
                    @clear="handleClearQuarter"
                  >
                    <template #prefix>
                      <el-icon><Calendar /></el-icon>
                    </template>
                  </el-input>
                </template>
                <div class="quarter-picker-panel">
                  <div class="panel-header">
                    <el-icon @click="pickerYear--" class="arrow-icon"><DArrowLeft /></el-icon>
                    <span class="year-text">{{ pickerYear }} 年</span>
                    <el-icon @click="pickerYear++" class="arrow-icon"><DArrowRight /></el-icon>
                  </div>
                  <div class="panel-divider"></div>
                  <div class="panel-content">
                    <div 
                      v-for="q in [1, 2, 3, 4]" 
                      :key="q" 
                      class="quarter-item"
                      :class="{ 'is-active': isQuarterActive(q) }"
                      @click="handleSelectQuarter(q)"
                    >
                      {{ getQuarterName(q) }}
                    </div>
                  </div>
                </div>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="选择月份" prop="month">
               <el-date-picker v-model="queryParams.month" type="month" value-format="M" format="M月" placeholder="请选择" style="width: 100%" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6" class="search-btns">
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="content-card">
      <template #header>
        <div class="header-container">
          <span class="title-text">月度任务信息列表</span>
          <div class="action-buttons">
            <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
            <el-button type="primary" plain icon="Upload" @click="handleImport">导入</el-button>
            <el-button type="info" plain icon="Download" @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="monthlyTaskList" border stripe highlight-current-row class="custom-table">
        <el-table-column type="index" label="序号" width="60" align="center" fixed />
        <el-table-column label="部门" align="center" prop="deptName" width="120" fixed />
        <el-table-column label="行业条线" align="center" prop="industryLine" width="100" />
        <el-table-column :label="(queryParams.quarter ? 'Q' + queryParams.quarter : '') + '季度任务'" align="center" prop="quarterTaskValue" width="100">
           <template #default="scope">
              {{ scope.row.quarterTaskValue ? scope.row.quarterTaskValue + '万' : '' }}
            </template>
        </el-table-column>
        
        <el-table-column :label="(queryParams.year || '') + '年' + (queryParams.month || '') + '月目标任务'" align="center">
          <el-table-column label="目标任务" align="center" prop="targetTask" width="100">
             <template #default="scope">
              {{ scope.row.targetTask ? scope.row.targetTask + '万' : '' }}
            </template>
          </el-table-column>
          <el-table-column label="实绩" align="center" prop="actualAchievement" width="80" />
          <el-table-column label="核心客户" align="center" prop="coreCustomer" width="150" show-overflow-tooltip />
          <el-table-column label="重点项目" align="center" prop="keyProject" width="150" show-overflow-tooltip />
          <el-table-column label="潜在商机" align="center" prop="potentialOpportunity" width="150" show-overflow-tooltip />
          <el-table-column label="达成比" align="center" prop="achievementRate" width="100">
             <template #default="scope">
               {{ scope.row.achievementRate || '' }}
             </template>
          </el-table-column>
          <el-table-column label="业务人员" align="center" prop="salesUserName" width="100" />
          <el-table-column label="客服人员" align="center" prop="serviceUserName" width="100" />
        </el-table-column>

        <el-table-column :label="(queryParams.year ? (queryParams.year - 1).toString() : '去年同期')" align="center">
          <el-table-column label="目标" align="center" prop="lastYearTarget" width="100" />
          <el-table-column label="实绩" align="center" prop="lastYearActual" width="100" />
        </el-table-column>

        <el-table-column label="同比" align="center" prop="yoy" width="80" fixed="right" />
      </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="MonthlyTask">
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { listBusinessTask } from '@/api/sale/businessTask/index';
import { deptTreeSelect } from '@/api/system/dept/index';
import { Calendar, DArrowLeft, DArrowRight } from '@element-plus/icons-vue';

const router = useRouter();
const { proxy } = getCurrentInstance();

const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const monthlyTaskList = ref([]);
const deptOptions = ref([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  taskType: 2, // 月度任务
  deptId: undefined,
  industryLine: undefined,
  salesName: undefined,
  csName: undefined,
  year: undefined,
  quarter: undefined,
  month: undefined
});

// 用于绑定的季度选择器值相关
const quarterPopoverVisible = ref(false);
const pickerYear = ref(new Date().getFullYear());

/** 计算当前显示的季度文本 */
const displayQuarterText = computed(() => {
  if (!queryParams.year || !queryParams.quarter) return '';
  return `${queryParams.year}年 第${queryParams.quarter}季度`;
});

/** 获取季度名称 */
const getQuarterName = (q) => {
  const names = ['', '第一季度', '第二季度', '第三季度', '第四季度'];
  return names[q];
};

/** 判定是否选中 */
const isQuarterActive = (q) => {
  return parseInt(queryParams.year) === pickerYear.value && queryParams.quarter === q;
};

/** 选择季度 */
const handleSelectQuarter = (q) => {
  queryParams.year = pickerYear.value.toString();
  queryParams.quarter = q;
  quarterPopoverVisible.value = false;
  handleQuery();
};

/** 清除季度 */
const handleClearQuarter = () => {
  queryParams.quarter = undefined;
  handleQuery();
};

const getDeptTree = async () => {
  const res = await deptTreeSelect();
  deptOptions.value = proxy.handleTree(res.data, 'deptId');
};

const getList = async () => {
  loading.value = true;
  try {
    const res = await listBusinessTask(queryParams);
    monthlyTaskList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (err) {
    console.error('获取月度任务列表失败', err);
  } finally {
    loading.value = false;
  }
};

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

const resetQuery = () => {
  proxy.resetForm("queryRef");
  queryParams.year = undefined;
  queryParams.quarter = undefined;
  pickerYear.value = new Date().getFullYear();
  handleQuery();
};

const handleAdd = () => {
  router.push('/sales/month-detail');
};

const handleImport = () => {};
const handleExport = () => {};

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

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

.search-card {
  margin-bottom: 20px;
  border: none;
  background: #fff;
  border-radius: 8px;
  padding: 10px;
  :deep(.el-form-item) {
    margin-bottom: 0px;
  }
}

.search-btns {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12px;
}

.content-card {
  border: none;
  .header-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .title-text {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    position: relative;
    padding-left: 12px;
    &::before {
      content: "";
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background: #409eff;
      border-radius: 2px;
    }
  }
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
  :deep(th.el-table__cell) {
    background-color: #f8fafc !important;
    color: #475569;
    font-weight: 600;
  }
}

/* 自定义季度选择器样式 */
.quarter-picker-panel {
  padding: 10px 5px;
  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px 10px;
    .year-text {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
    .arrow-icon {
      cursor: pointer;
      color: #909399;
      font-size: 16px;
      &:hover {
        color: #409eff;
      }
    }
  }
  .panel-divider {
    height: 1px;
    background-color: #ebeef5;
    margin: 0 0 15px;
  }
  .panel-content {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    gap: 10px;
    padding: 0 5px;
    .quarter-item {
      width: 45%;
      height: 40px;
      line-height: 40px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      font-size: 14px;
      color: #606266;
      transition: all 0.3s;
      
      &:hover {
        background-color: #f5f7fa;
        color: #409eff;
      }
      
      &.is-active {
        background-color: #ecf5ff;
        color: #409eff;
        font-weight: 600;
      }
    }
  }
}
</style>
