<template>
  <div class="app-container">
    <div class="top-bar">
      <SearchBar :config="searchConfig" @search="search" @reset="reset" />
    </div>
    <TablePage
      :data="list.records"
      :tableTitle="approvleTableTitle"
      :operates="operates"
      v-loading="loading"
    >
      <template v-slot:checkStatus="{ scope }">
        <el-tag
          :type="
            $constantsTool.getTagTypeByValue('checkStatus', scope.checkStatus)
          "
          >{{
            $constantsTool.getLabelByValue("checkStatus", scope.checkStatus)
          }}</el-tag
        >
      </template>
      <template v-slot:operates="{ scope }">
        <TableOperation
          :operations="getOperation(scope)"
          :rawData="scope"
          @handleOperation="handleOperation"
        >
        </TableOperation>
      </template>
    </TablePage>
    <el-pagination
      style="margin: 16px 0"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="Number(list.current)"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="Number(list.size)"
      layout="total, sizes, prev, pager, next, jumper"
      :total="Number(list.total)"
      class="pagination"
    >
    </el-pagination>
    <PreviewDialog
      ref="PreviewDialog"
      :detail="aprrovalDetail"
      :prviewType="prviewType"
      :dicts="dicts"
      @handleClose="handleClosePreviewDialog"
      @refresh="loadData"
    />
    <CrInfoEditDialog
      ref="CrInfo"
      :form="resubmitCrInfo"
      @refresh="loadData"
      :flowId="currentFlowId"
    />
    <DisplayInfoEditDialog
      ref="DisplayInfo"
      :form="resubmitDisplayInfo"
      @refresh="loadData"
      :flowId="currentFlowId"
    />
    <UploadDialog
      ref="UploadDialog"
      @update="loadData"
      :options="resubmitOptions"
    />
  </div>
</template>

<script>
import PreviewDialog from "./components/PreviewDialog.vue";
import CrInfoEditDialog from "@/views/culturalRelic/components/InfoEditDialog";
import DisplayInfoEditDialog from "@/views/display/components/InfoEditDialog";
import UploadDialog from "@/components/UploadDialog";
import {
  approvleTableTitle,
  operates,
  viewButton,
  approvalButton,
  reSubmitButtton,
} from "./config";
import {
  getFlowListPagePer,
  getFlowDetailById,
  getSourceDetailById,
} from "@/api/approval";
import { mapGetters } from "vuex";

export default {
  components: {
    PreviewDialog,
    CrInfoEditDialog,
    DisplayInfoEditDialog,
    UploadDialog,
  },
  // provide必须返回一个对象，不然更新后无法获取最新的值
  provide() {
    return {
      loadData: this.loadData,
    };
  },
  data() {
    return {
      list: {
        record: [],
        size: 10,
        current: 1,
        total: 0,
      },
      searchParams: {}, //记录SearchForm中的搜索条件
      searchConfig: [
        {
          prop: "title",
          type: "input",
          label: "标题",
        },
        {
          prop: "sourceType",
          type: "select",
          label: "资源类型",
          selectOptions: [
            {
              label: "文物",
              value: "文物",
            },
            {
              label: "展览展示",
              value: "展览展示",
            },
          ],
        },
        {
          prop: "addWay",
          type: "select",
          label: "添加方式",
          selectOptions: [
            {
              label: "批量导入",
              value: "批量导入",
            },
            {
              label: "整量导入",
              value: "整量导入",
            },
            {
              label: "手动添加",
              value: "手动添加",
            },
          ],
        },
        {
          prop: "checkStatus",
          type: "select",
          label: "审核状态",
          selectOptions: this.$constantsTool.getList("checkStatus"),
        },
      ],
      loading: false,
      previewDialogVisible: false, //预览可见性
      aprrovalDetail: {}, //审核的相关信息
      prviewType: "view", //预览类型，view-查看详情，approval-审批
      operates,
      approvleTableTitle,
      currentFlowId: "", //当前点击的流程的ID
      resubmitCrInfo: {}, //重传的手动添加的文物信息
      resubmitDisplayInfo: {}, //重传的手动添加的展览信息
      resubmitCrMulti: {}, //重传的批量导入的文物信息
      resubmitDisplayMulti: {}, //重传的整量导入的展览信息
      resubmitOptions: {
        recordsTitle: "", //上传时的记录标题,非必填
        bizType: "", //业务类型，文物、展览等biz_cultural_relic——文物，biz_exhibition——展览，如果是文物和展览批量上传必填，抠图不用填
        uploadUrl: process.env.VUE_APP_BASE_API + "/bizImport/importZip", //上传的地址，必填
        flowId: "", //流程ID,重传时需要，非必填
      },
    };
  },
  computed: {
    ...mapGetters(["dicts", "userInfo"]),
    getOperation(row) {
      return (row) => {
        switch (row.checkStatus) {
          case 0:
            // 审核中
            return [viewButton, approvalButton];
          case 1:
            // 已通过
            return [viewButton];
          case -2:
            // 已驳回
            return [viewButton, reSubmitButtton];
        }
      };
    },
  },
  async created() {
    this.loadData();
  },
  methods: {
    // 搜索
    async search(form) {
      // 记录搜索的参数
      this.searchParams = form;
      // 重置分页到第一页
      this.resetPage();
      this.loadData(form);
    },
    // 重置
    reset() {
      this.searchParams = {};
      this.loadData();
    },
    // 清除分页到初始状态
    resetPage() {
      this.list.current = 1;
    },
    // 加载数据
    async loadData(form) {
      this.loading = true;
      let params = {
        page: this.list.current,
        limit: this.list.size,
      };
      const queryParams = form || this.searchParams;
      if (Object.keys(queryParams)) {
        params = { ...params, ...queryParams };
      }
      let res = await getFlowListPagePer(params);
      if (res.code == 0) {
        this.list = res.data;
      }
      this.loading = false;
    },
    // 表格操作
    handleOperation(value, row) {
      const { type, id } = value;
      this.currentFlowId = id;
      if (type == "view" || type == "approval") {
        this.viewOrApproval(type, row);
      } else {
        // 重新上传
        this.resubmit(row);
      }
    },
    // 编辑或者审核，（都要查看详情，审核多了个表单）
    async viewOrApproval(type, row) {
      this.prviewType = type;
      const { id } = row;
      const res = await getFlowDetailById(id);
      if (res.code == 0) {
        this.aprrovalDetail = res.data;
        this.$refs.PreviewDialog.visible = true;
      } else {
        return;
      }
    },
    // 重新上传
    async resubmit(row) {
      const { addWay, sourceType, id, title } = row;
      const isManual = addWay == "手动添加";
      this.resubmitOptions.flowId = id;
      switch (sourceType) {
        case "文物":
          if (isManual) {
            const data = await this.getSourceDetail(id);
            console.log(data);
            this.resubmitCrInfo = data;
            this.$appCommon.openDialog(this, "CrInfo");
          } else {
            this.resubmitOptions.recordsTitle = title;
            this.resubmitOptions.bizType = "biz_cultural_relic";
            this.$appCommon.openDialog(this, "UploadDialog");
          }
          break;
        case "展览展示":
          if (isManual) {
            const data = await this.getSourceDetail(id);
            this.resubmitDisplayInfo = data;
            this.resubmitOptions.bizType = "biz_exhibition";
            this.$appCommon.openDialog(this, "DisplayInfo");
          } else {
            this.resubmitOptions.recordsTitle = title;
            this.$appCommon.openDialog(this, "UploadDialog");
          }
          break;
      }
    },
    // 获取资源详情
    getSourceDetail(id) {
      return new Promise(async (resolve, reject) => {
        try {
          const params = {
            id,
          };
          const res = await getSourceDetailById(params);
          if (res.code == 0) {
            resolve(res.data);
          } else {
            reject(false);
          }
        } catch (error) {
          reject(error);
        }
      });
    },

    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 改变页容量
    handleSizeChange(value) {
      this.list.size = value;
      this.loadData();
    },

    // 改变当前显示页
    handleCurrentChange(value) {
      this.list.current = value;
      this.loadData();
    },
    // 关闭预览图片
    closeImgViewer() {
      this.imgViewerVisible = false;
    },
    // 预览图片
    handelPreviewImages(images) {
      this.imgViewerVisible = true;
      this.imgList = [images];
    },

    handleClosePreviewDialog() {
      this.previewDialogVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.top-bar {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  height: 68px;
}

.tools {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 14px;

  .tools-item {
    display: flex;

    &:last-child {
      justify-content: flex-end;
    }
  }
}
</style>
