<template>
  <div class="studyRecordTable">
    <div class="studyStyle" :class="{ 'isFixed': headerFixed }" :style="{'left':left}">
      <div class="a_style">
        <i></i>
        <span>视频审核进度</span>
        <div class="flex_style_study">
          <div class="num_style" style="color: #0047d0">
            待审：{{ userData.pending }}节
          </div>
          <div class="num_style" style="color: #e53935">
            作弊：{{ userData.cheat }}节
          </div>
          <div class="num_style" style="color: #43a047">
            通过：{{ userData.pass }}节
          </div>
          <div style="clear: both"></div>
        </div>
      </div>
      <div class="a_style">
        <i></i>
        <span>做题审核进度</span>
        <div class="flex_style_study">
          <div class="num_style" style="color: #0047d0">
            待审：{{ userData.examPending }}节
          </div>
          <div class="num_style" style="color: #e53935">
            作弊：{{ userData.examCheat }}节
          </div>
          <div class="num_style" style="color: #43a047">
            通过：{{ userData.examPass }}节
          </div>
          <div style="clear: both"></div>
        </div>
      </div>
      <div class="a_style" style="width: 280px">
        <i></i>
        <span>学时审批状态</span>
        <div class="flex_style_study">
          <div class="num_style" style="color: #0047d0">
            {{
                ["不可审核", "未通过", "通过审核", "待审核", "审核中"][
                periodStatus + 1
                ]
            }}
          </div>
          <div style="clear: both"></div>
        </div>
      </div>
      <div class="s_sd">
        <template v-if="periodStatus === 2">
          <el-checkbox :disabled="!allIds.length" :indeterminate="isIndeterminate" v-model="checkAll"
            @change="handleCheckAllChange">待审全选</el-checkbox>
          <el-button style="margin-left: 10px" size="mini" type="success" @click="getChangeStatus(1)">勾选通过</el-button>
          <el-button size="mini" type="danger" @click="getChangeStatus(2)">勾选作弊</el-button>
        </template>

        <template v-if="periodStatus === 3">
          <el-button style="margin-left: 10px" size="mini" @click="checkBack">勾选数据，打回待审核状态</el-button>
          <el-button size="mini" type="warning" @click="approvedOK = true">确认审核通过结果</el-button>
        </template>
        <!-- <el-button
          v-if="periodStatus === 1"
          style="margin-left: 10px"
          size="mini"
          @click="backToAudit"
          >打回待审核状态</el-button
        > -->
      </div>
    </div>

    <el-checkbox-group v-model="checkList" @change="handleCheckedCitiesChange">
      <component :is="keys[key]" v-for="key in Object.keys(tablesData)" :key="key" :tabledata="tablesData[key]"
        :label="key == 5 ? '卷' : '章'"></component>
    </el-checkbox-group>

    <Cheat-dialog :disabledBtn="disabledBtn" :vidBoxHours.sync="vidBoxHours" @close="loadingClose" @submit="
      (reason) => {
        submitOK(2, reason);
      }
    "></Cheat-dialog>
    <Base-dialog title="操作提示：" :disabledBtn="disabledBtn" :isShow.sync="through" @close="loadingClose" @submit="
      () => {
        submitOK(1);
      }
    ">
      <div>
        确定所勾选的内容，审核结果为【通过】？<br />
        确认后，初审不可再修改，请检查清楚再操作！
      </div>
    </Base-dialog>
    <Base-dialog title="操作提示：" :disabledBtn="disabledBtn" :isShow.sync="popback" @close="loadingClose"
      @submit="uploadForm">
      <div>
        <div style="color: red">
          <h4 style="margin: 0px">当前勾选了{{ checkList.length }}条数据：</h4>
          <ul style="margin: 0px 0px 6px; max-height: 500px; overflow: auto">
            <li v-for="(item, index) in checkList" :key="index">
              {{ index + 1 }}.{{ getSecName(item) }}
            </li>
          </ul>
        </div>
        <div style="text-align: center; font-weight: bold">
          所选数据，确定要打回待审核状态吗？<br />
          打回后，重新走审核流程，请慎重操作。
        </div>
      </div>
    </Base-dialog>
    <Base-dialog title="操作提示：" :disabledBtn="disabledBtn" :isShow.sync="approvedOK" @close="loadingClose"
      @submit="approvedOKFunc">
      <div>
        <div style="color: red">
          <h4 style="margin: 0px">确认审核通过结果后：</h4>
          <ul style="margin: 0px 0px 6px">
            <li>
              （1）有做官方接口的，自动触发【学时官方推送】<br />
              （2）公开【学习学时记录-学时记录】按钮，权限人可查看【审核结果】<br />
              （3）有匹配的预约考试，可走预约流程
            </li>
          </ul>
        </div>
        <div style="font-weight: bold; margin-top: 20px">
          确认提交审核通过结果？<br />
          确认后，不能再修改，请慎重操作。
        </div>
      </div>
    </Base-dialog>
  </div>
</template>

<script>
import ModulTable from "./ModulTable.vue";
import ChapterTable from "./ChapterTable.vue";
import LessonTable from "./LessonTable.vue";
import CheatDialog from "./CheatDialog.vue";
import { rollBackPeriod } from "@/api/education/classManageMent";
import { debounce } from '@/utils'
import { mapGetters } from "vuex";
export default {
  props: {
    tablesData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    userData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    setData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    getUserInfo: {
      type: Function,
      default: () => { },
    },
  },
  provide() {
    return {
      getPeriodStatus: () => this.periodStatus,
      getUserInfo: this.getUserInfo,
      getAllIds: () => this.allIds,
    };
  },
  data() {
    return {
      checkList: [],
      allIds: [],
      checkAll: false,
      isIndeterminate: false,
      vidBoxHours: false,
      through: false,
      popback: false,
      approvedOK: false,
      disabledBtn: false,
      formData: {
        cheating_reason: "",
      },
      statusPop: "", //1单个2批量
      rules: {
        cheating_reason: [
          {
            required: true,
            message: "请填写作弊原因",
            trigger: ["blur", "change"],
          },
        ],
      },
      msgTitle: [
        { label: "学习拍照异常", value: 1 },
        {
          label: "学习拍照太黑无法识别人像，请确保拍照光线充足并拍到全脸",
          value: 2,
        },
        {
          label: "学习拍照太模糊无法识别人像，请确保拍照光线充足并拍到全脸",
          value: 3,
        },
        {
          label: "学习拍照人像不全无法识别，请确保拍照光线充足并拍到全脸",
          value: 4,
        },
      ],
      allType3List: [],
      offsetTop: 0,
      offsetHeight: 0,
      headerFixed: false
    };
  },
  methods: {
    handleScroll() {
      // 得到页面滚动的距离
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      // 判断页面滚动的距离是否大于吸顶元素的位置
      this.headerFixed = scrollTop > (this.offsetTop + this.offsetHeight);
    },
    submitAllSlect(reason) {
      this.submitOK(2, reason);
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      if (checkedCount) {
        this.checkAll = checkedCount === this.allIds.length;
      } else {
        this.checkAll = false;
      }
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.allIds.length;
    },
    handleCheckAllChange(val) {
      this.checkList = val ? this.allIds : [];
      this.isIndeterminate = false;
    },
    getAllId(data) {
      if (!data || !data.length) {
        return;
      }
      data.forEach((ele) => {
        if (ele.type == 3 || ele.type == 4) {
          this.allType3List.push(ele);
          ele.status === 2 && this.allIds.push(ele.periodStatusId);
        } else {
          if (ele.type == 1 && ele.arr) {
            let item = ele.arr[0];
            this.allType3List.push(item);
            item.status === 2 && this.allIds.push(item.periodStatusId);
          }
          this.getAllId(
            ele.type == 1 ? ele.classPeriods : ele.classPeriodSectionList
          );
        }
      });
    },
    getChangeStatus(int) {
      if (!this.checkList.length) {
        this.$message.warning("请勾选需要操作的待审核数据");
        return;
      }
      var data = {
        gradeId: Number(this.setData.id),
        userId: Number(this.setData.userId),
        goodsId: Number(this.setData.goodsId),
      };
      if (int === 1) {
        data.status = 1;
        this.through = true;
      }
      if (int === 2) {
        data.status = 0;
        this.statusPop = 2;
        this.formData.cheating_reason = "";
        this.vidBoxHours = true;
      }
    },
    loadingClose() {
      this.disabledBtn = false;
    },
    submitOK(int, msg) {
      this.disabledBtn = true;
      var data = {
        gradeId: Number(this.setData.id),
        userId: Number(this.setData.userId),
        goodsId: Number(this.setData.goodsId),
        ids: this.checkList,
      };
      if (int === 1) {
        data.status = 1;
      }
      if (int === 2) {
        data.auditReason = msg;
        data.status = 0;
      }
      this.$api
        .editGradeUsereditPeriodeAll(data)
        .then((res) => {
          if (int === 1) {
            this.$message.success("状态全部通过修改成功");
            this.through = false;
            this.checkAll && this.goReview();
          }
          if (int === 2) {
            this.$message.success("状态全部作弊修改成功");
            this.vidBoxHours = false;
          }
          this.checkList = [];
          this.isIndeterminate = false;
          this.checkAll = false;
          this.getUserInfo(true);
        })
        .catch(() => {
          this.disabledBtn = false;
        });
    },
    getSecName(id) {
      try {
        return this.allType3List.find((e) => e.periodStatusId == id).typeName;
      } catch (error) {
        return "";
      }
    },
    uploadText(msg) {
      this.formData.cheating_reason = msg;
    },
    checkBack() {
      if (!this.checkList.length) {
        this.$message.warning("请勾选数据");
        return;
      }
      this.popback = true;
    },
    // 打回审核状态
    uploadForm() {
      this.disabledBtn = true;
      let data = {
        gradeId: Number(this.setData.id),
        userId: Number(this.setData.userId),
        goodsId: Number(this.setData.goodsId),
        ids: this.checkList,
      };
      this.$api
        .editGradeUsereditrollbackPeriod(data)
        .then((res) => {
          this.checkList = []; //勾选列表
          this.isIndeterminate = false; //待审半选
          this.checkAll = false; //全选状态
          this.getUserInfo(true);
          this.$message.success("已打回待审核状态");
          this.popback = false;
          this.goReview();
        })
        .catch(() => {
          this.disabledBtn = false;
        });
    },
    // 确认审核结果
    approvedOKFunc() {
      this.disabledBtn = true;
      let data = {
        gradeId: Number(this.setData.id),
        userId: Number(this.setData.userId),
        goodsId: Number(this.setData.goodsId),
      };
      this.$api
        .editGradeUsereditrollconfirmPeriod(data)
        .then((res) => {
          this.getUserInfo(true);
          this.$message.success("审核通过");
          this.approvedOK = false;
          this.goReview();
        })
        .catch(() => {
          this.disabledBtn = false;
        });
    },
    backToAudit() {
      this.$confirm("此操作将打回审核状态, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          rollBackPeriod({ orderGoodsId: this.userData.orderGoodsId }).then(
            (res) => {
              this.getUserInfo(true);
              this.$message.success("已打回待审核状态");
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    goReview() {
      this.$router.push({
        name: "ListOfhoursToBeReviewed",
      });
    },
  },

  created() {
    this.keys = {
      1: "ModulTable",
      2: "ChapterTable",
      5: "ChapterTable",
      6: "LessonTable",
    };
  },
  components: { ModulTable, LessonTable, ChapterTable, CheatDialog },
  watch: {
    tablesData: {
      handler() {
        this.allIds = [];
        for (const key in this.tablesData) {
          this.getAllId(this.tablesData[key]);
        }
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    periodStatus() {
      return this.userData.periodStatus;
    },
    ...mapGetters(["sidebar"]),
    left() {
      return this.sidebar.opened ? '206px' : '60px'
    }
  },
  mounted() {
    this.$nextTick(function () {
      let header = document.getElementsByClassName("studyStyle")[0];
      this.offsetTop = header.offsetTop;
      this.offsetHeight = header.offsetHeight;
    });
    window.addEventListener('scroll', debounce(this.handleScroll, 50));
  }
};
</script>

<style lang="scss" scoped>
.studyRecordTable {
  .studyStyle {
    margin: 16px 0;
    display: flex;
    align-items: center;

    &>.a_style {
      display: flex;
      align-items: center;
      margin-right: 16px;
      padding: 11px 16px;
      box-shadow: 0px 0px 8px 0px rgba(217, 217, 217, 0.8);
      border-radius: 4px;
      height: 40px;
      width: 440px;
      user-select: none;

      i {
        width: 2px;
        height: 18px;
        display: inline-block;
        background-color: #0047d0;
        margin-right: 8px;
      }

      span {
        color: #666;
        font-weight: bold;
      }

      .flex_style_study {
        flex: 1;
      }

      .num_style {
        float: right;
        font-size: 14px;
        margin-left: 14px;
      }
    }

    .s_sd {
      flex: 1;
      justify-content: flex-end;
      display: flex;
      align-items: center;
      flex-shrink: 0;

      .dis_colu {
        height: 55px;
        margin-right: 14px;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        font-size: 14px;
      }
    }
  }

  .isFixed {
    position: fixed;
    top: 84px;
    right: 0;
    z-index: 10;
    background: #fff;
    padding: 0 20px;
    margin: 0;
  }

}
</style>