<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="fileName">
              <el-input v-model="queryParams.fileName" placeholder="请输入文件名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery" v-hasPermi="['design:prelimScheme:list']">搜索</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="['design:prelimScheme:add']">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="schemeList" @selection-change="handleSelectionChange">
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column label="文件名称" align="center" prop="fileName">
          <template #default="scope">
            <el-link type="primary" :href="scope.row.fileUrl" target="_blank" :underline="false">
              {{ scope.row.fileName }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="wf_business_status" :value="scope.row.status"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              link
              type="primary"
              v-if="scope.row.status !== 'draft'"
              icon="Edit"
              @click="handleView(scope.row)"
              v-hasPermi="['design:prelimScheme:query']"
              >查看流程</el-button
            >
            <el-button
              link
              type="primary"
              v-if="scope.row.status === 'draft'"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['design:prelimScheme:edit']"
              >修改</el-button
            >
            <!-- <el-button
              link
              type="primary"
              v-if="scope.row.status === 'draft'"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['design:PrelimScheme:remove']"
              >删除</el-button
            > -->
          </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>
  </div>
</template>

<script setup name="Scheme" lang="ts">
import { listPrelimScheme, getPrelimScheme, delPrelimScheme, addPrelimScheme, updatePrelimScheme } from '@/api/design/prelimScheme';
import { PrelimSchemeVO, PrelimSchemeQuery, PrelimSchemeForm } from '@/api/design/prelimScheme/types';
import { useUserStoreHook } from '@/store/modules/user';
import { useRoute } from 'vue-router';
const route = useRoute();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wf_business_status } = toRefs<any>(proxy?.useDict('wf_business_status'));
// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const schemeList = ref<PrelimSchemeVO[]>([]);
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 schemeFormRef = ref<ElFormInstance>();

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

const initFormData: PrelimSchemeForm = {
  id: undefined,
  projectId: currentProject.value?.id,
  ossId: undefined,
  fileName: undefined,
  fileUrl: undefined,
  status: undefined
};
const data = reactive<PageData<PrelimSchemeForm, PrelimSchemeQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProject.value?.id,

    ossId: undefined,
    fileName: undefined,
    fileUrl: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    projectId: [{ required: true, message: '项目id不能为空', trigger: 'blur' }],
    ossId: [{ required: true, message: 'ossId不能为空', trigger: 'blur' }],
    fileName: [{ required: true, message: '文件名称不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '审核状态不能为空', trigger: 'change' }]
  }
});

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

/** 查询设计初步方案列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPrelimScheme(queryParams.value);

  schemeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  proxy.$tab.closePage(route);
  proxy.$tab.openPage('/approval/prelimScheme/indexEdit', '', {
    type: 'add'
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: PrelimSchemeVO) => {
  proxy.$tab.closePage(route);

  proxy.$tab.openPage(`/approval/prelimScheme/indexEdit`, '', {
    id: row.id,
    type: 'update'
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: PrelimSchemeVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除设计初步方案编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delPrelimScheme(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleView = (row?: PrelimSchemeVO) => {
  proxy.$tab.closePage(route);
  proxy.$tab.openPage(`/approval/prelimScheme/indexEdit`, '', {
    id: row.id,
    type: 'view'
  });
};

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

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

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