<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 label="文件类型" prop="fileType">
              <el-select v-model="queryParams.fileType" placeholder="请选择文件类型" clearable>
                <el-option v-for="dict in drawing_file_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item> -->
            <el-form-item label="原文件名" prop="originalName">
              <el-input v-model="queryParams.originalName" placeholder="请输入原文件名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="是否最新" prop="newest">
              <el-select v-model="queryParams.newest" placeholder="请选择" clearable>
                <el-option label="是" :value="1" />
                <el-option label="否" :value="0" />
              </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="['design:drawing:add']">上传图纸</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-tabs type="border-card" v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="过程图纸" name="1">
          <DrawingTable
            :drawingList="drawingList"
            :loading="loading"
            :drawing_file_type="drawing_file_type"
            :wf_business_status="wf_business_status"
            @selection-change="handleSelectionChange"
            @view="handleView"
            @update="handleUpdate"
            @delete="handleDelete"
            @view-info="handleViewInfo"
            @cancel-process-apply="handleCancelProcessApply"
          />
        </el-tab-pane>
        <el-tab-pane label="蓝图" name="2">
          <DrawingTable
            :drawingList="drawingList"
            :loading="loading"
            :drawing_file_type="drawing_file_type"
            :wf_business_status="wf_business_status"
            @selection-change="handleSelectionChange"
            @view="handleView"
            @update="handleUpdate"
            @delete="handleDelete"
            @view-info="handleViewInfo"
            @cancel-process-apply="handleCancelProcessApply"
          />
        </el-tab-pane>
        <el-tab-pane label="变更图纸" name="3">
          <DrawingTable
            :drawingList="drawingList"
            :loading="loading"
            :drawing_file_type="drawing_file_type"
            :wf_business_status="wf_business_status"
            @selection-change="handleSelectionChange"
            @view="handleView"
            @update="handleUpdate"
            @delete="handleDelete"
            @view-info="handleViewInfo"
            @cancel-process-apply="handleCancelProcessApply"
          />
        </el-tab-pane>
      </el-tabs>
      <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="Drawing" lang="ts">
import { listDrawing, getDrawing, delDrawing, addDrawing, updateDrawing } from '@/api/design/drawing';
import { DrawingVO, DrawingQuery, DrawingForm } from '@/api/design/drawing/types';
import { useUserStoreHook } from '@/store/modules/user';
import { LeaveVO } from '@/api/workflow/leave/types';
import { cancelProcessApply } from '@/api/workflow/instance';
import DrawingTable from './DrawingTable.vue';

// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { drawing_file_type, wf_business_status } = toRefs<any>(proxy?.useDict('drawing_file_type', 'wf_business_status'));
console.log(drawing_file_type);

const drawingList = ref<DrawingVO[]>([]);
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 fileList = ref([]); // 存储上传的文件列表
const selectedFile = ref(null); // 当前选中的文件
const queryFormRef = ref<ElFormInstance>();
const drawingFormRef = ref<ElFormInstance>();
const activeName = ref('1');
const dialog = reactive({
  visible: false,
  title: '',
  isEdit: false
});
const initFormData: DrawingForm = {
  id: undefined,
  projectId: currentProject.value?.id,
  versionNumber: undefined,
  fileName: undefined,
  fileUrl: undefined,
  fileType: undefined,
  fileSuffix: undefined,
  originalName: undefined,
  remark: undefined
};
const data = reactive<PageData<DrawingForm, DrawingQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProject.value?.id,
    fileName: undefined,
    fileType: undefined,
    fileSuffix: undefined,
    fileStatus: undefined,
    originalName: undefined,
    newest: undefined,
    params: {}
  },
  rules: {
    versionNumber: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
    fileName: [{ required: true, message: '文件名称不能为空', trigger: 'blur' }],
    fileType: [{ required: true, message: '文件类型不能为空', trigger: 'change' }],
    file: [
      {
        validator: (rule, value, callback) => {
          console.log(dialog.isEdit);
          console.log(fileList.value);

          // 新增时必须上传文件
          if (!dialog.isEdit && !fileList.value.length) {
            callback(new Error('请上传图纸文件'));
          } else {
            callback();
          }
        },
        trigger: 'change'
      }
    ]
  }
});

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

/** 查询图纸管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDrawing(queryParams.value);
  drawingList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  drawingFormRef.value?.resetFields();
  fileList.value = [];
  selectedFile.value = null;
};

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/workflows/drawing/indexEdit`,
    query: {
      type: 'add'
    }
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DrawingVO) => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/workflows/drawing/indexEdit`,
    query: {
      id: row.id,
      type: 'update'
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: DrawingVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除图纸管理编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delDrawing(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleView = (row) => {
  var url = row.file.url;
  window.open(url, '_blank');
};

/** 查看按钮操作 */
const handleViewInfo = (row?: LeaveVO) => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/workflows/drawing/indexEdit`,
    query: {
      id: row.id,
      type: 'view'
    }
  });
};

/** 撤销按钮操作 */
const handleCancelProcessApply = async (id: string) => {
  await proxy?.$modal.confirm('是否确认撤销当前单据？');
  loading.value = true;
  const data = {
    businessId: id,
    message: '申请人撤销流程！'
  };
  await cancelProcessApply(data).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('撤销成功');
};

const handleClick = (val) => {
  queryParams.value.pageNum = 1;
  queryParams.value.fileType = val.props.name;
  getList();
};

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

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