<template>
  <d2-container class="page" id="courseRepl">
    <el-tabs value="first">
      <el-tab-pane label="申请课程顶替" name="first">
        提醒：课程顶替、准考证关联、转入关联以及手工录入成绩等工作，现场确认时，由工作人员处理。
        <!--选择毕业专业
        <el-select size="medium" v-model="major_id" filterable clearable placeholder="请选择专业" >
            <el-option v-for="item in majorList" :key="item.major_id" :label="item.full_name" :value="item.major_id"></el-option>
        </el-select>
          <el-button type="primary" @click="goApply()">提交</el-button>
-->
        <el-dialog title="申请课程顶替" width="1000px" :visible.sync="applyDialogVisible">
              <div style="margin-bottom: 8px; color:red;">
            请选择顶替规则(考生请仔细查看本规则)
        </div>
        <br>
        <div>
         <el-table
            :data="ruleList"
            style="width: 100%">
            <el-table-column label="" width="55">
                <template scope="scope">
                    <el-radio :label="scope.row.id" v-model="ruleId" @change.native="getTemplateRow(scope.$index,scope.row)">&nbsp;</el-radio>
                </template>
            </el-table-column>
            <el-table-column
                prop="major_code"
                label="专业编号"
                width="120">
            </el-table-column>
            <el-table-column
                prop="old_course_names"
                label="原计划规定课程及代号"
                width="220">
            </el-table-column>
            <el-table-column
                prop="repl_course_names"
                label="新计划规定课程及代号"
                width="220">
            </el-table-column>
            <el-table-column
                prop="remark"
                label="顶替规则"
                width="280">
            </el-table-column>
          </el-table>
        </div>
        <br>
        <div style="text-align: left">
            <div style="margin-bottom: 8px; color:red;">
                选择专业课程[已考课程，不包括不合格课程]
            </div>
            <el-transfer
                style="text-align: left; display: inline-block"
                v-model="selectedPassList"
                filterable
                :render-content="renderFunc"
                :titles="['源课程', '选择后的']"
               
                :format="{
                    noChecked: '${total}',
                    hasChecked: '${checked}/${total}'
                }"
                @change="handleChange"
                :data="passList">
                <span slot-scope="{ option }">{{ option.label }}</span>
                <!-- <el-button class="transfer-footer" slot="left-footer" size="small">操作</el-button>
                <el-button class="transfer-footer" slot="right-footer" size="small">操作</el-button> -->
            </el-transfer>
            <!-- {{selectedPassList}}
            ---
            {{passList}} -->
        </div>
        <br>
        <div style="text-align: left">
            <div style="margin-bottom: 8px;color:red;">
                选择顶替课程[未考课程，包括不合格课程]
            </div>
            <el-transfer
                style="text-align: left; display: inline-block"
                v-model="selectedFailList"
                filterable
                :titles="['源课程', '选择后的']"
               
                :format="{
                    noChecked: '${total}',
                    hasChecked: '${checked}/${total}'
                }"
                @change="handleChange"
                :data="failList">
                <span slot-scope="{ option }">{{ option.label }}</span>
                <!-- <el-button class="transfer-footer" slot="left-footer" size="small">操作</el-button>
                <el-button class="transfer-footer" slot="right-footer" size="small">操作</el-button> -->
            </el-transfer>
            <!-- {{selectedFailList}} -->

           <el-table
            :data="hasList"
            style="width: 100%">
            <el-table-column
                type="index"
                width="55">
            </el-table-column>
            <el-table-column
                prop="ticket_no"
                label="准考证号"
                width="120">
            </el-table-column>
            <el-table-column
                prop="old_course_names"
                label="旧课程"
                width="360">
            </el-table-column>
            <el-table-column
                prop="new_course_names"
                label="新课程"
                width="360">
            </el-table-column>
       
          </el-table>
          <br>
          <center>
            <el-button type="primary" @click="saveData">提交</el-button>
          </center>
        </div>
        </el-dialog>

      </el-tab-pane>
    </el-tabs>
  </d2-container>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { json } from "body-parser";
import { log } from 'util';

export default {
  computed: {
    ...mapState({
      stdReg: state => state.enrol.StdReg
    })
  },

  data() {
    const generateData = _ => {
      const data = [];
      for (let i = 1; i <= 15; i++) {
        data.push({
          key: i,
          label: `备选项 ${i}`,
          disabled: i % 4 === 0
        });
      }
      return data;
    };
    return {
      map: {},
      renderFunc(h, option) {
        return (
          <span>
            {option.key} - {option.label}
          </span>
        );
      },
      ruleId: null,
      loading: false,
      applyDialogVisible: false,
      major_id: null,
      majorList: null,
      ruleList: [],
      selectedRuleList: [],

      passList: [],
      selectedPassList: [],

      failList: [],
      selectedFailList: [],
      hasList: []
    };
  },

  async mounted() {
    this.loading = true;
    this.init();
    this.loading = false;
  },
  methods: {
    handleChange(value, direction, movedKeys) {
      console.log(value, direction, movedKeys);
    },
    getTemplateRow(index, row) {
      //获取选中数据
      this.templateSelection = row;
    },
    //初始化列表查询
    async init() {
      let res = await this.$http.post(
        "/std/stdMajor/list.htm",
        {},
        this.$http.headers.FORM
      );
      this.majorList = res.data.array;
      if (this.majorList.length > 0) {
        this.major_id = this.majorList[0].major_id;
      }
    },

    async goApply() {
      this.applyDialogVisible = false;
      let res = await this.$http.post(
        "/by/byCourseReplRecord/detail.htm",
        this.Qs.stringify({
          major_id: this.major_id
        }),
        this.$http.headers.FORM
      );
      this.applyDialogVisible = true;
      this.$nextTick(() => {
        this.map = res.data.map;
        this.ruleList = res.data.map.ruleList;
        this.passList = this.transListScore(res.data.map.passList);//score_id
        this.failList = this.transList(res.data.map.failList);
        this.hasList = res.data.map.hasList;
      });
    },

    transList(list) {
      if (!list && list.length == 0) {
        return [];
      }
      let rtnArray = [];
      _.forEach(list, item => {
        rtnArray.push({
          key: item.course_id,
          label: `${item.course_code}-${item.course_name}`
        });
      });
      return rtnArray;
    },
    transListScore(list) {
      if (!list && list.length == 0) {
        return [];
      }
      let rtnArray = [];
      _.forEach(list, item => {
        rtnArray.push({
          key: item.score_id,
          label: `${item.course_code}-${item.course_name}`
        });
      });
      return rtnArray;
    },
    async submit() {
      this.$refs["itemForm"].validate(valid => {
        if (valid) {
          this.saveData();
          return true;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //保存
    async saveData() {
      if(this.major_id == null){
        this.alert("请选择专业信息!");
        return;
      }
      if(this.ruleId == null){
        this.alert("请选择顶替规则!");
        return;
      }
      if(this.selectedPassList.length == 0){
        this.alert("请选择考试通过科目!");
        return;
      }
      if(this.selectedFailList.length == 0){
        this.alert("请选择考试未通过科目!");
        return;
      }
      let { data } = await this.$http.post(
        "by/byCourseReplRecord/add.htm",
        this.Qs.stringify({
          major_id: this.major_id,
          rule_id: this.ruleId,
          score_ids: this.selectedPassList.join(),//this.transScore(this.selectedPassList).join(),
          old_course_ids: this.selectedFailList.join()
        }),
        this.$http.headers.FORM
      );
      if (data.success) {
        this.alert("提交成功");
        this.init();
        this.$nextTick(() => {
          this.applyDialogVisible = false;
        });
      } else {
        this.alert(data.errorMsg);
      }
    },
    transScore(list){
     
      let passList = this.map.passList;
      //todo 测试
      // let passList = this.map.failList;
      let rtnArray = [];
       _.forEach(list, item => {   
          _.forEach(passList, j => {
            // console.log(item+ "@"+j.course_id);
              if(item == j.course_id){
                //todo 测试
                //if(!j.score_id) j.score_id = 69;
                rtnArray.push(j.score_id);
              }
          })
        
      });
      return rtnArray;

    }
  }
};
</script>

<style lang="scss">
@import "~@/assets/style/public.scss";
#courseRepl {
  .el-transfer-panel {
    width: 400px !important;
  }
}
</style>
