<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="width:100%;">
          <el-col :span="5">
            <el-form-item label="项目名称：">
              <el-input v-model="formInline.projectName" size="small" placeholder="请输入项目名称"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="项目时间：">
              <el-date-picker
                v-model="formInline.duringTime"
                size="small"
                type="daterange"
                start-placeholder="请选择开始时间"
                end-placeholder="请选择结束时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>-->
          <el-col :span="12">
            <el-form-item label="项目时间：">
              <el-date-picker
                v-model="formInline.projectBegintime"
                size="small"
                type="datetime"
                placeholder="请选择开始时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions0"
              ></el-date-picker>
                ~
              <el-date-picker
                v-model="formInline.projectEndtime"
                size="small"
                type="datetime"
                placeholder="请选择结束时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions1"
                default-time="23:59:59"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="4">
            <el-form-item label="~">
              <el-date-picker
                v-model="formInline.projectEndtime"
                size="small"
                type="datetime"
                placeholder="请选择结束时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions1"
                default-time="23:59:59"
              ></el-date-picker>
            </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-row>
        <el-col :span="5">
          <el-form ref="formInline" :model="formInline" label-width="75px" style="width:100%;">
            <el-form-item label="发布状态：">
              <el-select size="small" v-model="formInline.projectStatus" 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-form>
        </el-col>
      </el-row>
      <el-form v-if="isRoleOfOuter" :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="projectName" label="项目名称" min-width="100" align="center">
          <template slot-scope="scope">
            <span @click="previewTemplate(scope.row, 1)" style="color:rgb(2, 130, 132);cursor:pointer;" 
              v-if="scope.row.projectType == 3
              && (scope.row.level == 'L1' || scope.row.level == 'L2') ">{{scope.row.projectName}}</span>
            <span v-else>{{scope.row.projectName}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdName" label="创建人" align="center"></el-table-column>
        <el-table-column prop="projectLeader" label="项目负责人" align="center"></el-table-column>
        <el-table-column prop="projectTypeValue" label="项目类型" align="center"></el-table-column>
        <el-table-column prop="createdTime" label="创建时间" width="100" align="center"></el-table-column>
        <!-- <el-table-column
          prop="projectIntro"
          label="项目简介"
          align="center"
          min-width="100"
          show-overflow-tooltip
        ></el-table-column> -->
        <el-table-column prop="projectBegintime" label="项目开始时间" min-width="90" align="center"></el-table-column>
        <el-table-column prop="projectEndtime" label="项目结束时间" min-width="90" align="center"></el-table-column>
        <el-table-column prop="projectStatus" label="状态" align="center">
          <template slot-scope="scope">
            <span>{{ [scope.row.projectStatus , idType] | statusProject }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="360" align="center">
          <template slot-scope="scope">
            <el-button
              @click="changeStatus(scope.row,0)"
              v-show="showButton(scope.row,0)"
              type="primary"
              size="small"
            >编辑</el-button>
            <el-button
              @click="changeStatus(scope.row,1)"
              v-show="showButton(scope.row,1)"
              type="primary"
              size="small"
            >暂存</el-button>
            <el-button
              @click="changeStatus(scope.row,2)"
              v-show="showButton(scope.row,2)"
              type="primary"
              size="small"
            >完成</el-button>
            <el-button
              @click="changeStatus(scope.row,3)"
              v-show="showButton(scope.row,3)"
              type="primary"
              size="small"
            >发布</el-button>
            <el-button
              @click="changeStatus(scope.row,4)"
              v-show="showButton(scope.row,4)"
              type="primary"
              size="small"
            >通过</el-button>
            <el-button
              @click="changeStatus(scope.row,5)"
              v-show="showButton(scope.row,5)"
              type="primary"
              size="small"
            >下架</el-button>
            <el-button
              @click="changeStatus(scope.row,7)"
              v-show="showButton(scope.row,7)"
              type="primary"
              size="small"
              :disabled="scope.row.checkStatus==1"
            >提醒审核</el-button>
            <el-button
              @click="changeStatus(scope.row,8)"
              v-show="showButton(scope.row,8)"
              type="primary"
              size="small"
            >取消审核</el-button>
            <el-button
              @click="changeStatus(scope.row,6)"
              v-show="showButton(scope.row,6)"
              type="primary"
              size="small"
            >拒绝</el-button>
            <el-button
              @click="delItem(scope.row,9)"
              v-show="showButton(scope.row,9)"
              type="primary"
              size="small"
            >删除</el-button>

            <el-button
              @click="hanldeCmeClick(scope.row)"
              v-show="showCMEButton(scope.row)"
              type="primary"
              size="small"
            >{{ handleCmeOperate(scope.row.projectStatus) }}</el-button>
            <el-button
              @click="toShield(scope.row)"
              v-show="scope.row.blackModifiable == true"
              type="primary"
              size="small"
            >屏蔽</el-button>
            <el-button
              @click="addOrModifyNotice(scope.row, 0)"
              v-if="scope.row.level != 'L3'"
              type="primary"
              size="small"
            >公告</el-button>
            <el-button
              @click="reviewReport(scope.row)"
              type="primary"
              size="small"
            >查看学情报告</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="centerDialogVisible"
        width="600px"
        :close-on-click-modal="false"
        @close="handleTypeClose"
        center>
        <span style="margin: 0 20px;">项目类型：</span>
        <el-radio-group v-model="newProjectType">
          <el-radio :label="1">普通项目</el-radio>
          <el-radio :label="2">CME项目</el-radio>
          <el-radio :label="3">开放模板</el-radio>
        </el-radio-group>
        <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleCreateProject">确 定</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>
    </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";
import { setTimeout } from 'timers';
let vm = null;
export default {
  components: {
    BreadCrumb
  },
  data() {
    return {
      idValue: '',
      curmbFirst: "教培项目",
      curmbSecond: "项目管理",
      centerDialogVisible: false,  // 新建项目弹窗
      firstCheckVisible: false,  // 各种操作的确认弹窗
      secondCheckVisible: false,
      newProjectType: 1, // 1 普通项目 2 CME项目 
      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: "已拒绝/未上架"
        },
        {
          value: 7,
          label: "待初审"
        },
        {
          value: 8,
          label: "初审未通过"
        },
        {
          value: 9,
          label: "待复审"
        },
        {
          value: 10,
          label: "复审未通过"
        },
        {
          value: 11,
          label: "复审通过"
        },
        // 加上去 。。。。。。。CME

      ],
      tableData: [],
      totalRows: 0,
      loading: true,
      timingTime: "",
      currentPage: 1,
      formInline: {
        projectName: "",
        projectBegintime: "",
        projectEndtime: "",
        projectStatus: "",
        pageNo: 1,
        pageSize: 10
      },
      pickerOptions0: {
        disabledDate: time => {
          if (this.formInline.projectEndtime != "" && this.formInline.projectEndtime !=null) {
            return (
              time.getTime() >
              new Date(this.formInline.projectEndtime).getTime()
            );
          }
        }
      },
      pickerOptions1: {
        disabledDate: time => {
          return (
            time.getTime() <
            new Date(this.formInline.projectBegintime).getTime()
          ); //减去一天的时间代表可以选择同一天;
        }
      },
      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'
    ]),

    //跳转到报告详情页
    reviewReport(row) {
      let routerData = {
        id: row.id,
        projectName: row.projectName,
      };
      vm.$router.push({ path: "/item-list" , query: routerData });
    },

    hideDeleteFrom() {
      this.deleteVisible = false;
    },
    
    // 打开新建页面
    openProject() {
      if(vm.idType == 2) {
        vm.toTemplatePage();
      } else {
        this.centerDialogVisible = true;
      }
    },
    toPage(isPreview = 0) {
      this.$router.push("edit-manager?projectType=1&isPreview=" + isPreview);
    },
    toCmePage(isPreview = 0) {
      this.$router.push("edit-cme?projectType=2&isPreview=" + isPreview);
    },    
    toTemplatePage(isPreview = 0) {
      this.$router.push("template-open?projectType=3&isPreview=" + isPreview);
    },
    toShield(row) {
      this.$router.push("item-shield?projectId="+row.id);
    },
    handleTypeClose() {
      this.centerDialogVisible = false;
      this.newProjectType = 1;
    },
    handleCreateProject() {
      if (this.newProjectType == 1) {  // 1 普通项目 2 CME项目
        this.toPage();
      } else if (this.newProjectType == 2) {
        this.toCmePage();
      } else if(this.newProjectType == 3) {
        this.toTemplatePage();
      }
    },

    previewTemplate(row, isPreview) {
      this.$router.push(`template-open?projectId=${row.id}&projectType=3&isPreview=${isPreview}`);
    },

    // handleCreateProject(isPreview) {
    //   if (this.newProjectType == 1) {  // 1 普通项目 2 CME项目
    //     this.toPage(isPreview);
    //   } else if (this.newProjectType == 2) {
    //     this.toCmePage(isPreview);
    //   } else if(this.newProjectType == 3) {
    //     this.toTemplatePage(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;
      this.formInline.projectBegintime = !this.formInline.projectBegintime ? "" : this.formInline.projectBegintime;
      this.formInline.projectEndtime = !this.formInline.projectEndtime ? "" : this.formInline.projectEndtime;
      openLoading(vm);
      vm.GET("portal/portalInfo/getProjectList", req).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          vm.tableData = res.data.data;
          //console.log(vm.tableData);
          vm.totalRows = res.data.totalRows;
        }
      });
    },
    showCMEButton(row, type) {
      // if(row.projectType == 2) {
      //   return true;
      // } else {
      //   return false;
      // }
      // CME 专属状态码 为7~11，是这些代码的直接走新逻辑，别的走老逻辑
      let cmeStatus = [7, 8, 9, 10, 11];
      let currentStatus = parseInt(row.projectStatus);
      if ( cmeStatus.indexOf(currentStatus) > -1 ) {
        return true; 
      } else {
        return false;
      }
    },
    //按钮展示情况
    showButton(row, type) {
      if(!row.isRoleOfOuter) return false;
      // 按钮type类型： 0-编辑
      // 1-暂存 2-完成 3-上架 4-通过 5-下架 6-拒绝
      // 7- 提醒审核 8(2)-取消审核 9-删除
      let projectStatus = row.projectStatus;
      let idType = row.idType;
      let level = row.level;
      let flag = false;
      let typeStr = parseInt(type);
      let buttonStatus = "";
      if (idType == 1) {
        //内部项目
        buttonStatus = returnData().buttonStatusIn;
      } else {
        //外部项目
        buttonStatus = returnData().buttonStatusOut;
      }
      if(projectStatus == null) {
        return false;
      }
      if (level != null) {
        let tempStatus = JSON.parse(JSON.stringify(projectStatus));
        if (tempStatus > 6) {
          tempStatus = 1;
        }
        let statusSet = buttonStatus[tempStatus - 1][level];
        let flagValue = statusSet.indexOf(typeStr);
        if (flagValue >= 0) {
          flag = true;
        } else {
          flag = false;
        }
      }
      // 添加新的判断逻辑
      if(flag && type == 0) {
        return (row.level == 'L1' && row.idType == 1) || (row.level == 'L2' && row.idType == 2)
      }
      return flag;
    },
    handleCmeOperate(status) {
      let text = '';
      // 7.待初审 8.初审未通过 9.待复审 10.复审未通过 11.复审通过
      if (status == 7 || status == 8) {  // 按钮显示 初审
        text = '初审';
      } else if (status == 9 || status == 10) {  // 按钮显示 复审
        text = '复审'; 
      } else if (status == 11) {  // 按钮显示 发布
        text = '发布';
      }
      this.cmeBtnText = text;
      return text;
      // return true / false; 
    },
    //改变状态
    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 (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 {
        // if (type === 8) {
        //   //取消审批值对应2
        //   type = 2;
        //   let req = {
        //     portalProjectId: projectId,
        //     warnType: 5
        //   };
        //   vm.GET("portal/portalCheck/remindPortalCheck", req).then(res => {
        //     vm.$message.info(res.message);
        //     if (res.code == "000000") {
        //       console.log(res);
        //       vm.getProjectList();
        //     }
        //   });
        // }
        // if (type == 4 || type == 6) {
        //   //发送消息
        //   let warnType = "";
        //   if (type == 4) {
        //     warnType = 3;
        //   } else if (type == 6) {
        //     warnType = 4;
        //   }
        //   let req = {
        //     portalProjectId: projectId,
        //     warnType: warnType
        //   };
        //   vm.GET("portal/portalCheck/remindPortalCheck", req).then(res => {
        //     vm.$message.info(res.message);
        //     if (res.code == "000000") {
        //       console.log(res);
        //       vm.getProjectList();
        //     }
        //   });
        // }
        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(
        {},
        {
          projectName: "",
          projectBegintime: "",
          projectEndtime: "",
          projectStatus: "",
          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]);
        }
      }
    },
    addOrModifyNotice(row) {
      this.$router.push("edit-notice?projectId=" + row.id);
    }
  }
};
</script>
<style lang="scss">
.item-table .el-button {
  margin: 5px 0;
}
.item-manager-wrap {
  .component-content {
    background: #fff;
    //margin-top: 88px;
    padding: 10px;
    .header-title {
      padding: 10px 12px;
      font-size: 12px;
      color: #449284;
      border-bottom: 1px solid #efefef;
    }
    // .table-option span {
    //   color: #409eff;
    // }
    .add-button {
      float: right;
    }
    .table-empty {
      img {
        width: 100px;
      }
      p {
        margin-top: -50px;
      }
    }
  }
}
.el-tooltip__popper {
  max-width:50%
}
</style>
