<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="分包类型名称" prop="dictName">
              <el-input v-model="queryParams.dictName" placeholder="请输入分包类型名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="计划招标时间" prop="plannedBiddingTime">
              <el-date-picker
                clearable
                v-model="queryParams.plannedBiddingTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择计划招标时间"
              />
            </el-form-item>
            <el-form-item label="招标方式(公招，邀标)" prop="plannedBiddingMethod">
              <el-input v-model="queryParams.plannedBiddingMethod" placeholder="请输入招标方式(公招，邀标)" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="总价" prop="price">
              <el-input v-model="queryParams.price" placeholder="请输入总价" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="限价" prop="limitPrice">
              <el-input v-model="queryParams.limitPrice" placeholder="请输入限价" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="合同额" prop="contractPrice">
              <el-input v-model="queryParams.contractPrice" placeholder="请输入合同额" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['plan:plan:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['plan:plan:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" align="center" prop="id" v-if="false" />
        <el-table-column label="项目Id" align="center" prop="projectId" v-if="false" />
        <el-table-column label="分包类型名称" align="center" prop="dictName" />
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="计划招标时间" align="center" prop="plannedBiddingTime" width="180" v-if="false">
          <template #default="scope">
            <span>{{ parseTime(scope.row.plannedBiddingTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="招标方式(公招，邀标)" align="center" prop="plannedBiddingMethod" />
        <el-table-column label="总价" align="center" prop="price" v-if="false" />
        <el-table-column label="限价" align="center" prop="limitPrice" />
        <el-table-column label="合同额" align="center" prop="contractPrice" />
        <el-table-column label="分包内容" align="center" prop="content" />
        <el-table-column label="中标通知书" align="center" prop="bidFile" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['plan:plan:edit']"></el-button>
            </el-tooltip>
          </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>
    <!-- 添加或修改招标计划对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="planFormRef" :model="form" :rules="rules" label-width="120px">
        <!-- 调整项目ID表单项：与目标代码一致，自动关联当前项目并显示提示 -->
        <el-input v-model="form.projectId" placeholder="请输入项目ID" :readonly="!!currentProjectId" :disabled="!!currentProjectId" v-if="false" />
        <template #help>
          <span v-if="currentProjectId" class="text-success">已自动关联当前选中项目</span>
        </template>
        <el-input v-model="form.id" placeholder="ID" readonly v-if="false" />
        <el-form-item label="分包类型名称" prop="dictName" v-if="false">
          <el-input v-model="form.dictName" placeholder="请输入分包类型名称" />
        </el-form-item>

        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="计划招标时间" prop="plannedBiddingTime" v-if="false">
          <el-date-picker clearable v-model="form.plannedBiddingTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择计划招标时间" />
        </el-form-item>

        <el-form-item label="招标方式(公招，邀标)" prop="plannedBiddingMethod">
          <el-input v-model="form.plannedBiddingMethod" placeholder="请输入招标方式(公招，邀标)" />
        </el-form-item>

        <el-form-item label="总价" prop="price" v-if="false">
          <el-input v-model="form.price" placeholder="请输入总价" />
        </el-form-item>

        <el-form-item label="限价" prop="limitPrice">
          <el-input v-model="form.limitPrice" placeholder="请输入限价" />
        </el-form-item>

        <el-form-item label="合同额" prop="contractPrice">
          <el-input v-model="form.contractPrice" placeholder="请输入合同额" />
        </el-form-item>

        <el-form-item label="分包内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入分包内容" rows="3" />
        </el-form-item>

        <el-form-item label="中标通知书" prop="bidFile">
          <file-upload v-model="form.bidFile" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Plan" lang="ts">
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from '@/api/plan/plan';
import { PlanVO, PlanQuery, PlanForm } from '@/api/plan/plan/types';
import { getCurrentInstance, onMounted, ref, reactive, toRefs, computed, watch } from 'vue';
import type { ElFormInstance } from 'element-plus';
import { useUserStoreHook } from '@/store/modules/user';

// 1. 与目标代码一致：从用户Store获取当前选中项目及ID
const userStore = useUserStoreHook();
const currentProject = computed(() => userStore.selectedProject);
const currentProjectId = computed(() => currentProject.value?.id);

// 2. 类型定义（保持原有基础，新增projectId关联）
interface DialogOption {
  visible: boolean;
  title: string;
}

interface PageData<F, Q> {
  form: F;
  queryParams: Q;
  rules: Record<string, any[]>;
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const planList = ref<PlanVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const planFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 3. 初始化表单数据：新增projectId，默认关联当前选中项目ID（与目标代码一致）
const initFormData: PlanForm & { dictName?: string; content?: string } = {
  id: '1958116259107012609',
  projectId: currentProjectId.value, // 初始关联当前项目ID
  plannedBiddingMethod: undefined,
  price: undefined,
  limitPrice: undefined,
  contractPrice: undefined,
  bidFile: undefined,
  dictName: '1',
  name: 'test1',
  content: 'trhbhbt'
};

// 4. 页面数据：查询参数默认携带当前项目ID（与目标代码一致）
const data = reactive<PageData<typeof initFormData, PlanQuery & { dictName?: string; content?: string }>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProjectId.value, // 查询参数默认关联当前项目
    dictName: undefined,
    name: undefined,
    plannedBiddingTime: undefined,
    plannedBiddingMethod: undefined,
    price: undefined,
    limitPrice: undefined,
    contractPrice: undefined,
    content: undefined,
    bidFile: undefined,
    params: {}
  },
  rules: {
    projectId: [{ required: true, message: '请输入项目ID', trigger: 'blur' }], // 新增项目ID必填规则
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    plannedBiddingMethod: [{ required: true, message: '请输入招标方式', trigger: 'blur' }],
    limitPrice: [{ required: true, message: '请输入限价', trigger: 'blur' }],
    contractPrice: [{ required: true, message: '请输入合同额', trigger: 'blur' }],
    content: [{ required: true, message: '请输入分包内容', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 5. 与目标代码一致：监听当前项目ID变化，自动更新查询参数、表单数据并刷新列表
watch(currentProjectId, (newVal) => {
  // 更新查询参数的项目ID
  queryParams.value.projectId = newVal;
  // 新增状态下更新表单项目ID
  if (!form.value.id) {
    form.value.projectId = newVal;
  }
  // 重新加载列表
  getList();
});

/** 查询招标计划列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listPlan(queryParams.value);
    planList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('获取招标计划列表失败', error);
    proxy?.$modal.msgError('获取招标计划列表失败');
  } finally {
    loading.value = false;
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置：重置时保留当前项目ID（与目标代码一致） */
const reset = () => {
  form.value = { ...initFormData, projectId: currentProjectId.value };
  planFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作：保留当前项目ID（与目标代码一致） */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.projectId = currentProjectId.value;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PlanVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 修改按钮操作：回显数据时保留项目ID */
const handleUpdate = async (row?: PlanVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  if (!_id) {
    proxy?.$modal.msgWarning('请选择需要修改的招标计划');
    return;
  }
  try {
    const res = await getPlan(_id);
    Object.assign(form.value, res.data, {
      id: res.data.id || initFormData.id,
      dictName: res.data.dictName || initFormData.dictName,
      content: res.data.content || initFormData.content,
      projectId: res.data.projectId || currentProjectId.value // 确保项目ID正确
    });
    dialog.visible = true;
    dialog.title = '修改招标计划';
  } catch (error) {
    console.error('获取招标计划详情失败', error);
    proxy?.$modal.msgError('获取招标计划详情失败');
  }
};

/** 提交按钮：新增时强制携带当前项目ID（与目标代码一致） */
const submitForm = () => {
  planFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 新增时强制使用当前选中项目ID
        if (!form.value.id && currentProjectId.value) {
          form.value.projectId = currentProjectId.value;
        }
        if (form.value.id) {
          await updatePlan(form.value);
        } else {
          await addPlan(form.value);
        }
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        await getList();
      } catch (error) {
        console.error('操作失败', error);
        proxy?.$modal.msgError('操作失败，请重试');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 删除按钮操作（原有逻辑不变） */
const handleDelete = async (row?: PlanVO) => {
  const _ids = row?.id || ids.value;
  if (!_ids || (_ids instanceof Array && _ids.length === 0)) {
    proxy?.$modal.msgWarning('请选择需要删除的招标计划');
    return;
  }
  try {
    await proxy?.$modal.confirm('是否确认删除选中的招标计划？');
    await delPlan(_ids);
    proxy?.$modal.msgSuccess('删除成功');
    await getList();
  } catch (error) {
    console.error('删除失败', error);
    if (error !== 'cancel') {
      proxy?.$modal.msgError('删除失败，请重试');
    }
  }
};

/** 导出按钮操作（原有逻辑不变） */
const handleExport = () => {
  proxy?.download(
    'plan/plan/export',
    {
      ...queryParams.value
    },
    `plan_${new Date().getTime()}.xlsx`
  );
};

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

<style scoped lang="scss">
.mb-4 {
  margin-bottom: 16px;
}
.el-table .small-padding .cell {
  padding: 0 5px;
}
.el-table .fixed-width {
  width: 120px !important;
}
.el-table-column .el-button--text + .el-button--text {
  margin-left: 10px;
}
</style>
