<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="90px">
        <!-- 第一行 3项 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="年度" prop="year" required>
              <el-date-picker v-model="form.year" type="year" value-format="YYYY" placeholder="请选择" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="部门" prop="deptId">
              <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>

        <!-- 第二行 2项 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="目标任务" prop="targetTask" required>
              <el-input v-model.number="form.targetTask" type="number" placeholder="请输入目标任务" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="冲刺任务" prop="sprintTask" required>
              <el-input v-model.number="form.sprintTask" type="number" 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">添加数据</el-button>
            <el-button type="primary" plain icon="Upload" size="default" class="btn-import-custom">导入数据</el-button>
          </div>

          <el-table :data="form.details" border class="standard-table" header-row-class-name="table-header">
            <el-table-column label="目标任务" align="center">
              <template #default="scope">
                <el-input v-model.number="scope.row.targetTask" type="number" placeholder="请输入目标任务" class="table-input" />
              </template>
            </el-table-column>
            <el-table-column label="核心客户名称" align="center" min-width="200">
              <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">
              <template #default="scope">
                <el-input v-model.number="scope.row.sprintTask" type="number" placeholder="请输入冲刺任务" class="table-input" />
              </template>
            </el-table-column>
            <el-table-column label="重点项目" align="center">
              <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="80">
              <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">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup name="AnnualTaskDetail">
import { ref, onMounted, getCurrentInstance, computed } 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';

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 isEdit = computed(() => !!id.value);
const pageTitle = computed(() => isEdit.value ? '修改目标' : '新增目标');

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({
  year: new Date().getFullYear().toString(),
  deptId: '',
  industryLine: '',
  targetTask: undefined,
  sprintTask: undefined,
  taskType: 0, // 0: 年度任务
  details: []
});

const rules = {
  year: [{ 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 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) {
      if (isEdit.value) {
        await updateBusinessTask({ ...form.value, id: id.value });
        proxy.$modal.msgSuccess('修改成功');
      } else {
        await addBusinessTask(form.value);
        proxy.$modal.msgSuccess('新增成功');
      }
      handleCancel();
    }
  });
};

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

onMounted(async () => {
  getDeptTree();
  getCustomerList();
  if (isEdit.value) {
    const res = await getBusinessTask(id.value);
    form.value = res.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) {
    font-weight: normal;
    color: #606266;
    &::before {
        margin-right: 2px !important;
    }
  }
}

.table-section {
  margin-top: 30px;
  
  .row-flex {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    
    .label-pre {
      font-size: 14px;
      color: #606266;
      width: 80px;
    }
    
    .btn-primary-custom {
      background-color: #409eff;
      border-color: #409eff;
    }
    
    .btn-import-custom {
      background-color: #f0f7ff;
      border-color: #c6e2ff;
      color: #409eff;
    }
  }
}

.standard-table {
  :deep(.table-header th) {
    background-color: #f8f9fb !important;
    color: #333;
    font-weight: 600;
  }
  
  :deep(.el-input__wrapper) {
    box-shadow: none;
    padding: 0 10px;
  }
  :deep(.el-input__inner) {
      text-align: center;
  }
}

.footer-btns {
  margin-top: 40px;
  display: flex;
  justify-content: flex-start;
  gap: 15px;
  
  .el-button--primary {
    padding: 10px 25px;
  }
}
</style>
