<template>
  <div class="exam-plan pg-main">
    <div class="pg-title">
      <span>考试同步管理</span>
    </div>
    <div class="pg-select-infos">
      <Form ref="queryForm_one" :label-width="80" inline>
        <Row>
          <Col span="6">
            <FormItem label="考试任务" style="width: 100%">
              <Select v-model="query.examCode">
                <Option value="">全部</Option>
                <Option
                  v-for="item in xldata.examCodeList"
                  :value="item.examCode"
                  :key="item.examCode"
                  >{{ item.name }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="同步结果" :label-width="100" style="width: 100%">
              <Select v-model="query.result">
                <Option
                  v-for="item in resultList"
                  :value="item.value"
                  :key="item.value"
                  >{{ item.name }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="任务状态" :label-width="100" style="width: 100%">
              <Select v-model="query.status">
                <Option
                  v-for="item in statusList"
                  :value="item.value"
                  :key="item.value"
                  >{{ item.name }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <Button
              @click="doQuery"
              style="margin-left: 20px"
              type="primary"
              icon="md-search"
              >查询</Button
            >
          </Col>
        </Row>
      </Form>
    </div>
    <div class="pg-body">
      <Table
        ref="table"
        :columns="columns"
        :data="list"
        :disabled-hover="true"
      ></Table>
      <Page
        placement="top"
        :current="query.pageNo"
        :loading="true"
        :page-size="query.pageSize"
        :total="query.totalElements"
        show-total
        show-sizer
        @on-change="changePageNo"
        @on-page-size-change="changePageSize"
      ></Page>
    </div>

    <!-- UploadFileDialog -->
    <UploadFileDialog
      ref="UploadFileDialog"
      :title="uploadSet.title"
      :format="uploadSet.format"
      :max-size="uploadSet.maxSize"
      :upload-url="uploadSet.uploadUrl"
      :upload-data="uploadSet.uploadData"
      :headers="uploadSet.headers"
      @upload-success="uploadSuccess"
    />
  </div>
</template>

<script>
import { axios, baseUrl } from "../../libs/http";
import UploadFileDialog from "./UploadFileDialog";
import util from "../../libs/util";

export default {
  name: "exam_plan_index",
  components: { UploadFileDialog },
  data() {
    return {
      query: {
        pageNo: 1,
        pageSize: 10,
        totalElements: 0,
        totalPages: 0,
        examCode: "",
        status: "",
        result: "",
      },
      xldata: {
        examCodeList: [],
      },
      resultList: [
        {
          name: "全部",
          value: "",
        },
        {
          name: "成功",
          value: "SUCCESS",
        },
        {
          name: "失败",
          value: "ERROR",
        },
      ],
      statusList: [
        {
          name: "全部",
          value: "",
        },
        {
          name: "未开始",
          value: "INIT",
        },
        {
          name: "进行中",
          value: "RUNNING",
        },
        {
          name: "已完成",
          value: "FINISH",
        },
      ],
      columns: [
        {
          type: "index_seq",
          title: "序号",
          align: "center",
          width: 80,
          render: (h, params) => {
            let a =
              (this.query.pageNo - 1) * this.query.pageSize + params.index + 1;
            return h("span", a);
          },
        },
        {
          title: "任务名称",
          key: "name",
          minWidth: 200,
        },
        {
          title: "考试识别码",
          key: "examCode",
          width: 140,
        },
        {
          title: "任务结果",
          key: "result",
          width: 120,
          render: (h, params) => {
            let obj = {
              SUCCESS: "成功",
              ERROR: "失败",
            };
            // if (params.row.result) {
            //   return h("span", obj[params.row.result]);
            // } else {
            //   return h("span");
            // }
            const doms = [h("span", obj[params.row.result])];
            if (!params.row.summary) {
              return h("div", doms);
            }

            doms.push(
              h(
                "Tooltip",
                {
                  props: {
                    content: params.row.summary,
                    placement: "top",
                    maxWidth: 400,
                  },
                },
                [
                  h(
                    "Icon",
                    {
                      props: {
                        size: "18",
                        type: "md-information-circle",
                        color: "#808080",
                      },
                      style: {
                        padding: "0 0 0 5px",
                        marginTop: "-3px",
                        cursor: "pointer",
                      },
                    },
                    ""
                  ),
                ]
              )
            );
            return h("div", doms);
          },
        },
        {
          title: "任务状态",
          key: "status",
          width: 120,
          render: (h, params) => {
            let obj = {
              INIT: "未开始",
              RUNNING: "进行中",
              FINISH: "已完成",
            };
            if (params.row.status) {
              return h("span", obj[params.row.status]);
            } else {
              return h("span");
            }
          },
        },
        {
          title: "进度",
          key: "progress",
          width: 100,
          render: (h, params) => {
            if (params.row.progress !== null) {
              return h("span", params.row.progress + "%");
            } else {
              return h("span");
            }
          },
        },
        {
          title: "创建时间",
          key: "createTime",
          width: 190,
          render: (h, params) => {
            if (params.row.createTime) {
              return h("span", util.dateFormat(params.row.createTime));
            } else {
              return h("span", "");
            }
          },
        },
        {
          title: "操作",
          key: "show_more",
          align: "center",
          width: 240,
          render: (h, params) => {
            const canSync =
              !params.row.status ||
              (params.row.status && params.row.status === "INIT") ||
              (params.row.status &&
                params.row.status === "FINISH" &&
                params.row.result !== "SUCCESS");
            const cannotUpload =
              params.row.status && params.row.status === "RUNNING";

            return h("div", [
              h(
                "Tooltip",
                {
                  props: {
                    content: "同步",
                    placement: "top",
                  },
                },
                [
                  h(
                    "Button",
                    {
                      props: {
                        disabled: !canSync,
                        type: "text",
                      },
                      style: {
                        padding: "0 10px",
                      },
                      on: {
                        click: () => {
                          this.doSync(params.row);
                        },
                      },
                    },
                    [
                      h(
                        "Icon",
                        {
                          props: {
                            size: "22",
                            type: "ios-redo",
                          },
                        },
                        ""
                      ),
                    ]
                  ),
                ]
              ),
              h(
                "Tooltip",
                {
                  props: {
                    content: "上传答案",
                    placement: "top",
                  },
                },
                [
                  h(
                    "Button",
                    {
                      props: {
                        disabled: cannotUpload,
                        type: "text",
                      },
                      style: {
                        padding: "0 10px",
                      },
                      on: {
                        click: () => {
                          this.doUpload(params.row);
                        },
                      },
                    },
                    [
                      h(
                        "Icon",
                        {
                          props: {
                            size: "22",
                            type: "md-cloud-upload",
                          },
                        },
                        ""
                      ),
                    ]
                  ),
                ]
              ),
              h(
                "Tooltip",
                {
                  props: {
                    content: "清除",
                    placement: "top",
                  },
                },
                [
                  h(
                    "Button",
                    {
                      props: {
                        type: "text",
                      },
                      style: {
                        padding: "0 10px",
                      },
                      on: {
                        click: () => {
                          this.doClean(params.row);
                        },
                      },
                    },
                    [
                      h(
                        "Icon",
                        {
                          props: {
                            size: "22",
                            type: "ios-trash",
                          },
                        },
                        ""
                      ),
                    ]
                  ),
                ]
              ),
            ]);
          },
        },
      ],
      list: [],
      curRow: {},
      loopRunning: false,
      loopSetTs: [],
      hideLoading: false,
      // upload
      uploadSet: {
        title: "上传答案",
        format: ["zip", "rar"],
        maxSize: 100 * 1024,
        uploadUrl: "",
        uploadData: {},
        headers: {},
      },
    };
  },
  created() {
    let _q = this.$route.query._q;
    if (_q) {
      let query = JSON.parse(_q);
      this.query.pageNo = query.pageNo;
    }
    this.xldata.examCodeList = [];
    axios.post("/system/kj/hz/getPlans", {}).then((response) => {
      let data = response.data.data;
      if (data) {
        this.xldata.examCodeList = data;
      }
    });
    this.uploadSet.headers = {
      "authorization-token": this.$store.state.user.accessToken,
      schoolId: this.$store.state.user.schoolId,
    };
    this.load();
  },
  beforeDestroy() {
    this.loopRunning = false;
    this.clearLoopSetTs();
  },
  methods: {
    clearLoopSetTs() {
      if (!this.loopSetTs.length) return;
      this.loopSetTs.forEach((sett) => {
        clearTimeout(sett);
      });
      this.loopSetTs = [];
    },
    async timerUpdatePage() {
      this.clearLoopSetTs();
      if (!this.loopRunning) return;

      await this.getList().catch(() => {});
      this.hideLoading = true;

      this.loopSetTs.push(
        setTimeout(() => {
          this.timerUpdatePage();
        }, 10 * 1000)
      );
    },
    doSync(row) {
      let _$ = this;
      this.$Modal.confirm({
        title: "系统提示",
        content: "确定要开始同步当前任务吗？",
        onOk() {
          axios
            .post("/system/exam/task/sync", {
              examCode: row.examCode,
            })
            .then((response) => {
              let data = response.data;
              if (data.code == 0) {
                _$.load();
                this.$Notice.success({
                  title: "系统提示",
                  desc: "<p>同步已经开始</p>",
                });
              }
            });
        },
      });
    },
    doUpload(row) {
      this.uploadSet.uploadUrl = `${baseUrl}/system/exam/task/${row.examCode}/${row.examType}`;
      this.$refs.UploadFileDialog.open();
    },
    doClean(row) {
      let _$ = this;
      this.$Modal.confirm({
        title: "系统提示",
        content: "确定要清除当前任务吗？",
        onOk() {
          axios
            .post("/system/exam/task/clean", {
              examCode: row.examCode,
            })
            .then((response) => {
              let data = response.data;
              if (data.code == 0) {
                _$.load();
                this.$Notice.success({
                  title: "系统提示",
                  desc: "<p>操作成功</p>",
                });
              }
            });
        },
      });
    },
    uploadSuccess() {
      this.$refs.UploadFileDialog.cancel();
      this.$Message.success("上传成功！");
    },
    async load() {
      this.hideLoading = false;
      this.loopRunning = true;
      this.timerUpdatePage();
    },
    async getList() {
      const response = await axios
        .post("/system/exam/task/query", this.query, {
          hideLoading: this.hideLoading,
        })
        .catch(() => {});
      if (!response) return;
      let data = response.data.data;
      if (data) {
        this.list = data.content || [];
        this.query.totalElements = data.totalElements;
        this.query.totalPages = data.totalPages;
      }
    },
    doQuery() {
      this.query.pageNo = 1;
      this.load();
    },
    changePageNo(p) {
      //切换页码
      this.query.pageNo = p;
      this.load();
    },
    changePageSize(pageSize) {
      //切换每一页显示多少条
      this.query.pageSize = pageSize;
      this.load();
    },
  },
};
</script>
