<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">
        <!-- 第一行：月度、部门、行业 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="月度" prop="month">
               <el-date-picker v-model="form.month" type="month" value-format="YYYY-MM" 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>

        <!-- 第二行：目标任务、冲刺任务 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="目标任务" prop="targetTask">
              <el-input v-model="form.targetTask" placeholder="请输入目标任务" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="冲刺任务" prop="sprintTask">
              <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="MonthlyTaskDetail">
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 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({
  month: new Date().toISOString().slice(0, 7), // 默认当前月 YYYY-MM
  deptId: '',
  industryLine: '',
  targetTask: undefined,
  sprintTask: undefined,
  taskType: 2, // 2: 月度任务
  details: []
});

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

const rules = {
  month: [{ 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) {
      // 拆分年份和月份发送给后端
      const datePart = form.value.month.split('-');
      const data = {
          ...form.value,
          year: parseInt(datePart[0]),
          month: parseInt(datePart[1])
      };
      
      if (isEdit.value) {
        await updateBusinessTask({ ...data, id: id.value });
      } else {
        await addBusinessTask(data);
      }
      proxy.$modal.msgSuccess('保存成功');
      handleCancel();
    }
  });
};

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

onMounted(async () => {
  getDeptTree();
  getCustomerList();
  if (isEdit.value) {
    const res = await getBusinessTask(id.value);
    const data = res.data;
    // 回显月度 YYYY-MM
    if (data.year && data.month) {
      data.month = `${data.year}-${String(data.month).padStart(2, '0')}`;
    }
    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;
}
</style>
