<template>
  <div class="credit-manage-wrap">
    <bread-crumb :curmbFirst="curmbFirst" :curmbSecond="curmbSecond"></bread-crumb>

    <div class="credit-list screenSet" id="screenSet">
      <el-form ref="form" :model="searchForm" label-width="80px">
        <div style="width: 75%; float:left;">
          <el-form-item label="学分名称：" class="search-item">
            <el-input v-model="searchForm.name" placeholder="请输入学分名称" size="small" class="form-width"></el-input>
          </el-form-item>
          <el-form-item label="学分等级：" class="search-item">
            <el-select v-model="searchForm.grade" placeholder="请选择" size="small" class="form-width">
              <el-option v-for="(item, index) in creditGrade" :key="index" :label="item.text" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态：" class="search-item">
            <el-select v-model="searchForm.status" placeholder="请选择" size="small" class="form-width">
              <el-option v-for="(item, index) in creditStatus" :key="index" :label="item.text" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div style="width: 25%; float: right;">
          <el-form-item class="btn-list">
            <el-button @click="goToSearch" size="small">搜索</el-button>
            <el-button @click="goToReset" size="small">重置</el-button>
            <el-button @click="showNewAddForm" type="primary" size="small">新增学分</el-button>
          </el-form-item>
        </div>
      </el-form>

      <el-table :data="tableData" border style="width: 100%">
        <el-table-column align="center" prop="id" label="编号" width="80"></el-table-column>
        <el-table-column align="center" prop="name" label="学分名称" ></el-table-column>
        <el-table-column align="center" prop="org" label="主管机构" ></el-table-column>
        <el-table-column align="center" prop="studyTypeText" label="学习形式" ></el-table-column>
        <el-table-column align="center" prop="gradeText" label="学分等级"></el-table-column>
        <el-table-column align="center" prop="value" label="项目学分分值" ></el-table-column>
        <el-table-column align="center" prop="modifiedName" label="最后修改者" ></el-table-column>
        <el-table-column align="center" prop="modifiedTime" label="最后修改日期" ></el-table-column>
        <el-table-column align="center" prop="statusText" label="状态" ></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button @click="operationClick(scope.row)" type="text" size="small">
              {{ returnHandleText(scope.row) }}
            </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
          class="pagination-style"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :total="totalRows"
          :current-page="searchForm.pageNo"
          :page-sizes="[15, 30, 50, 100]"
          :page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </div>
    </div>

    <!-- 新增学分 弹窗 -->
    <el-dialog
      title="学分新增"
      @close="hideNewAddForm"
      :visible.sync="centerDialogVisible"
      :close-on-click-modal="false"
      width="600px"
      center>
      <el-form ref="addForm" :rules="rules" :model="addForm" label-width="120px">
        <el-form-item label="学分名称：" class="search-item" prop="name">
          <el-input v-model="addForm.name" size="small" class="wide-form"></el-input>
        </el-form-item>
        <el-form-item label="主管机构：" class="search-item" prop="org">
          <el-input v-model="addForm.org" size="small" class="wide-form"></el-input>
        </el-form-item>
        <el-form-item label="学习形式：" class="search-item" prop="studyType">
          <el-radio-group v-model="addForm.studyType">
            <el-radio :label="item.id" v-for="(item, index) in studyType" :key="index">{{ item.text }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="学分等级：" class="search-item" prop="grade">
          <el-select v-model="addForm.grade" placeholder="请选择" size="small" class="form-width">
            <el-option v-for="(item, index) in creditGrade" :key="index" :label="item.text" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目学分分值：" class="search-item" prop="value">
          <el-input v-model="addForm.value" size="small" class="form-width" type="number" min="0"></el-input>
        </el-form-item>
        <el-form-item label="关联学分证书：" class="search-item" prop="certificateId">
          <el-select v-model="addForm.certificateId" placeholder="请选择" size="small" class="form-width">
            <el-option v-for="(item, index) in relateList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="hideNewAddForm">取 消</el-button>
        <el-button type="primary" @click="submitForm('addForm')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增的确认弹窗 -->
    <el-dialog
      :visible.sync="submitConfirmVisible"
      :close-on-click-modal="false"
      :show-close="false"
      width="350px"
      center>
      <p style="text-align: center;">提交后不可修改，请确认</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="submitConfirmVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitConfirmClick">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import { openLoading, closeLoading } from "../../utils/utils";
  import BreadCrumb from "../../components/breadcrumb.vue";
  import * as commonUtil from "../../utils/utils";
  import { 
    getSelectListReq, 
    getCreditListReq, 
    getRelatedCreditReq, 
    goUpReq, 
    goDownReq, 
    goAddNewReq 
  } from '@/utils/cme/cmeApi'


  export default {
    data() {
      var validateCreditValue = (rule, value, callback) => {
        if (value <= 0) {
          return callback(new Error('项目学分分值需大于0'));
        } else {
          console.log(value)
          let isBadValue = /[-+]/.test(value);
          if (isBadValue) {
            return callback(new Error('项目学分分值需大于0'));
          }
          let arr = value.split('.');
          if (arr.length > 1) {
            let temp = arr[1];
            if (temp.length > 1) {
              return callback(new Error('项目学分分值 最多1位小数'));
            }
          }
        }
        callback();
      };
      return {
        curmbFirst: "CME",
        curmbSecond: "学分管理列表",
        totalRows: 0,

        searchForm: {
          name: '',
          grade: '',
          status: '',
          pageNo: 1,
          pageSize: 15,
        },
        creditGrade: [],    // 学分等级
        creditStatus: [],   // 状态
        studyType: [],      // 学习形式
        relateList: [],     // 关联学分证书列表

        centerDialogVisible: false,
        submitConfirmVisible: false,

        tableData: [],
        handleStatusText: {  // 1 已创建状态>显示上架； 2 上架状态>显示下架; 3 下架状态>显示上架
          1: '上架',
          2: '下架',
          3: '上架', 
        },

        addForm: {
          name: '',
          org: '',
          studyType: 1,
          grade: '',
          value: '',
          certificateId: '',
        },
        rules: {
          name: [{ required: true, message: '请输入', trigger: 'blur' }],
          org: [{ required: true, message: '请输入', trigger: 'blur' }],
          studyType: [{ required: true, message: '请选择', trigger: 'blur' }],
          grade: [{ required: true, message: '请选择', trigger: 'blur' }],
          value: [
            { required: true, message: '请输入项目学分分值', trigger: 'blur' },
            { validator: validateCreditValue, trigger: 'blur' }
          ],
          certificateId: [{ required: true, message: '请选择', trigger: 'blur' }],
        }
      }
    },

    components: {
      BreadCrumb
    },

    created() {
      this.getSelectList('credit_grade');  // get 学分等级
      this.getSelectList('credit_status'); // get 状态
      this.getSelectList('study_type'); // get 学习形式
      this.goToSearch();
    },
    mounted() {
      commonUtil.resizeHeight();
    },
    methods: {
      // 获取 学分等级/状态/学习形式 常亮接口
      getSelectList(type) {
        // openLoading(this);
        getSelectListReq(type).then(res => {
          // closeLoading(this);
          if (res.code == "000000") {
            if (type == 'credit_grade') {
              this.creditGrade = res.data;
            } else if (type == 'credit_status') {
              this.creditStatus = res.data;
            } else if (type == 'study_type') {
              this.studyType = res.data;
              // console.log('学习形式： ', this.studyType)
            }
          } else {
            this.$message(res.message);
          }
        }).catch(err => {
          this.$message.error('请求失败');
        });
      },

      goToSearch() {
        this.searchForm.pageNo = 1;
        // this.searchForm.pageSize = 15;
        this.getCreditList();
      },
      goToReset() {
        this.searchForm = {
          name: '',
          grade: '',
          status: '',
          pageNo: 1,
          pageSize: 15,
        };
      },

      // 获取 学分table列表
      getCreditList() {
        let req = this.searchForm;
        openLoading(this);
        getCreditListReq(req).then(res => {
          closeLoading(this);
          if (res.code == "000000") {
            // console.log('@@@@@@@', res.data.contentList)
            if (res.data && res.data.contentList) {
              this.tableData = res.data.contentList;
              this.totalRows = res.data.total;
            } else {
              this.tableData = [];
            }
          } else {
            this.$message(res.message);
          }
        }).catch(err => {
          this.$message.error('请求失败');
        });
      },

      // 操作内的文案
      returnHandleText(row) {
        let status = row.status;
        // console.log('>>>>**** status ', status)
        return this.handleStatusText[status] || '';
      },

      // 获取 关联学分证书
      getRelatedCredit() {
        let req = {};
        getRelatedCreditReq(req).then(res => {
          if (res.code == "000000") {
            // console.log('获取关联学分证书接口 ', res)
            if (res.data && res.data.list) {
              this.relateList = res.data.list;
            } else {
              this.relateList = [];
            }
          } else {
            this.$message(res.message);
          }
        }).catch(err => {
          this.$message.error('请求失败');
        });
      },

      operationClick(row) {
        // console.log('操作： ', row)
        let status = row.status;
        // 1 已创建状态>显示上架； 2 上架状态>显示下架; 3 下架状态>显示上架
        if (status == 1 || status == 3){  // 去上架
          this.goUp(row.id);
        } else if (status == 2) {  // 去下架
          this.goDown(row.id);
        }
      },

      goUp(id) {
        openLoading(this);
        let req = {};
        goUpReq(req, id).then(res => {
          closeLoading(this);
          // console.log('上架英文', res)
          if (res.code == "000000") {
            this.getCreditList();
          } else {
            this.$message(res.message);
          }
        }).catch(err => {
          this.$message.error('请求失败');
        });
      },

      goDown(id) {
        openLoading(this);
        let req = {};
        goDownReq(req, id).then(res => {
          closeLoading(this);
          // console.log('下架英文', res)
          if (res.code == "000000") {
            this.getCreditList();
          } else {
            this.$message(res.message);
          }
        }).catch(err => {
          this.$message.error('请求失败');
        });
      },

      showNewAddForm() {
        this.centerDialogVisible = true;
        this.getRelatedCredit();
      },

      hideNewAddForm() {
        this.centerDialogVisible = false;
        this.resetForm('addForm');
      },

      resetForm(formName) {
        this.$refs[formName].resetFields();
      },

      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // alert('submit!');
            this.showSubmitConfirm();
            
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      showSubmitConfirm() {
        this.submitConfirmVisible = true;
      },
      submitConfirmClick() {
        this.goAddNew();
      },
      goAddNew() {
        let req = this.addForm;
        goAddNewReq(req).then(res => {
          closeLoading(this);
          // console.log('新增积分记录', res)
          if (res.code == "000000") {
            this.submitConfirmVisible = false;
            this.hideNewAddForm();
            this.getCreditList();
          } else {
            this.$message(res.message);
          }
        }).catch(err => {
          this.$message.error('请求失败');
        });
      },
      
      handleSizeChange(val){
        // console.log('handleSizeChange>>>')
        this.searchForm.pageSize = val;
        this.goToSearch();
      },
      
      handleCurrentChange(val){
        // 切换当前页
        this.searchForm.pageNo = val;
        this.getCreditList();
      },

    },

  }
</script>  

<style lang="scss">
  .credit-manage-wrap{
    .form-width{
      width: 200px;
    }
    .wide-form{
      width: 300px;
    }
    .credit-list{
      padding: 10px;
      background: #fff;
      .el-button--small{
        font-size: 14px;
      }
      .search-item{
        float: left;
      }
      
      .btn-list{
        float: right;
        margin-right: 30px;
        .el-form-item__content{
          margin-left: 0 !important;
        }
      }
      .table-empty {
        img {
          width: 100px;
        }
        p {
          margin-top: -50px;
        }
      }
    }
  }
</style>