<template>
  <div class="app-container">
    <transition name="fade-transform" mode="out-in">
      <!-- 列表页展示视图 -->
      <div v-if="!showForm" key="list" class="list-view">
        <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
                      show-checkbox
                      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 @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="业务员" prop="salesUserName">
                  <el-input v-model="queryParams.salesUserName" placeholder="请输入业务人员" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="客服人员" prop="serviceUserName">
                  <el-input v-model="queryParams.serviceUserName" placeholder="请输入客服人员" clearable @keyup.enter="handleQuery" />
                </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="18" 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-group>
                  <el-button icon="Grid" title="卡片模式"></el-button>
                  <el-button icon="Menu" title="列表模式" class="is-active"></el-button>
                </el-button-group>
                <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="annualTaskList" 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="120" fixed />
            
            <!-- 2026年目标任务 -->
            <el-table-column :label="`${queryParams.year}年目标任务`" align="center">
              <el-table-column label="目标任务" align="center" prop="targetTask" width="120">
                <template #default="scope">
                  {{ scope.row.targetTask ? scope.row.targetTask + '万' : '' }}
                </template>
              </el-table-column>
              <el-table-column label="冲刺任务" align="center" prop="sprintTask" width="120">
                <template #default="scope">
                  {{ scope.row.sprintTask ? scope.row.sprintTask + '万' : '' }}
                </template>
              </el-table-column>
              <el-table-column label="核心客户" align="center" prop="coreCustomer" min-width="200" show-overflow-tooltip />
              <el-table-column label="重点项目" align="center" prop="keyProject" width="150" />
              <el-table-column label="业务人员" align="center" prop="salesUserName" width="100" />
              <el-table-column label="客服人员" align="center" prop="serviceUserName" width="100" />
              <el-table-column label="实绩" align="center" prop="actualAchievement" width="100">
                <template #default="scope">
                  {{ (scope.row.actualAchievement && scope.row.actualAchievement != 0) ? scope.row.actualAchievement + '万' : '' }}
                </template>
              </el-table-column>
              <el-table-column label="达成比" align="center" prop="achievementRate" width="100">
                <template #default="scope">
                  <span v-if="scope.row.achievementRate && scope.row.achievementRate !== '0.00%'" :class="parseFloat(scope.row.achievementRate) >= 100 ? 'text-success' : 'text-primary'">
                    {{ scope.row.achievementRate }}
                  </span>
                  <span v-else></span>
                </template>
              </el-table-column>
            </el-table-column>

            <!-- 上年指标 -->
            <el-table-column label="上年指标" align="center">
              <el-table-column label="目标" align="center" prop="lastYearTarget" width="120">
                <template #default="scope">
                  {{ (scope.row.lastYearTarget && scope.row.lastYearTarget != 0) ? scope.row.lastYearTarget + '万' : '' }}
                </template>
              </el-table-column>
              <el-table-column label="实绩" align="center" prop="lastYearActual" width="120">
                <template #default="scope">
                  {{ (scope.row.lastYearActual && scope.row.lastYearActual != 0) ? scope.row.lastYearActual + '万' : '' }}
                </template>
              </el-table-column>
            </el-table-column>

            <el-table-column label="同比" align="center" prop="yoy" width="100" fixed="right">
              <template #default="scope">
                <span v-if="scope.row.yoy && scope.row.yoy !== '0.00%'" :class="scope.row.yoy?.includes('+') ? 'text-danger' : 'text-success'">
                  {{ scope.row.yoy }}
                </span>
                <span v-else></span>
              </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>

      <!-- 新增/编辑表单已迁移至详情页 -->
    </transition>
  </div>
</template>

<script setup name="AnnualTask">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { listBusinessTask } from '@/api/sale/businessTask/index';
import { deptTreeSelect } from '@/api/system/dept/index';

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

const loading = ref(false);
const showSearch = ref(true);
const showForm = ref(false);
const total = ref(0);
const annualTaskList = ref([]);
const currentYear = ref(new Date().getFullYear());

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  taskType: 0, // 年度任务
  deptId: undefined,
  industryLine: undefined,
  salesUserName: undefined,
  serviceUserName: undefined,
  year: new Date().getFullYear().toString()
});

const form = ref({
  id: undefined,
  year: '',
  deptId: '',
  industryLine: '',
  targetTask: 0,
  sprintTask: 0,
  details: []
});

const rules = {
  year: [{ required: true, message: "年份不能为空", trigger: "change" }],
  deptId: [{ required: true, message: "部门不能为空", trigger: "change" }],
  industryLine: [{ required: true, message: "条线不能为空", trigger: "change" }],
  targetTask: [{ required: true, message: "目标任务不能为空", trigger: "blur" }],
  sprintTask: [{ required: true, message: "冲刺任务不能为空", trigger: "blur" }],
};

const deptOptions = ref([]);

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);
    annualTaskList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (err) {
    console.error('获取列表失败', err);
  } finally {
    loading.value = false;
  }
};

/** 重置查询 */
const resetQuery = () => {
  proxy.resetForm("queryRef");
  queryParams.year = new Date().getFullYear().toString();
  handleQuery();
};

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

/** 新增按钮 */
const handleAdd = () => {
  router.push('/sales/year-detail');
};

/** 修改按钮 */
const handleUpdate = (row) => {
  router.push(`/sales/year-detail/${row.id}`);
};

/** 导出 */
const handleExport = () => {
  proxy.download('customer/businessTask/export', {
    ...queryParams
  }, `年度任务_${new Date().getTime()}.xlsx`)
};

onMounted(() => {
  getList();
  getDeptTree();
});
</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;
    .is-active {
        background-color: #f0f7ff;
        color: #409eff;
        border-color: #c6e2ff;
    }
  }
  .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;
    }
  }
}

.action-buttons {
    display: flex;
    gap: 12px;
    align-items: center;
}

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

.text-success { color: #67c23a; }
.text-primary { color: #409eff; }
.text-danger { color: #f56c6c; }

/* 表单视图样式 */
.form-view {
  .form-header {
    display: flex;
    align-items: center;
    gap: 10px;
    .form-title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .premium-form {
    padding: 20px 40px;
  }

  .section-divider {
    margin: 30px 0 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 12px;
    .section-title {
      font-size: 15px;
      font-weight: 600;
      color: #606266;
      border-left: 3px solid #409eff;
      padding-left: 10px;
    }
  }

  .form-footer {
    margin-top: 50px;
    display: flex;
    justify-content: center;
    gap: 20px;
  }
}

.detail-table {
    :deep(el-input) {
        --el-input-border-radius: 4px;
    }
}

/* 动画效果 */
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.5s;
}
.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}
.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(30px);
}
</style>
