<template>
  <div class="parentContent">
    <div class="left whiteBlock">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        size="medium"
      >
      <!-- 课程名称 -->
        <el-form-item :label="$t('message.safetyEducation.courseName')" prop="eduCourseName">
          <el-input v-model="ruleForm.eduCourseName" :placeholder="$t('message.safetyEducation.pleaseEnter')" :disabled="eduId!=''"></el-input>
        </el-form-item>
        <!-- 课程类型 -->
        <el-form-item :label="$t('message.safetyEducation.courseType')" prop="eduType">
          <el-select :disabled="eduId!=''"
            style="width: 100%"
            v-model="ruleForm.eduType"
            :placeholder="$t('message.safetyEducation.pleaseEnter')"
          >
            <el-option
              v-for="(item, index) in educateTypeList"
              :key="index"
              :label="item"
              :value="index + 1"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 课程分类 -->
        <el-form-item :label="$t('message.safetyEducation.courseClass')" prop="classifyId">
          <el-select :disabled="eduId!=''"
            style="width: 100%"
            v-model="ruleForm.classifyId"
            :placeholder="$t('message.safetyEducation.pleaseEnter')"
          >
            <el-option
              v-for="item in classifyList"
              :key="item.id+'classify'"
              :label="item.classifyName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 课程视频 -->
        <el-form-item :label="$t('message.safetyEducation.courseVideo')" prop="eduVideo">
          <!-- <el-input v-model="ruleForm.eduVideo"></el-input> -->
          <el-upload :disabled="eduId!=''"
            class="upload-demo" name="files"
            :action="$store.state.UPLOADURL"
            :on-success="handleSuccess"
            :show-file-list="false" accept="video/mp4">
            <el-button size="small" type="primary"  v-show="eduId==''">
              <!-- 点击上传 -->
              {{ $t('message.safetyEducation.clickUpload') }}
            </el-button>
            <video :src="$store.state.FILEURL+ruleForm.eduVideo" width="100%" height="200" controls></video>
        </el-upload>
        </el-form-item>
        <!-- 试卷总分 -->
        <el-form-item :label="$t('message.safetyEducation.totalScore')" prop="totalScore">
          <el-input v-model="ruleForm.totalScore" disabled></el-input>
        </el-form-item>
        <!-- 及格分数 -->
        <el-form-item :label="$t('message.safetyEducation.passingScore')" prop="passScore" >
          <!-- <el-input v-model="ruleForm.passScore" :disabled="eduId!=''"></el-input> -->
          <el-input-number v-model="ruleForm.passScore" :min="1" :precision="0" :label="$t('message.workType.placeholder')" :disabled="eduId!=''" style="width:100%;" :controls="false"></el-input-number>
        </el-form-item> 
        <el-form-item label="" v-show="eduId==''">
          <el-button type="primary" @click="submitForm('ruleForm')"
            >
            <!-- 保存 -->
            {{ $t('message.safetyEducation.preservation') }}
            </el-button
          >
          <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
        </el-form-item>
      </el-form>
      <!-- iewBigPicture 查看大图 -->
      <div :title="$t('message.safetyEducation.iewBigPicture')" @click="showBig" id="workerQRcode" ref="workerQRcode" class="workerQRcode" v-show="eduId!=''&&$route.path.indexOf('/project/')!=-1"></div>
    </div>
    <div class="right whiteBlock" :class="{'dark_right': styleType == 2}">
      <vue-scroll>
        <el-button v-if="eduId==''" type="primary" size="medium" @click="addQuesFn"
          >
          <!-- 新增试题 -->
          {{ $t('message.safetyEducation.newTestQuestions') }}
          </el-button>
        <el-button v-else type="primary" size="medium" @click="showRecordsDialog"
          >
          <!-- 答题记录 -->
          {{ $t('message.safetyEducation.answerRecord') }}
          </el-button>
        <ul class="questionList" style="padding: 0 0px 10px">
          <li v-for="(item,index) in ruleForm.questionList" :key="index">
            <div class="questionTitle">{{index+1}}、{{item.questionName}}（{{item.questionScore}}
              {{$t('message.safetyEducation.branch')}}）
              <!-- branch 分 -->
            </div>
            <div class="answers">
              <el-checkbox :value="data.correctType==1" v-for="(data,index2) in item.optionList" :key="index2">{{indexList[index2]}}、{{data.optionName}}</el-checkbox>
            </div>
            <!-- <div class="answers">
              <el-radio value="1" label="1">A、答案1</el-radio>
            </div> -->
            <div class="tableBtns" v-if="eduId==''">
              <div @click="editBefore(item,index)" class="operationText">
                <img
                  src="@/assets/images/icon-edit.png"
                  width="15px"
                  height="15px"
                />
                <span>{{ $t("message.workType.edit") }}</span>
              </div>
              <div @click="deleteBefore(index)" class="operationText">
                <img
                  src="@/assets/images/icon-delete.png"
                  width="15px"
                  height="15px"
                />
                <span>{{ $t("message.workType.delete") }}</span>
              </div>
            </div>
          </li>
        </ul>
      </vue-scroll>
      <div class="placeholderBox" v-if="ruleForm.questionList.length == 0">
          <img src="@/assets/images/noData.png" alt="" />
          <!-- 无试题 -->
          <p>{{ $t("message.safetyEducation.noQuestions") }}</p>
        </div>
    </div>
    <el-dialog
      :modal-append-to-body="false"
      :title="$t('message.workType.operate')[type]"
      :visible.sync="dialogVisible"
      width="667px"
    >
      <div class="dialog_content">
        <el-form
          label-width="120px"
          size="medium"
          class="dialogFormBox"
          ref="addEditForm"
          :model="addEditForm" :rules="addEditFormRules"
        >
        <!-- 试题类型 -->
          <el-form-item :label="$t('message.safetyEducation.testQuestionType')" prop="questionType">
            <el-select v-model="addEditForm.questionType" :placeholder="$t('message.workType.pleaseSelect')">
              <!-- 单选题 -->
              <el-option :label="$t('message.safetyEducation.singleChoice')" :value="'1'"></el-option>
              <!-- 多选题 -->
              <el-option :label="$t('message.safetyEducation.multipleChoice')" :value="'2'"> </el-option>
            </el-select>
          </el-form-item>
          <!-- 试题名称 -->
          <el-form-item :label="$t('message.safetyEducation.testTitle')" prop="questionName">
            <el-input
              v-model="addEditForm.questionName"
              :placeholder="$t('message.workType.placeholder')"
            ></el-input>
          </el-form-item>
          <!-- 试题分数 -->
          <el-form-item :label="$t('message.safetyEducation.testScore')" prop="questionScore">
            <!-- <el-input
              v-model="addEditForm.questionScore"
              :placeholder="$t('message.workType.placeholder')"
            ></el-input> -->
            <el-input-number v-model="addEditForm.questionScore" :min="1" :precision="0" :label="$t('message.workType.placeholder')" :controls="false"></el-input-number>
          </el-form-item>
          <!-- 试题选项及答案 -->
          <el-form-item :label="$t('message.safetyEducation.optionsAndAnswers')"> </el-form-item>
          <el-form-item
            :label="'A、'"
            prop="lsit"
            v-for="(item, index) in addEditForm.optionList"
            :key="index"
          >
            <template slot="label">
              <p>
                <el-checkbox :value="item.correctType" v-model="item.correctType"
                  >{{ indexList[index] }}、</el-checkbox
                >
              </p>
            </template>
            <el-input
              v-model="item.optionName"
              :placeholder="$t('message.workType.placeholder')"
            ></el-input>
            <i class="el-icon-remove" @click="removeOptions(index)"></i>
          </el-form-item>
          <el-form-item :label="''">
            <el-button type="primary" plain size="medium" @click="addOptions"
              >
              <!-- 新增选项 -->
              {{$t('message.safetyEducation.newOptions')}}
              </el-button
            >
          </el-form-item>
          <div class="dialog-footer">
            <el-button
              class="cancleBtn"
              @click="dialogVisible = false"
              icon="el-icon-circle-close"
              size="medium"
              >{{ $t("message.personnelPosition.cancel") }}
            </el-button>
            <el-button
              type="primary"
              icon="el-icon-circle-check"
              @click="saveQuesFn"
              size="medium"
              >{{ $t("message.personnelPosition.determine") }}
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <!-- 二维码 -->
    <el-dialog
      :title="$t('message.personnelPosition.qrCode')"
      :visible.sync="imgDialogVisible"
      width="50%">
      <div id="workerQRcode1" ref="workerQRcode1" class="workerQRcode workerQRcode1"></div>
      <p style="margin: 20px auto;text-align:center;font-size:25px">
        <!-- 请扫描二维码进行在线教育 -->
       {{$t('message.safetyEducation.pleaseScanQrCode')}}
      </p>
    </el-dialog>
    <!-- 答题记录 -->
    <el-dialog
      :title="$t('message.safetyEducation.answerRecord')"
      :visible.sync="recordDialogVisible"
      width="667px">
      <div class="">
        <div class="filterBox" style="margin:0 15px 10px">
          <!-- 按人员姓名搜索 -->
          <el-input :placeholder="$t('message.safetyEducation.searchByPersonName')" v-model="searchName" size="medium">
            <el-button slot="append" icon="el-icon-search" class="searchBtn" size="medium" @click="getRecords"></el-button>
          </el-input>
        </div>
        <div class="table_wrap whiteBlock">
          <el-table :data="personRecordList" class="tables" style="background:#0C1830;">
            <!-- 人员姓名 -->
            <el-table-column prop="workerName" :label="$t('message.safetyEducation.personnelName')"> </el-table-column>
            <!-- 答题时间 -->
            <el-table-column prop="studyTime" :label="$t('message.safetyEducation.answerTime')" width="250px"> </el-table-column>
            <!-- 考试分数 -->
            <el-table-column prop="score" :label="$t('message.safetyEducation.testScore')"> </el-table-column>
            <!-- 是否及格 -->
            <el-table-column prop="isQualified" :label="$t('message.safetyEducation.passOrNot')"> 
              <template slot-scope="scope">
                <!-- 合格: 不合格 -->
                {{scope.row.isQualified==1? $t('message.safetyEducation.qualified') : $t('message.safetyEducation.unqualified')}}
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="margin-top:20px"
            class="pagerBox"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNo"
            :page-sizes="$store.state.PAGESIZRS"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="recordsTotal"
            background
          ></el-pagination>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  safeEducationQuestionAddApi,
  safeEducationQuestionDetailApi,educationClassifyListApi,
  workerSafeEducationDetailApi2
} from "@/assets/js/api/laborPerson";
import QRCode from 'qrcodejs2'
export default {
  props:['eduId','classifyId'],
  data() {
    return {
      styleType: 1,
      ruleForm: {
        eduAddr: "",
        eduClasshour: "",
        eduContent: "",
        eduCourseName: "",
        eduPhoto: "",
        eduTeacher: "",
        eduTime: "",
        eduType: "",
        eduVideo: "",
        passScore: "",
        projectSn: "",
        questionList: [],
        totalScore: "",
        videoType: 1,
        classifyId:''
      },
      indexList: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "N",
        "M",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ],
      type: "add",
      addEditForm: {
        questionName: "",
        questionType:'',
        questionScore:0,
        sortNum:0,
        optionList: [
          {
            optionName: "",
            correctType:false,
          },
          {
            optionName: "",
            correctType:false,
          },
          {
            optionName: "",
            correctType:false,
          },
          {
            optionName: "",
            correctType:false,
          },
        ],
      },
      dialogVisible: false,
      rules: {
        eduCourseName: [
          // 请输入课程名称
          { required: true, message: this.$t('message.safetyEducation.rulesA1'), trigger: "blur" }
        ],
        eduType: [
          // 请选择课程类型
          { required: true, message: this.$t('message.safetyEducation.rulesA2'), trigger: "change" },
        ],
        classifyId:[
          // 请选择课程分类
          { required: true, message: this.$t('message.safetyEducation.rulesA3'), trigger: "change" }
        ],
        // 请上传课程视频
        eduVideo: [{ required: true, message: this.$t('message.safetyEducation.rulesA4'), trigger: "blur" }],
      },
      addEditFormRules:{
        questionType: [
          // 请选择试题类型
          { required: true, message: this.$t('message.safetyEducation.rulesA5'), trigger: "change" }
        ],
        questionName: [
          // 请输入试题名称
          { required: true, message: this.$t('message.safetyEducation.rulesA6'), trigger: "blur" },
        ],
      },
      educateTypeList: this.$t("message.laborDev.educateTypeList"),
      questionIndex:-1,
      classifyList:[],
      imgDialogVisible:false,
      qrcodeUrl:'',
      recordDialogVisible:false,
      personRecordList:[],
      searchName:'',
      pageNo:1,
      pageSize:10,
      recordsTotal:0
    };
  },
  mounted(){
    
    // console.log(process.env.NODE_ENV)
    this.ruleForm.classifyId=parseInt(this.classifyId)
    this.styleType = this.$store.state.userInfo.styleType
    console.log(this.styleType)
    if(this.eduId==''){
      if(this.$route.path.indexOf('/project/')!=-1){
        this.ruleForm.projectSn=this.$store.state.projectSn
      }else{
        this.ruleForm.projectSn=this.$store.state.userInfo.headquartersSn
      }
      this.getClassifyList()
    }else{
      this.createQRcode('')
      this.getDetailData()
    }
    
  },
  methods: {
    //生成二维码
    createQRcode(index){
      if(this.$route.path.indexOf('/project/')!=-1){
        let url = ''
        if (process.env.NODE_ENV == 'development'){
          url='http://192.168.34.210:6023/'
        }else{
          url=window.location.origin + "/"
        }
        let width = 90;
        let height = 90;
        if(index){
          width = 500;
          height = 500;
        }
        new QRCode('workerQRcode'+index, {
          width: width,
          height: height, // 高度
          text:url+'#/pages/projectEnd/safetyEducation/authentication?eduId='+this.eduId+'&projectSn='+this.$store.state.projectSn, // 二维码内容
          render: 'canvas',   // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
          // background: '#f0f',
          // foreground: '#ff0'
        });
      }
    },
    //展示大图
    showBig(){
      this.imgDialogVisible=true;
      this.$nextTick(()=>{
        this.createQRcode(1)
      })
      
    },
    handleClick(){

    },
    //视频上传成功
    handleSuccess(res,file){
      console.log(res,file)
      this.ruleForm.eduVideo=res.data[0].imageUrl
    },
    //获取详细数据
    getDetailData(){
      safeEducationQuestionDetailApi({eduId:this.eduId}).then(res=>{
        this.ruleForm=res.result.safeEducation
      })
    },
    addOptions() {
      this.addEditForm.optionList.push({
        optionName: "",
        correctType:false,
      });
    },
    removeOptions(index) {
      this.addEditForm.optionList.splice(index, 1);
    },
    editBefore(data,index){
      this.dialogVisible=true
      console.log(data)
      
      
      this.$nextTick(()=>{
        this.addEditForm=JSON.parse(JSON.stringify(data))
        var optionList=data.optionList
        this.questionIndex=index
        optionList.forEach((element,index) => {
          if(element.correctType==1){
            this.addEditForm.optionList[index].correctType=true
          }else{
            this.addEditForm.optionList[index].correctType=false
          }
        });
      })
      
    },
    deleteBefore(index){
      this.$confirm(this.$t('message.safetyEducation.determineDelete'), this.$t('message.safetyEducation.tips'), {
        confirmButtonText: this.$t('message.safetyEducation.determine'),
        cancelButtonText: this.$t('message.safetyEducation.cancel'),
        type: "warning",
      })
        .then(() => {
          this.ruleForm.questionList.splice(index,1)
          this.computeTotalScore()
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t('message.safetyEducation.deletionCancelled'),
          });
        });
      
    },
    saveQuesFn() {
      this.$refs['addEditForm'].validate((valid) => {
        if (valid) {
          var data = JSON.parse(JSON.stringify(this.addEditForm))
          var optionList=data.optionList
          if(optionList.length<2){
            // 请添加至少两个选项
              this.$message.error(this.$t('message.safetyEducation.rulesB1'))
              return;
          }
          var correctNum = 0
          optionList.forEach((element,index) => {
            if(element.optionName==''){
              // 请输入选项内容
              this.$message.error(this.$t('message.safetyEducation.rulesB2'))
              return;
            }
            if(element.correctType===true||element.correctType===1){
              data.optionList[index].correctType=1
              correctNum++
            }else{
              data.optionList[index].correctType=2
            }
          });
          console.log(data)
          if(data.questionType==1&&correctNum==0){
            // 请选中正确选项
            this.$message.error(this.$t('message.safetyEducation.rulesB3'))
              return;
          }
          if(data.questionType==1&&correctNum>1){
            // 正确选项只能是1个
            this.$message.error(this.$t('message.safetyEducation.rulesB4'))
              return;
          }
          if(data.questionType==2&&correctNum<2){
            // 正确选项必须大于1个
            this.$message.error(this.$t('message.safetyEducation.rulesB5'))
              return;
          }
          if(this.questionIndex==-1){
            this.ruleForm.questionList.push(data)
          }else{
            this.ruleForm.questionList[this.questionIndex]=data
          }
          
          this.dialogVisible=false
          this.computeTotalScore()
        } else {
          console.log("error submit!!");
          return false;
        }
      });

    },
    //计算试卷总分
    computeTotalScore(){
      var num=0
      this.ruleForm.questionList.forEach(element => {
        num+=parseInt(element.questionScore)
      });
      this.ruleForm.totalScore=num
    },
    addQuesFn() {
      this.questionIndex=-1
      this.dialogVisible = true;
      this.$nextTick(()=>{
        this.$refs['addEditForm'].resetFields();
        this.addEditForm.optionList=[
          {
            optionName: "",
            correctType:false,
          },
          {
            optionName: "",
            correctType:false,
          },
          {
            optionName: "",
            correctType:false,
          },
          {
            optionName: "",
            correctType:false,
          },
        ]
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let type=2// 2总企业，1项目
          if(this.$route.path.indexOf('/project/')!=-1){
            type=1
          }
          this.ruleForm.type=type
          safeEducationQuestionAddApi(this.ruleForm).then(res=>{
            // 保存成功！
            this.$message.success(this.$t('message.safetyEducation.savedSuccess'))
            // this.resetForm(formName)
            this.$emit('showList',true)
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //获取课程分类
    getClassifyList() {
        educationClassifyListApi({sn: this.ruleForm.projectSn}).then(result => {
            this.classifyList = result.result;
        })
    },
    handleSizeChange(value) {
      this.pageSize = value;
      this.getRecords();
    },
    handleCurrentChange(value) {
      this.pageNo = value;
      this.getRecords();
    },
    //获取答题记录
    getRecords(){
      let json = {
        pageNo:this.pageNo,
        pageSize:this.pageSize,
        projectSn:this.ruleForm.projectSn,
        workerName:this.searchName,
        eduId:this.eduId
      }
      workerSafeEducationDetailApi2(json).then(result => {
            this.personRecordList = result.result.records;
            this.recordsTotal=result.result.total
        })
    },
    showRecordsDialog(){
      this.searchName='';
      this.pageNo=1;
      this.pageSize=10;
      this.getRecords()
      this.recordDialogVisible=true
    }
  },
};
</script>
<style lang="less" scoped>
.parentContent {
  overflow: hidden;
  margin-top: 10px;
  height: calc(100% - 20px);
  // .whiteBlock{
  //   padding:15px;
  // }
  .left {
    width: 350px;
    float: left;
    margin-right: 15px;
    padding: 30px 30px 0 0;
    height: calc(100% - 30px);
  }
  .right {
    width: calc(100% - 435px);
    float: left;
    padding: 20px;
    height: calc(100% - 40px);
    position: relative;
  }
  .dark_right{
    width: calc(100% - 472px);
  }
}
.questionList {
  li {
    // border-top: 1px solid #ccc;
    box-shadow: 0 4px 14px 0px rgba(212, 220, 236, 0.69);
    padding: 20px;
    margin-top: 20px;
    border-radius: 8px;
    position: relative;
    .questionTitle {
      margin-bottom: 10px;
    }
    .answers {
      margin-left: 25px;
    }
    .desc {
      margin-left: 25px;
      font-size: 14px;
      margin-top: 10px;
    }
  }
}
.jyjzPage {
  .questionList{
    li{
      background-color: rgba(13, 26, 52, 1);
      box-shadow: 0px 1px 6px 0px rgba(18, 127, 236, 0.09);
      border: 1px solid rgba(20, 46, 90, 1);
    }
  }
}
.tableBtns {
  position: absolute;
  right: 20px;
  top: 20px;
  font-size: 14px;
}
.el-icon-remove {
  font-size: 20px;
  color: #ff3d3d;
  position: absolute;
  right: -30px;
  top: 7px;
  cursor: pointer;
}
.workerQRcode{
  margin: 20px auto;
  display: flex;
  justify-content: center;
  border: 1px solid rgba(212, 220, 236, 0.69);
  width: 90px;
  height: 90px;
  padding: 5px;
  cursor: pointer;
  background-color: white;
  border-radius: 3px;
}
.workerQRcode1{
  width: 500px;
  height: 500px;
}
.searchBtn{
  background-color: @--color-primary!important;
  color: white!important;
  // border-color: @--color-primary!important;
  border: none!important;
}
/deep/.el-input-group__append{
  border: none!important;
  background: none!important;
}
</style>