<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="nodeName">
              <el-input v-model="queryParams.nodeName" placeholder="请输入节点名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in project_construction_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </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="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['progress:constructionSchedulePlan:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref="constructionSchedulePlanTableRef"
        v-loading="loading"
        :data="constructionSchedulePlanList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <!-- <el-table-column label="序号" type="id" /> -->
        <el-table-column label="节点名称" prop="nodeName" />
        <el-table-column label="对应项目结构" align="center" prop="projectStructure" />
        <el-table-column label="预计开始时间" align="center" prop="planStartDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.planStartDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预计结束时间" align="center" prop="planEndDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.planEndDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际开始时间" align="center" prop="practicalStartDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.practicalStartDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际结束时间" align="center" prop="practicalEndDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.practicalEndDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="project_construction_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <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="['progress:constructionSchedulePlan:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['progress:constructionSchedulePlan:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['progress:constructionSchedulePlan:remove']"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改施工进度计划对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="constructionSchedulePlanFormRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="父节点" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="constructionSchedulePlanOptions"
            :props="{ value: 'id', label: 'nodeName', children: 'children' }"
            value-key="id"
            placeholder="请选择父节点"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="节点名称" prop="nodeName">
          <el-input v-model="form.nodeName" placeholder="请输入节点名称" />
        </el-form-item>
        <el-form-item label="对应项目结构" prop="projectStructure">
          <el-input v-model="form.projectStructure" placeholder="请输入对应项目结构" />
        </el-form-item>
        <el-form-item label="预计开始时间" prop="planStartDate">
          <el-date-picker clearable v-model="form.planStartDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择预计开始时间" />
        </el-form-item>
        <el-form-item label="预计结束时间" prop="planEndDate">
          <el-date-picker clearable v-model="form.planEndDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择预计结束时间" />
        </el-form-item>
        <el-form-item label="实际开始时间" prop="practicalStartDate">
          <el-date-picker
            clearable
            v-model="form.practicalStartDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择实际开始时间"
          />
        </el-form-item>
        <el-form-item label="实际结束时间" prop="practicalEndDate">
          <el-date-picker
            clearable
            v-model="form.practicalEndDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择实际结束时间"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="dict in project_construction_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </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="ConstructionSchedulePlan" lang="ts">
import {
  listConstructionSchedulePlan,
  getConstructionSchedulePlan,
  delConstructionSchedulePlan,
  addConstructionSchedulePlan,
  updateConstructionSchedulePlan
} from '@/api/progress/constructionSchedulePlan';
import {
  ConstructionSchedulePlanVO,
  ConstructionSchedulePlanQuery,
  ConstructionSchedulePlanForm
} from '@/api/progress/constructionSchedulePlan/types';
import { useUserStoreHook } from '@/store/modules/user';

type ConstructionSchedulePlanOption = {
  id: number;
  nodeName: string;
  children?: ConstructionSchedulePlanOption[];
};
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);

const { project_construction_status } = toRefs<any>(proxy?.useDict('project_construction_status'));

const constructionSchedulePlanList = ref<ConstructionSchedulePlanVO[]>([]);
const constructionSchedulePlanOptions = ref<ConstructionSchedulePlanOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const constructionSchedulePlanFormRef = ref<ElFormInstance>();
const constructionSchedulePlanTableRef = ref<ElTableInstance>();

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

const initFormData: ConstructionSchedulePlanForm = {
  id: undefined,
  projectId: currentProject.value?.id,
  parentId: undefined,
  nodeName: undefined,
  projectStructure: undefined,
  planStartDate: undefined,
  planEndDate: undefined,
  practicalStartDate: undefined,
  practicalEndDate: undefined,
  status: undefined,
  remark: undefined
};

const data = reactive<PageData<ConstructionSchedulePlanForm, ConstructionSchedulePlanQuery>>({
  form: { ...initFormData },
  queryParams: {
    projectId: currentProject.value?.id,
    parentId: undefined,
    nodeName: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    projectId: [{ required: true, message: '项目ID不能为空', trigger: 'blur' }],
    parentId: [{ required: true, message: '父ID不能为空', trigger: 'blur' }],
    nodeName: [{ required: true, message: '节点名称不能为空', trigger: 'blur' }],
    planStartDate: [{ required: true, message: '预计开始时间不能为空', trigger: 'blur' }],
    planEndDate: [{ required: true, message: '预计结束时间不能为空', trigger: 'blur' }]
  }
});

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

/** 查询施工进度计划列表 */
const getList = async () => {
  loading.value = true;
  const res = await listConstructionSchedulePlan(queryParams.value);
  const data = proxy?.handleTree<ConstructionSchedulePlanVO>(res.data, 'id', 'parentId');
  console.log('🚀 ~ getList ~ data:', data);

  if (data) {
    constructionSchedulePlanList.value = data;
    loading.value = false;
  }
};

/** 查询施工进度计划下拉树结构 */
const getTreeselect = async () => {
  const res = await listConstructionSchedulePlan();
  constructionSchedulePlanOptions.value = [];
  const data: ConstructionSchedulePlanOption = { id: 0, nodeName: '顶级节点', children: [] };
  data.children = proxy?.handleTree<ConstructionSchedulePlanOption>(res.data, 'id', 'parentId');
  constructionSchedulePlanOptions.value.push(data);
};

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

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  constructionSchedulePlanFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = (row?: ConstructionSchedulePlanVO) => {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = '添加施工进度计划';
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(constructionSchedulePlanList.value, isExpandAll.value);
};

/** 展开/折叠操作 */
const toggleExpandAll = (data: ConstructionSchedulePlanVO[], status: boolean) => {
  data.forEach((item) => {
    constructionSchedulePlanTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row: ConstructionSchedulePlanVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getConstructionSchedulePlan(row.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改施工进度计划';
};

/** 提交按钮 */
const submitForm = () => {
  constructionSchedulePlanFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateConstructionSchedulePlan(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addConstructionSchedulePlan(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: ConstructionSchedulePlanVO) => {
  await proxy?.$modal.confirm('是否确认删除施工进度计划编号为"' + row.id + '"的数据项？');
  loading.value = true;
  await delConstructionSchedulePlan(row.id).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getList();
});

//监听项目id刷新数据
const listeningProject = watch(
  () => currentProject.value?.id,
  (nid, oid) => {
    queryParams.value.projectId = nid;
    form.value.projectId = nid;
    getList();
  }
);

onUnmounted(() => {
  listeningProject();
});
</script>
