<template>
  <div class="item-manager-wrap">
    <bread-crumb :curmbFirst="curmbFirst" :curmbSecond="curmbSecond"></bread-crumb>
    <div class="component-content screenSet" id="screenSet">
      <div class="header-title">学科管理</div>
      <el-row :gutter="30" class="row" type="flex" style="margin-top: 10px;">
        <el-form ref="formInline" :model="formInline" label-width="75px" style="min-width:1200px;">
          <el-col style="width: 300px">
            <el-form-item label="学科名称：">
              <el-input style="width: 192px;" v-model="formInline.subjectName" size="small" placeholder="请输入学科名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col style="width: 600px">
            <el-form-item label="发布状态：">
              <el-select size="small" v-model="formInline.status" placeholder="请选择发布状态">
                <el-option
                  v-for="item in optionStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" style="padding:0;text-align:right;padding-right:15px;">
            <el-button type="primary" size="small" @click="searchList">查询</el-button>
            <el-button type="default" size="small" @click="resetForm" style="margin-left:0;">重置</el-button>
          </el-col>
        </el-form>
      </el-row>

      <el-form :model="formInline" class="demo-form-inline">
        <el-form-item >
          <el-button class="add-button" size="small" type="primary" @click="openProject()">新建项目</el-button>
        </el-form-item>
      </el-form>

      <el-table class="item-table" :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="ID编号" min-width="100" align="center"></el-table-column>
        <el-table-column prop="firstSubjectName" label="学科名称" align="center"></el-table-column>
        <!-- <el-table-column prop="title" label="所属职称" align="center"></el-table-column> -->
        <el-table-column prop="createdName" label="创建人" align="center"></el-table-column>
        <el-table-column prop="statusText" label="状态" align="center"></el-table-column>
        <el-table-column fixed="right" label="操作" min-width="250" align="center">
          <template slot-scope="scope">
            <el-button
              v-for="btn in scope.row.btns"
              :key="btn.type"
              @click="onBtnClick(scope.row, btn)"
              type="primary"
              size="small"
            >{{ btn.name }}</el-button>
          </template>
        </el-table-column>
        <div slot="empty">
          <div class="table-empty">
            <img src="../../assets/image/no-content1.png" />
            <p>没有查询到相关结果</p>
          </div>
        </div>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="formInline.pageNo"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="formInline.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRows"
        ></el-pagination>
      </div>

      <!-- 初审 弹窗 -->
      <el-dialog
        title="项目初审"
        :visible.sync="firstCheckVisible"
        width="600px"
        :close-on-click-modal="false"
        center
      >
        <span style="margin: 0 20px;">{{ `项目《${currentRow.projectName}》初审结果为？` }}</span>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleCheckLeft">通 过</el-button>
          <el-button @click="handleCheckRight">不通过</el-button>
        </span>
      </el-dialog>

      <!-- 复审 弹窗 -->
      <el-dialog
        title="项目复审"
        :visible.sync="secondCheckVisible"
        width="600px"
        :close-on-click-modal="false"
        center
      >
        <span style="margin: 0 20px;">{{ `项目《${currentRow.projectName}》复审结果为？` }}</span>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleCheckLeft">通 过</el-button>
          <el-button @click="handleCheckRight">不通过</el-button>
        </span>
      </el-dialog>
      <!-- 删除 弹窗 -->
      <el-dialog
        title="确认删除"
        :show-close="false"
        :visible.sync="deleteVisible"
        :close-on-click-modal="false"
        width="600px"
        center
      >
        <p style="text-align: center;">删除后将不可撤销，确认删除吗？</p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="confirmDelete">删 除</el-button>
          <el-button type="primary" @click="hideDeleteFrom">取 消</el-button>
        </span>
      </el-dialog>

      <!-- 修改状态 -->
      <el-dialog
        :title="changeStatusConfig.title"
        :show-close="false"
        :visible.sync="changeStatusVisible"
        :close-on-click-modal="false"
        width="600px"
        center
      >
        <p style="text-align: center;">{{changeStatusConfig.message}}</p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="changeStatusVisible=false">取 消</el-button>
          <el-button type="primary" @click="changeStatusPre">确 认</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import BreadCrumb from "../../components/breadcrumb.vue";
import { create } from "domain";
import { mapGetters, mapActions } from "vuex";
import { returnData } from "../../utils/mock";
import { openLoading, closeLoading } from "../../utils/utils";
import * as commonUtil from "../../utils/utils";

let vm = null;
export default {
  components: {
    BreadCrumb
  },
  data() {
    return {
      changeStatusVisible: false,
      currentRow: null,
      currentType: 4,
      changeStatusConfig: {
        title: "确认通过该项目模版审核吗？",
        message: "下架后，用户新建项目则无法看到该模版"
      },
      idValue: "",
      curmbFirst: "教培项目",
      curmbSecond: "学科管理",
      firstCheckVisible: false, // 各种操作的确认弹窗
      secondCheckVisible: false,
      searchParam: {
        name: "",
        status: "",
        pageNo: 1,
        pageSize: 10
      },
      cmeBtnText: "",
      currentRow: {},
      optionStatus: [
        { value: "", label: "全部" },
        { value: 1, label: "草稿" },
        { value: 2, label: "未上架" },
        { value: 3, label: "审核中/待审核" },
        { value: 4, label: "已上架" },
        { value: 5, label: "已下架" },
        { value: 6, label: "已拒绝/未上架" }
      ],
      tableData: [],
      totalRows: 0,
      loading: true,
      timingTime: "",
      currentPage: 1,
      formInline: {
        subjectName: "",
        status: "",
        pageNo: 1,
        pageSize: 10
      },
      idType: "",
      deleteVisible: false,
      isRoleOfOuter: 0
    };
  },
  computed: {
    ...mapGetters([
      "_token"
      // "idType",
    ])
  },
  created() {
    vm = this;
    vm.idType = localStorage.getItem("storageIdType"); //
    vm.isRoleOfOuter = localStorage.getItem("isRoleOfOuter") - 0; // 内部管理员权限

    let pageSize = vm.formInline.pageSize;
    console.log("idType:", vm.idType);
    if (this.$route.query.pageNum) {
      this.formInline = { ...this.$store.state.common.itemManager };
      this.formInline.pageNo = parseInt(this.$route.query.pageNum);
      this.formInline.pageSize = pageSize;
    }
    this.$nextTick(function() {
      this.getProjectList();
    });
  },
  // 挂载到Dom完成时
  mounted: function() {
    commonUtil.resizeHeight();
  },
  methods: {
    ...mapActions(["updateItemManager", "setKind"]),

    hideDeleteFrom() {
      this.deleteVisible = false;
    },

    // 打开新建页面
    openProject() {
      this.$router.push("edit-subject");
    },
    toEditCustomPage(isPreview = 0) {
      this.setKind(0);
      this.$router.push("edit-custom?projectType=4&isPreview=" + isPreview);
    },

    hanldeCmeClick(row) {
      this.currentRow = row;
      let status = row.projectStatus;
      // 7.待初审 8.初审未通过 9.待复审 10.复审未通过 11.复审通过
      if (status == 7 || status == 8) {
        // 按钮显示 初审
        this.firstCheckVisible = true;
      } else if (status == 9 || status == 10) {
        // 按钮显示 复审
        this.secondCheckVisible = true;
      } else if (status == 11) {
        // 按钮显示 发布
        this.changeStatus(row, 3);
      }
    },
    handleCheckLeft() {
      // 左边通过
      this.goToCheckAuth(1);
    },
    handleCheckRight() {
      this.goToCheckAuth(2);
    },
    goToCheckAuth(refuse) {
      let row = this.currentRow;
      let req = {};
      openLoading(vm);
      // refuse = 1 : 同意   refuse = 2：拒绝
      vm.GET(
        `portal/cme/verifyProject?projectId=${row.id}&refuse=${refuse}`,
        req
      ).then(res => {
        closeLoading(vm);
        // debugger;
        vm.firstCheckVisible = false;
        vm.secondCheckVisible = false;
        if (res.code == "000000") {
          vm.getProjectList();
          this.$message({
            message: "审核成功",
            type: "success"
          });
        } else {
          this.$message.error(res.message);
        }
      });
    },
    searchList() {
      this.formInline.pageNo = 1;
      this.getProjectList();
    },
    //查询项目列表
    getProjectList() {
      let req = {};
      req = this.formInline;
      openLoading(vm);
      vm.GET("portal/titleTest/list", req).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          const { list = [], total } = res.data;
          vm.tableData = list.map(item => {
            let statusText = '';
            let btns = [];
            // 设置按钮名称、类型、操作之后的status
            let [edit, publish, accept, reject, outOf, del] = [
              { name: '编辑', type: 'edit' },
              { name: '发布', type: 'publish', next: 3 },
              { name: '通过', type: 'accept', next: 4 },
              { name: '拒绝', type: 'reject', next: 6 },
              { name: '下架', type: 'outOf', next: 5 },
              { name: '删除', type: 'del', next: 7 },
            ];
            switch (item.status) {
              case 1:
                statusText = '草稿';
                btns = [edit, publish, del];
                break;
              case 2:
                statusText = '未上架';
                btns = [edit, publish, del];
                break;
              case 3:
                statusText = '审核中/待审核';
                btns = [accept, reject];
                break;
              case 4:
                statusText = '已上架';
                btns = [edit, outOf];
                break;
              case 5:
                statusText = '已下架';
                btns = [edit, del];
                break;
              case 6:
                statusText = '已拒绝/未上架';
                btns = [edit, publish, del];
                break;
              default:
                //
            }
            return {
              ...item,
              statusText,
              btns,
            }
          });
          //console.log(vm.tableData);
          vm.totalRows = total;
        }
      });
    },
    changeStatusPre() {
      this.changeStatus(this.currentRow, this.currentType);
      this.changeStatusVisible = false;
    },
    changeStatusForSP(row, type) {
      this.currentRow = row;
      this.currentType = type;
      if (type == 4) {
        this.changeStatusConfig.title = "确认通过该项目审核吗？";
        this.changeStatusConfig.message =
          "审核通过后，该项目范围内的学员可在云鹊医App进行培训学习";
      } else if (type == 6) {
        this.changeStatusConfig.title = "确认要拒绝该项目吗？";
        this.changeStatusConfig.message = "";
      }
      this.changeStatusVisible = true;
    },
    onBtnClick(item, btn) {
      if (btn.type === 'edit') {
        this.$router.push(
          "edit-subject?projectId=" +
          item.id +
          "&level=" +
          item.level +
          "&pageNum=" +
          this.formInline.pageNo
        );
      } else {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.changeStatus(item.id, btn.next);
        }).catch(() => {
        });
      }
    },
    // 修改状态
    changeStatus(id, status) {
      this.POST("portal/titleTest/changeSubjectStatus", { id, status }).then(res => {
        this.$message.info(res.message);
        if (res.code == "000000") {
          console.log(res);
          this.getProjectList();
        }
      });
    },

    //改变状态
    changeStatus(row, type) {
      let projectId = row.id;
      let level = row.level;
      if (type === 0) {
        this.updateItemManager(this.formInline);
        //编辑
        if (row.projectType === 1) {
          this.$router.push(
            "edit-manager?projectType=1&projectId=" +
              projectId +
              "&level=" +
              level +
              "&pageNum=" +
              this.formInline.pageNo
          );
        } else if (row.projectType === 2) {
          this.$router.push(
            "edit-cme?projectType=2&projectId=" +
              projectId +
              "&level=" +
              level +
              "&pageNum=" +
              this.formInline.pageNo
          );
        } else if (row.projectType === 3) {
          this.$router.push(
            "template-open?projectType=3&projectId=" +
              projectId +
              "&level=" +
              level +
              "&pageNum=" +
              this.formInline.pageNo
          );
        } else if (row.projectType === 4) {
          this.$router.push(
            "edit-custom?projectType=4&projectId=" +
              projectId + "&level=" + level + "&pageNum=" + this.formInline.pageNo +
              "&projectStatus=" + row.projectStatus
          );
        }
      } else if (type === 7) {
        //提醒审核
        let req = {
          portalProjectId: projectId,
          warnType: 1
        };
        vm.GET("portal/portalCheck/remindPortalCheck", req).then(res => {
          vm.$message.info(res.message);
          vm.getProjectList();
          // if (res.code == "000000") {
          //   console.log(res);
          //   vm.getProjectList();
          // } else {
          //   vm.$message.info(res.message);
          // }
        });
      } else {
        let req = {
          projectId: projectId,
          changeStatus: vm.getType(type)
        };
        vm.POST("portal/portalInfo/changeStatus", req).then(res => {
          vm.$message.info(res.message);
          if (res.code == "000000") {
            console.log(res);
            vm.getProjectList();

            //changeStatus之后remindPortalCheck
            if (type == 4 || type == 6 || type == 8) {
              //发送消息
              let warnType = "";
              if (type == 4) {
                warnType = 3;
              } else if (type == 6) {
                warnType = 4;
              } else if (type == 8) {
                warnType = 5;
              }
              let req = {
                portalProjectId: projectId,
                warnType: warnType
              };
              vm.GET("portal/portalCheck/remindPortalCheck", req).then(res => {
                vm.$message.info(res.message);
                if (res.code == "000000") {
                  vm.getProjectList();
                }
              });
            }
          }
        });
      }
    },
    getType(value) {
      let data = value;
      if (data == 8) {
        data = 2;
      }
      return data;
    },
    delItem(row) {
      this.deleteVisible = true;
      this.currentRow = row;
    },
    hideDeleteFrom() {
      this.deleteVisible = false;
    },
    // 删除项目
    confirmDelete() {
      let req = {};
      vm.DELETE("portal/portalInfo/delete/" + this.currentRow.id, req).then(
        res => {
          vm.$message.info(res.message);
          if (res.code == "000000") {
            this.deleteVisible = false;
            vm.getProjectList();
          }
        }
      );
    },
    // 重置表单
    resetForm() {
      vm.formInline = Object.assign(
        {},
        {
          subjectName: "",
          status: "",
          pageNo: 1,
          pageSize: 10,
          duringTime: ""
        }
      );
      vm.getProjectList();
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.formInline.pageSize = val;
      this.handleCurrentChange(this.searchParam.pageNo);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.formInline.pageNo = val;
      this.getProjectList();
      //需要判断是否检索
      // if (!this.flag) {
      //   this.currentChangePage(this.tableDataEnd);
      // } else {
      //   this.currentChangePage(this.filterTableDataEnd);
      // }
    }, //组件自带监控当前页码
    currentChangePage(list) {
      let from = (this.currentPage - 1) * this.pageSize;
      let to = this.currentPage * this.pageSize;
      this.tableDataEnd = [];
      for (; from < to; from++) {
        if (list[from]) {
          this.tableDataEnd.push(list[from]);
        }
      }
    },
  }
};
</script>
<style lang="scss">
.item-table .el-button {
  margin: 5px 0;
}
.item-manager-wrap {
  .component-content {
    background: #fff;
    padding: 10px;
    .header-title {
      padding: 10px 12px;
      font-size: 12px;
      color: #449284;
      border-bottom: 1px solid #efefef;
    }
    .demo-form-inline {
      margin-right: 20px;
      .add-button {
        float: right;
        margin-right: 10px;
      }
    }
    .table-empty {
      img {
        width: 100px;
      }
      p {
        margin-top: -50px;
      }
    }
  }
}
.el-tooltip__popper {
  max-width: 50%;
}
</style>
