<template>
  <div class="app-container">
    <div class="header-breadcrumb">
      <el-button link icon="Back" @click="handleCancel" class="back-link">返回</el-button>
      <div class="v-line"></div>
      <span class="page-title">{{ pageTitle }}</span>
    </div>

    <div class="form-wrapper">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <!-- 第一行：季度、部门、行业 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="季度：" prop="quarter" required>
              <el-popover placement="bottom-start" :width="320" trigger="click" v-model:visible="quarterPopoverVisible">
                <template #reference>
                  <el-input 
                    readonly 
                    :value="displayQuarterText" 
                    placeholder="请选择季度" 
                    style="width: 100%"
                  >
                    <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="8">
            <el-form-item label="部门：" prop="deptId" required>
              <el-tree-select
                v-model="form.deptId"
                :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="请选择"
                check-strictly
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="行业条线：" prop="industryLine">
              <el-input v-model="form.industryLine" placeholder="请输入行业条线" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：目标任务、冲刺任务 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="目标任务：" prop="targetTask" required>
              <el-input v-model="form.targetTask" placeholder="请输入目标任务" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="冲刺任务：" prop="sprintTask" required>
              <el-input v-model="form.sprintTask" placeholder="请输入冲刺任务" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="table-section">
          <div class="row-flex">
            <span class="label-pre">任务分解：</span>
            <el-button type="primary" icon="Plus" size="default" @click="handleAddRow" class="btn-primary-custom" style="padding: 8px 20px;">添加</el-button>
            <el-button type="primary" plain icon="Upload" size="default" class="btn-import-custom" style="padding: 8px 20px;">导入</el-button>
          </div>

          <el-table :data="form.details" border class="standard-table" header-row-class-name="table-header">
            <el-table-column label="目标任务" align="center" width="200">
              <template #default="scope">
                <el-input v-model="scope.row.targetTask" placeholder="请输入目标任务" class="table-input" />
              </template>
            </el-table-column>
            <el-table-column label="核心客户名称" align="center" min-width="250">
              <template #default="scope">
                <el-select v-model="scope.row.coreCustomer" placeholder="请选择核心客户名称" filterable style="width: 100%">
                   <el-option v-for="item in customerOptions" :key="item.id || item.customerId" :label="item.customerName" :value="item.customerName" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="冲刺任务" align="center" width="200">
              <template #default="scope">
                <el-input v-model="scope.row.sprintTask" placeholder="请输入冲刺任务" class="table-input" />
              </template>
            </el-table-column>
            <el-table-column label="重点项目" align="center" min-width="200">
              <template #default="scope">
                <el-input v-model="scope.row.keyProject" placeholder="请输入重点项目" class="table-input" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template #default="scope">
                <el-button type="danger" link @click="handleDeleteRow(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="footer-btns">
          <el-button type="primary" icon="CircleCheck" @click="handleSubmit" style="padding: 10px 30px;">提交</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup name="QuarterlyTaskDetail">
import { ref, computed, onMounted, getCurrentInstance } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getBusinessTask, addBusinessTask, updateBusinessTask } from '@/api/sale/businessTask/index';
import { deptTreeSelect } from '@/api/system/dept/index';
import { listCustomerInfo } from '@/api/customer/customerInfo/index';
import { Calendar, DArrowLeft, DArrowRight, InfoFilled, Back, CircleCheck, Delete } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const id = ref(route.params.id);
const formRef = ref(null);
const deptOptions = ref([]);
const customerOptions = ref([]);

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

const getCustomerList = async () => {
  const res = await listCustomerInfo({ pageNum: 1, pageSize: 500, isHighSeas: 'all' });
  customerOptions.value = res.rows || [];
};

const form = ref({
  id: undefined,
  quarter: undefined,
  deptId: undefined,
  industryLine: undefined,
  targetTask: undefined,
  sprintTask: undefined,
  taskType: 1, // 1: 季度任务
  details: []
});

const isEdit = computed(() => !!id.value);
const pageTitle = computed(() => isEdit.value ? '修改目标' : '新增目标');

// 自定义季度选择器相关逻辑
const quarterPopoverVisible = ref(false);
const pickerYear = ref(new Date().getFullYear());

/** 计算当前显示的季度文本 */
const displayQuarterText = computed(() => {
  if (!form.value.quarter || !form.value.quarter.includes('-')) return '';
  const parts = form.value.quarter.split('-');
  return `${parts[0]}年 第${parts[1]}季度`;
});

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

/** 判定是否选中 */
const isQuarterActive = (q) => {
  if (!form.value.quarter || !form.value.quarter.includes('-')) return false;
  const parts = form.value.quarter.split('-');
  return parseInt(parts[0]) === pickerYear.value && parseInt(parts[1]) === q;
};

/** 选择季度 */
const handleSelectQuarter = (q) => {
  form.value.quarter = `${pickerYear.value}-${q}`;
  quarterPopoverVisible.value = false;
};

const rules = {
  quarter: [{ required: true, message: '请选择季度', trigger: 'change' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  industryLine: [{ required: true, message: '请输入行业条线', trigger: 'blur' }],
  targetTask: [{ required: true, message: '请输入目标任务', trigger: 'blur' }],
  sprintTask: [{ required: true, message: '请输入冲刺任务', trigger: 'blur' }]
};

/** 合计逻辑 */
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    if (column.label === '目标任务' || column.label === '冲刺任务') {
      const values = data.map(item => Number(item[column.property === 'targetTask' ? 'targetTask' : 'sprintTask']));
      if (!values.every(value => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0).toFixed(2) + ' 万';
      } else {
        sums[index] = 'N/A';
      }
    } else {
      sums[index] = '';
    }
  });
  return sums;
};

/** 计算差异 */
const totalDiff = computed(() => {
    const detailTotal = form.value.details.reduce((acc, cur) => acc + (Number(cur.targetTask) || 0), 0);
    return (form.value.targetTask || 0) - detailTotal;
});

const handleAddRow = () => {
  form.value.details.push({ targetTask: undefined, coreCustomer: '', sprintTask: undefined, keyProject: '' });
};

const handleDeleteRow = (index) => {
  form.value.details.splice(index, 1);
};

const handleSubmit = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 拆分 YYYY-q 格式日期
      let data = { ...form.value };
      if (data.quarter && typeof data.quarter === 'string' && data.quarter.includes('-')) {
        const parts = data.quarter.split('-');
        data.year = parseInt(parts[0]);
        // 后端 Q1 一般对应数字 1
        data.quarter = parseInt(parts[1]);
      }

      if (isEdit.value) {
        await updateBusinessTask({ ...data, id: id.value });
      } else {
        await addBusinessTask(data);
      }
      proxy.$modal.msgSuccess('保存成功');
      handleCancel();
    }
  });
};

const handleCancel = () => {
  router.push('/sales/quarter');
};

onMounted(async () => {
  getDeptTree();
  getCustomerList();
  if (isEdit.value) {
    const res = await getBusinessTask(id.value);
    const data = res.data;
    // 回显映射：后端返回 quarterTargetTask，前端表单使用 targetTask
    if (data.quarterTargetTask !== undefined) {
        data.targetTask = data.quarterTargetTask;
    }
    // 回显季度 YYYY-q
    if (data.year && data.quarter) {
      data.quarter = `${data.year}-${data.quarter}`;
    }
    form.value = { ...form.value, ...data };
  } else {
    // 新增时默认添加一行
    handleAddRow();
  }
});
</script>

<style scoped lang="scss">
.app-container {
  padding: 0;
  background-color: #fff;
  min-height: 100vh;
}

.header-breadcrumb {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  gap: 10px;
  
  .back-link {
    font-size: 14px;
    color: #606266;
    font-weight: 500;
  }
  
  .v-line {
    width: 1px;
    height: 14px;
    background-color: #dcdfe6;
  }
  
  .page-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

.form-wrapper {
  padding: 25px 30px;
  
  :deep(.el-form-item__label) {
    color: #606266;
  }
}

.table-section {
  margin-top: 30px;
  
  .row-flex {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    
    .label-pre {
      font-size: 14px;
      color: #606266;
      width: 80px;
    }
  }
}

.standard-table {
  :deep(.table-header th) {
    background-color: #f8f9fb !important;
    color: #333;
    font-weight: 600;
  }
  :deep(.el-input__inner) {
      text-align: center;
  }
}

.btn-primary-custom {
  background-color: #409eff;
  border-color: #409eff;
}

.btn-import-custom {
  background-color: #f0f7ff;
  border-color: #c6e2ff;
  color: #409eff;
}

.footer-btns {
  margin-top: 40px;
  display: flex;
  justify-content: flex-start;
}

/* 自定义季度选择器样式 */
.quarter-picker-panel {
  padding: 12px;
  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    .year-text {
      font-size: 15px;
      font-weight: 600;
      color: #111827;
    }
    .arrow-icon {
      cursor: pointer;
      color: #9ca3af;
      font-size: 16px;
      padding: 4px;
      border-radius: 4px;
      &:hover {
        background-color: #f3f4f6;
        color: #3b82f6;
      }
    }
  }
  .panel-divider {
    height: 1px;
    background-color: #f3f4f6;
    margin: 0 -12px 12px;
  }
  .panel-content {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
    .quarter-item {
      height: 36px;
      line-height: 36px;
      text-align: center;
      cursor: pointer;
      border-radius: 6px;
      font-size: 13px;
      color: #4b5563;
      transition: all 0.2s;
      border: 1px solid transparent;
      
      &:hover {
        background-color: #f3f4f6;
        color: #3b82f6;
      }
      
      &.is-active {
        background-color: #eff6ff;
        color: #3b82f6;
        border-color: #bfdbfe;
        font-weight: 600;
      }
    }
  }
}
</style>
