<!--选择组件-->
<template>
  <div class="select-manager-wrap">
      <div class="third-step">
        <el-form
          ref="formComponent"
          class="form-component"
          label-width="150px"
          :model="formComponent"
          :rules="rulesComponent"
        >
          <el-form-item label="选择组件：" prop="component">
            <el-col :span="10">
              <el-select
                v-model="formComponent.component"
                multiple
                collapse-tags
                filterable
                style="width: 350px"
                placeholder="请选择组件"
                @change="changeValue"
                :disabled="disabled"
              >
                <el-option
                  v-for="item in optionsComponent"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-col>
          </el-form-item>

          <el-form-item label="已选择：" class="check-component">
            <el-col :span="20" class="tags-list">
              <el-tag
                class = "tags-component"
                v-for="tag in tagsComponent"
                v-bind:class="{'tags-component-online': tag.disabled === true }"
                :key="tag.value"
                closable
                :type="tag.type"
                style="margin-left: 10px;"
                @close="handleCloseComponent(tag)"
              >{{tag.name}}</el-tag>
            </el-col>
          </el-form-item>

          <el-form-item required label="学习时长：" class="time-contrl">
            <el-col :span="10">
              <el-radio-group class="el-time-ctr" v-model="formComponent.courseRequire" :disabled="disabled">
                <el-radio :label="1">是（必须达到课程配置的观看时长要求才算通过）</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-col>
          </el-form-item>
        </el-form>

        <el-form
          ref="formExam"
          label-width="150px"
          :model="formExam"
          class="achievement"

        >
          <el-form-item required label="项目通过标准" :class="customError.standard.className">
            <el-select
                v-model="formExam.passType"
                placeholder="请选择"
                style="width: 350px"
                @change="updateCertificateType"
                :disabled="disabled"
              >
                <el-option
                  v-for="item in certificateTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              <div class="el-form-item__error" v-if="customError.standard.error != ''">{{customError.standard.error}}</div>
          </el-form-item>

          <el-form-item required label="累计学习时长大于等于:" v-show="formExam.passType == 3" :class="customError.passTotalLearnTime.className">
            <el-input placeholder="请输入" :disabled="disabled" v-model="formComponent.passTotalLearnTime" style="width:200px" @input="focusFun($event,'passTotalLearnTime')">
              <template slot="append">分钟</template>
            </el-input>
            <div class="el-form-item__error" v-if="customError.passTotalLearnTime.error != ''">{{customError.passTotalLearnTime.error}}</div>
          </el-form-item>

          <!--add 选择平均分展示-->
          <div v-show="formExam.passType == 2" >
              <div class="mleft60" v-show="formExam.passType == 2">
                <div class="mini-source" style="overflow: hidden;">
                  <el-form-item  label="项目中最高" label-width="80px" style="float: left;" :class="customError.passExamCount.className" class="min-label">
                    <div class="source-item">
                      <el-input placeholder="请输入数字" :disabled="disabled" size="mini" v-model="formComponent.passExamCount" style="width:150px"  @input="focusFun($event,'passExamCount')">
                        <template slot="append">门</template>
                      </el-input>
                    </div>
                    <div class="el-form-item__error" v-if="customError.passExamCount.error != ''">{{customError.passExamCount.error}}</div>
                  </el-form-item>
                  <div style="float: left;padding:0 5px;line-height: 26px;font-size: 12px;color:#606266">考试成绩的平均分大于等于</div>
                  <el-form-item  label="" label-width="0px" style="float: left;" :class="customError.passAverageScore.className"  class="min-label">
                    <div class="source-item">
                       <el-input placeholder="请输入数字" :disabled="disabled" size="mini" v-model="formComponent.passAverageScore" style="width:150px" @input="focusFun($event,'passAverageScore')">
                         <template slot="append">分</template>
                       </el-input>
                    </div>
                    <div class="el-form-item__error" v-if="customError.passAverageScore.error != ''">{{customError.passAverageScore.error}}</div>
                  </el-form-item>
                   <div style="float: left;padding:0 5px;line-height: 26px;font-size: 12px;color:#606266">则项目通过</div>
                </div>
              </div>
          </div>

          <el-form-item required label="配置证书：">
            <el-col :span="10">
            <el-radio-group class="el-configure" v-model="formComponent.configure" :disabled="disabled">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
            </el-col>
          </el-form-item>

          <!--edit 选择配置证书展示-->
          <div v-show="formComponent.configure == 1 && formExam.passType == 2" v-for="(item , index) in formExam.exam" :key="index">
            <div class="mleft60">
              <div class="soure-configure">

                  <div class="configure-item">
                      <el-form-item label="平均分:" label-width="65px" style="float: left;" :class="item.minClass" class="min-label">
                        <el-col :span="5">
                          <el-input :disabled="disabled" placeholder="请输入数字" size="mini" v-model="item.rangeMin" style="width:215px"  @input="focusFun($event,'rangeMin',index)">
                           <template slot="append">分</template>
                          </el-input>
                        </el-col>
                        <div class="el-form-item__error" v-if="item.minError">{{item.minError}}</div>
                      </el-form-item>
                      <div style="float: left;padding:0 5px;line-height: 26px;">~</div>
                      <el-form-item  label-width="0" style="float: left;margin-left:0px;" :class="item.maxClass" class="min-label">
                         <el-col :span="5">
                           <el-input :disabled="disabled" placeholder="请输入数字" size="mini" v-model="item.rangeMax" style="width:215px"  @input="focusFun($event,'rangeMax',index)">
                            <template slot="append">分</template>
                           </el-input>
                         </el-col>
                         <div class="el-form-item__error" v-if="item.maxError">{{item.maxError}}</div>
                      </el-form-item>
                  </div>
                 <div class="configure-item">
                   <el-form-item label="发放证书:" style="margin-left: -85px;" :class="item.certClass">
                     <el-select
                       v-model="item.certificateId"
                       placeholder="请选择证书"
                       size="mini"
                       style="width: 450px;"
                       @change="updateCertificate(index)"
                       :disabled="disabled"
                     >
                       <el-option
                         v-for="item in optionsCertificate"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value"
                       ></el-option>
                     </el-select>
                     <div class="el-form-item__error" v-if="item.certError">{{item.certError}}</div>
                   </el-form-item>
                 </div>
                 <div class="configure-option">
                   <el-button size="mini" @click="addCertificate" icon="el-icon-plus" circle :disabled="disabled"></el-button>
                   <el-button size="mini" @click="reduceCertificate(index)" icon="el-icon-minus" circle :disabled="disabled"></el-button>
                 </div>
              </div>
            </div>
          </div>

          <el-form-item required v-show="formComponent.configure == 1 && (formExam.passType == 1 || formExam.passType == 3)" label="发放证书" :class="customError.certificate.className">
            <el-select
              v-model="formComponent.certificate"
              placeholder="请选择证书"
              style="width: 350px"
              :disabled="disabled"
            >
              <el-option
                v-for="item in optionsCertificate"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <div class="el-form-item__error" v-if="customError.certificate.error != ''">{{customError.certificate.error}}</div>
          </el-form-item>

        </el-form>
      </div>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import { openLoading, closeLoading } from "../../../utils/utils";
import * as commonUtil from "../../../utils/utils";
import * as operationData from "../../../utils/operation";
import Sortable from "sortablejs";

let vm = null;
export default {
  props: {
    openTemplateId: {
      type: String | Number,
      deault: 0
    },
    messageObj: {
      type: Object,
      default:() => {
        return null
      }
    },
    isEditor: {
      type: Boolean,
      default: true
    },
    newBuild: {
      type: Boolean,
      default: true
    }
  },
  data() {
    let checkNormalInt = (rule, value, callback) => {
      const val = parseFloat(value);
      const isInteger = Number.isInteger(val);
      if (!value || (isInteger && val >= 0 && val <= 100)) {
        callback();
      } else {
        callback(new Error(`请输入0~100正整数`));
      }
    };
    return {
      customError: {
        standard: {
          className: "",
          error: ""
        },
        certificate: {
          className: "",
          error: ""
        },
        passTotalLearnTime: {
          className: "",
          error: ""
        },
        passExamCount: {
          className: "",
          error: ""
        },
        passAverageScore: {
          className: "",
          error: ""
        }
      },
      //选择项目组件 数据
      optionsComponent: [],
      optionsCertificate: [],
      formComponent: {
        component: [],
        configure: 2,
        certificate: "",
        courseRequire: 0, //模板内课程的完成是否受学习时长控制：0否1是
        passExamCount: "", //模板中最高考试门数限制：passType=2时有值
        passAverageScore: "", //门数限制下考试成绩的平均分限制：passType=2时有值
        passTotalLearnTime: ""
      },
      tagsComponent: [],
      projectStatus: "",
      status4Flag: "",
      showStorage: false,
      //考试数据
      formExam: {
        certificateType: 1, //模板证书类型：1单证书2多证书
        passType: 1,  //模板通过标准类型：1所有组件通过，2根据平均分设定，3根据项目内学习时长设定
        exam: [
          {
            examCount: 1,
            rangeMin: "",
            rangeMax: "",
            certificateId: "",
            certificateName: ""
          }
        ]
      },
      certificateTypeList: [
        {
          label: "所有组件通过",
          value: 1
        },
        {
          label: "根据平均分设定",
          value: 2
        },
        {
          label: "根据项目内学习时长设定",
          value: 3
        }
      ],
      organizationContent: "",
      //校验工具 数据
      rulesComponent: {
        component: [
          { required: true, message: "请选择组件", trigger: "change" }
        ],
        certificate: [
          { required: true, message: "请选择证书", trigger: "change" }
        ],
        visitTime: [
          { required: false, trigger: "change", validator: checkNormalInt }
        ],
        showRules1: [{ required: true, message: "请输入门数", trigger: "blur" }]
      },
      disabled: false
    };
  },
  computed: {
    ...mapGetters(["_token"])
  },
  created() {
    vm = this;
    
    vm.getComponentInfo();
    if (!vm.newBuild){
      vm.setEditData(this.messageObj);
    }
    if (!vm.newBuild && !vm.isEditor) {
      this.disabled = true;
    } else {
       this.disabled = false;
    }
  },
  // 挂载到Dom完成时
  mounted: function() {
    commonUtil.resizeHeight();
  },
  methods: {
    // 输入校验
    focusFun(ev, parm, index) {
      console.log('=================focusFun');
      if (index != undefined) {
        if (parseInt(ev) < 0 || !this.checkIntFun(ev)) {
          console.log(typeof index);
          this.formExam.exam[index][parm] = "";
        }
        if (parm == "rangeMax" && parseInt(ev) > 100) {
          this.formExam.exam[index][parm] = "100";
        }
        if (ev != "") {
          if (parm == "rangeMax") {
            this.formExam.exam[index].maxClass = "";
            this.formExam.exam[index].maxError = "";
          }
          if (parm == "rangeMin") {
            this.formExam.exam[index].minClass = "";
            this.formExam.exam[index].minError = "";
          }
        }
      } else {
        if (parseInt(ev) < 0 || !this.checkIntFun(ev)) {
          this.formComponent[parm] = "";
        }
        if (parm == "passAverageScore" && parseInt(ev) > 100) {
          this.formComponent[parm] = "100";
        }
        if (ev != "") {
          this.customError[parm] = {
            className: "",
            error: ""
          };
        }
      }
    },
    // add 校验输入是否为整数
    checkIntFun(str) {
      console.log('=================checkIntFun');
      let r = /^\+?[0-9]*$/;
      return r.test(str);
    },
     //查询组件证书信息
    getComponentInfo() {
      console.log('=================getComponentInfo');
      vm
        .GET("portal/openTemplate/getAllComponent")
        .then(res => {
          if (res.code == "000000") {
            //console.log(res);
            let componentList = res.data.componentList;
            let certificateList = res.data.certificateList;
            let optionsComponent = [],
              optionsCertificate = [];
            for (let index = 0; index < componentList.length; index++) {
              optionsComponent[index] = {};
              optionsComponent[index].value = componentList[index].id;
              optionsComponent[index].label = componentList[index].name;
              optionsComponent[index].name = componentList[index].name;
            }
            for (let index = 0; index < certificateList.length; index++) {
              optionsCertificate[index] = {};
              optionsCertificate[index].value = certificateList[index].id;
              optionsCertificate[index].label = certificateList[index].name;
              optionsCertificate[index].name = certificateList[index].name;
            }
            this.optionsComponent = optionsComponent;
            this.optionsCertificate = optionsCertificate;
            this.organizationContent = res.data.creatorOrganizationName;
          }
        });
    },
    //项目组件信息 暂存/完成  1暂存2保存3发布
    componentDraft(type) {
      console.log('=================componentDraft');
      let param = {
        // componentIds: this.formComponent.component,
        componentIds: operationData.getComponent(vm.tagsComponent),
        // certificateId: this.formComponent.certificate,
        certificateId: [],
        openTemplateId: this.openTemplateId,
        type: type,
        status: this.projectStatus,
        certificateType: this.formExam.passType == 2 ? 2 : 1,
        getCertificateRule: [],
        courseRequire: this.formComponent.courseRequire,
        passType: this.formExam.passType
      };
      if (this.formExam.passType == 2) {
        param.passAverageScore = this.formComponent.passAverageScore;
        param.passExamCount = this.formComponent.passExamCount;
      }
      if (this.formExam.passType == 3) {
        param.passTotalLearnTime = this.formComponent.passTotalLearnTime;
      }
      // console.log('排序后',vm.tagsComponent,'param',param);
      if (this.formComponent.configure == 1) {
        //  2.多证书有规
        if (this.formExam.passType == 2) {
          let ruleData = vm.formExam.exam;
          for (let o = 0; o < ruleData.length; o++) {
            if (
              ruleData[o].certificateId != "" &&
              ruleData[o].certificateId != null
            ) {
              param.certificateId[o] = ruleData[o].certificateId;
            }
            param.getCertificateRule[o] = {
              certificateId: ruleData[o].certificateId,
              certificateName: ruleData[o].certificateName,
              examCount: ruleData[o].examCount,
              openTemplateId: this.openTemplateId,
              rangeMax: ruleData[o].rangeMax,
              rangeMin: ruleData[o].rangeMin
            };
          }
        } else {
          // 1.单证书无规则
          if (
            this.formComponent.certificate != "" &&
            this.formComponent.certificate != null
          ) {
            param.certificateId[0] = this.formComponent.certificate;
          }
        }
      }
      vm.POST("portal/openTemplate/componentDraft", param).then(res => {
        console.log(res);
        vm.$message({
          message: res.message,
          type: "info"
        });
        if (res.code == "000000") {
          //notify
          if (type == 3) {
            let query = {};
            if (this.$route.query.pageNum) {
              query = { pageNum: this.$route.query.pageNum };
            }
            this.$router.push({ path: "template-manager", query: query });
            // this.$router.push("item-manager?pageNum="+this.$route.query.pageNum);
          }
        }
      });
    },
    //选择项目组件
    //改变组件选择情况
    changeValue(value) {
      console.log('=================changeValue');
      this.tagsComponent = [];
      let len = 0;
      for (let i = 0; i < value.length; i++) {
        for (let j = 0; j < this.optionsComponent.length; j++) {
          if (value[i] == this.optionsComponent[j].value) {
            this.tagsComponent[len] = {};
            this.tagsComponent[len] = this.optionsComponent[j];
            this.tagsComponent[len].value = this.optionsComponent[j].value;
            this.tagsComponent[len].name = this.optionsComponent[j].label;
            len++;
          }
        }
      }
      //console.log('this.tagsComponent',this.tagsComponent);
    },
    // 如有数据时  初始化
    setEditData(editData) {
      //设置选择项目组件页
      let componentEdit = [];
      let certificateEdit = 0;
      for (let i = 0; i < editData.componentData.length; i++) {
        componentEdit.push(editData.componentData[i].relevanceId);
      }
      this.formComponent.component = componentEdit;
      this.initTags(componentEdit);
      if (editData.certificateData.length > 0) {
        this.formComponent.configure = 1;
        this.formComponent.certificate =
          editData.certificateData[0].relevanceId;
      }
      if (editData.certificateRule.length > 0) {
        this.formComponent.configure = 1;
      }
      //初始化考试平均分配置数据
      this.formExam.certificateType = editData.portalOpenTemplateModel.certificateType;
      this.formExam.passType = editData.portalOpenTemplateModel.passType;
      this.formExam.exam = editData.certificateRule;
      if (this.formExam.exam.length > 0) {
        for (let k = 0; k < this.formExam.exam.length; k++) {
          this.formExam.exam[k].certClass = "";
          this.formExam.exam[k].certError = "";
          this.formExam.exam[k].minClass = "";
          this.formExam.exam[k].minError = "";
          this.formExam.exam[k].maxClass = "";
          this.formExam.exam[k].maxError = "";
        }
      }
      console.log(this.formExam.exam);
      this.formComponent.passAverageScore =
        editData.portalOpenTemplateModel.passAverageScore > 0
          ? editData.portalOpenTemplateModel.passAverageScore
          : "";
      this.formComponent.passExamCount =
        editData.portalOpenTemplateModel.passExamCount > 0
          ? editData.portalOpenTemplateModel.passExamCount
          : "";
      this.formComponent.passTotalLearnTime =
        editData.portalOpenTemplateModel.passTotalLearnTime;
      if (this.formExam.exam.length == 0) {
        this.formExam.exam = [
          {
            examCount: 1,
            rangeMin: "",
            rangeMax: "",
            certificateId: "",
            certificateName: "",
            minClass: "",
            minError: "",
            maxClass: "",
            maxError: "",
            certClass: "",
            certError: ""
          }
        ];
      }
    },
    initTags(value) {
      //console.log('value',value,'optionsComponent',this.optionsComponent);
      this.tagsComponent = [];
      let len = 0;
      for (let i = 0; i < value.length; i++) {
        for (let j = 0; j < this.optionsComponent.length; j++) {
          if (value[i] == this.optionsComponent[j].value) {
            this.tagsComponent[len] = {};
            this.tagsComponent[len].value = this.optionsComponent[j].value;
            this.tagsComponent[len].name = this.optionsComponent[j].label;
            if (vm.status4Flag == 1) {
              this.optionsComponent[j].disabled = true;
              this.tagsComponent[len].disabled = true;
            }
            len++;
          }
        }
      }
      console.log("this.optionsComponent值：", this.optionsComponent);
    },
    //关闭已选择组件
    handleCloseComponent(tag) {
      console.log('=================handleCloseComponent');
      if (tag.disabled == true) {
        return;
      }
      // if (this.projectStatus == 1 || this.projectStatus == 2) {
      this.tagsComponent.splice(this.tagsComponent.indexOf(tag), 1);
      this.formComponent.component = [];
      for (let j = 0; j < this.tagsComponent.length; j++) {
        this.formComponent.component[j] = this.tagsComponent[j].value;
      }
      // }
    },
    // 增加配置证书
    addCertificate() {
      console.log('=================addCertificate');
      if (vm.formExam.exam.length == 5) {
        return vm.$message("最多配置5个证书");
      }
      let obj = {
        examCount: 1,
        rangeMin: "",
        rangeMax: "",
        certificateId: "",
        certificateName: "",
        minClass: "",
        minError: "",
        maxClass: "",
        maxError: "",
        certClass: "",
        certError: ""
      };
      vm.formExam.exam.push(obj);
    },
    // 减少配置证书
    reduceCertificate(index) {
     console.log('=================reduceCertificate');
      if (vm.formExam.exam.length > 1) {
        vm.formExam.exam.splice(index, 1);
      } else {
        vm.$message("至少配置1个证书");
      }
    },
    // 选择证书
    updateCertificate(index) {
      // console.log('optionsCertificate',vm.optionsCertificate,'index',index,'item',vm.formExam.exam[index])
      for (let i = 0; i < vm.optionsCertificate.length; i++) {
        if (
          vm.optionsCertificate[i].value ==
          vm.formExam.exam[index].certificateId
        ) {
          vm.formExam.exam[index].certificateName =
            vm.optionsCertificate[i].label;
          break;
        }
      }
      vm.formExam.exam[index].certClass = "";
      vm.formExam.exam[index].certError = "";
    },
    //更新项目成绩评定条件
    updateCertificateType() {
      console.log('=================updateCertificateType');
      console.log("更新certificateType", vm.formExam.certificateType);
      if (vm.formExam.passType == 2) {
        vm.formExam.exam = [
          {
            examCount: 1,
            rangeMin: "",
            rangeMax: "",
            certificateId: "",
            certificateName: "",
            minClass: "",
            minError: "",
            maxClass: "",
            maxError: "",
            certClass: "",
            certError: ""
          }
        ];
      } else if (vm.formExam.passType == 1) {
        vm.formComponent.certificate = "";
      }
    },
    setMoreOption(data, type) {
      console.log('=================setMoreOption');
      let option = [];
      for (let i = 0; i < data.length; i++) {
        let obj = data[i];
        if (type == "cities") {
          obj.label = data[i].cityName;
          obj.value = data[i].cityId;
        } else if (type == "counties") {
          obj.label = data[i].countyName;
          obj.value = data[i].countyId;
          // obj.leaf = true;
        } else if (type == "towns") {
          obj.label = data[i].townName;
          obj.value = data[i].townId;
          obj.leaf = true;
        }
        option.push(obj);
      }
      return option;
    }
  }
};
</script>
<style lang="scss">
.min-label {
  .el-form-item__label {
    line-height: 26px;
  }
  .el-form-item__content {
    line-height: 26px;
  }
}
.select-manager-wrap {
  padding-top: 64px;
  .mleft60 {
    margin-left: 60px;
  }
  .soure-configure {
    background: #f9f9f9;
    padding: 15px;
    width: 550px;
    font-size: 12px;
    color: #606266;
    position: relative;
    margin-bottom: 20px;
    .configure-option {
      position: absolute;
      right: -95px;
      top: 50%;
      margin-top: -15px;
    }
    .mb15 {
      margin-bottom: 15px;
    }
    .configure-item {
      overflow: hidden;
      .configure-item-l {
        display: inline-block;
        width: 60px;
        text-align: right;
      }
    }
  }
  .mini-source {
    background: #f9f9f9;
    width: 650px;
    padding: 15px;
    margin-bottom: 20px;
    .source-item {
      padding-top: 0px;
      font-size: 12px;
      line-height: 28px;
      color: #606266;
    }
  }
  .third-step {
    margin: 30px 0 0px 30px;
    padding-bottom: 30px;
    ::-webkit-scrollbar {
      width: 4px;
      height: 20px;
      background-color: #d8d8d8;
    }
    ::-webkit-scrollbar-thumb {
      background-color: #d8d8d8;
    }
    .el-tag {
      margin-top: 5px;
      display: table;
      background-color: #e6f1fc;
      color: #389efe;
    }
    .el-select {
      .el-tag {
        i {
          display: none;
        }
      }
    }
    .tags-list {
      border: 1px #e8e8e8 solid;
      height: 350px;
      min-width: 280px;
      overflow-y: scroll;
    }
    .tags-component-online {
      color: #9aceff;
      background-color: #f3f8fe;
      border-color: #d5eafe;
    }
    .achievement {
      margin-top: 60px;
    }
    .form-component {
      position: relative;
    }
    .check-component {
      top: 0px;
      right: 5%;
      position: absolute;
      z-index: 999;
    }
    .el-time-ctr {
      .el-radio {
        display: block;
        padding: 10px 0;
      }
    }
    .el-configure {
      width: 200px;
    }
    .time-contrl {
      .el-input__inner {
        padding-right: 0;
      }
      .el-input-group__append {
        padding: 0 8px;
      }
    }
  }
}
.edit-img {
  width: 20px;
}
.popover-content {
  position: relative;
  top: 0;
  left: 0;
}
</style>
