<!--新增模板-->
<template>
  <div class="page-container certificateTemplate-addPage">
    <div class="page-container-top-max-big-box">
      <p class="top-1-p">{{newData.id?'编辑证书模板':'新增证书模板'}}</p>
      <p class="top-2-p" @click="backPage()">返回</p>
      <p class="top-4-p" @click="submitForm()">保存</p>
    </div>
    <div class="content-box">
      <div class="left-content-box">
        <el-form class="add-form-box" :model="newData" ref="form" :rules="rules" label-width="120px">
          <el-form-item label="证书模板名称" prop="templateName" style="margin-top:20px;">
            <el-input v-model="newData.templateName" placeholder="请输入证书模板名称" maxLength="20" style="width:500px;"></el-input>
          </el-form-item>
          <el-form-item label="适用考试类型" prop="templateType">
            <el-select v-model="newData.templateType" placeholder="请选择证书类型" style="width: 500px">
              <el-option
                v-for="dict in optionList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="颁发单位" prop="deptId">
            <el-cascader
              style="width: 500px"
              v-model="newData.deptId"
              :options="optionDeptList"
              :props="{
                emitPath:false,
                checkStrictly: true,
                value: 'deptId',
                label: 'deptName',
                children: 'child',
              }"
              :show-all-levels="false"
              filterable
              placeholder="请选择颁发单位"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="证书模板" prop="templateWordPath">
            <el-upload
              drag
              :action="uploadImgUrl"
              :show-file-list="false"
              accept=".docx"
              :on-success="handleAvatarSuccess"
              :headers="headers"
              :before-upload="beforeAvatarUpload">
              <i class="el-icon-upload"></i>
              <p v-if="upData.length > 0" style="margin-top: 10px; color: #606266;">
                已选中文件：<strong>{{ upData[0].name }}</strong>
              </p>
              <div v-else class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传docx文件，且不超过{{ fileSizeLimit }}MB</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="描述说明" prop="description">
            <el-input v-model="newData.description" placeholder="请输入描述说明" maxLength="20" style="width:500px;"></el-input>
          </el-form-item>
          <el-form-item label="是否共享" prop="shareStatus">
            <el-switch
              :active-value="1"
              :inactive-value="0"
              v-model="newData.shareStatus"
              active-color="#0183FB"
              inactive-color="#AAAAAA">
            </el-switch>
          </el-form-item>
        </el-form>
      </div>
      <div class="right-content-box">
        <p class="right-title-p">证书模板变量</p>
        <p class="right-text-p">证书内容通过文本替换的方式，将您上传的docx文件中的固定变量名称替换成具体的值，变量名称请严格区分大小写!</p>
        <div class="right-text-box">
          <div class="right-for-box" v-for="(item,index) in textList" :key="index">
            <p>{{item.value}}</p>
            <p>{{item.name}}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { getToken } from "@/utils/auth";
  //import { getDicts } from "@/api/commonality/noPermission";
  //import { systemUserSelect } from "@/api/commonality/permission";
  import { examElExamTypeList,systemDeptCurrentDept,examElCertificateTemplateAdd,examElCertificateTemplateEdit } from "@/api/safetyEducationExaminationNew/index";
  export default {
    name: 'addPage',
    props:{
      propsData:{},
    },
    data(){
      return{
        fileSizeLimit:20,//文件大小限制
        uploadImgUrl: this.uploadUrl(), // 上传的图片服务器地址
        headers: {
          Authorization: getToken(),
        },
        upData:[],
        optionList:[{value:'1',label:'考试证书'},{value:'2',label:'培训证书'},],
        optionDeptList:[],
        newData:{
          templateName:'',
          templateType:null,
          deptId:null,
          templateWordPath:'',
          description:'',
          shareStatus:1,
        },
        rules:{
          templateName: [
            { required: true, message: "请输入证书模板名称", trigger: "blur" },
            { required: true, message: "请输入证书模板名称", validator: this.spaceJudgment, trigger: "blur" }
          ],
          templateType: [
            { required: true, message: "请选择考试类型", trigger: "blur" },
            { required: true, message: "请选择考试类型", validator: this.spaceJudgment, trigger: "blur" }
          ],
          deptId: [
            { required: true, message: "请选择颁发单位", trigger: "blur" },
            { required: true, message: "请选择颁发单位", validator: this.spaceJudgment, trigger: "blur" }
          ],
          templateWordPath: [
            { required: true, message: "请上传证书模板", trigger: "blur" },
            { required: true, message: "请上传证书模板", validator: this.spaceJudgment, trigger: "blur" }
          ],
        },
        textList:[
          {value:'{{cnName}}',name:'学院名称'},
          {value:'{{userName}}',name:'用户姓名'},
          {value:'{{account}}',name:'学工号'},
          {value:'{{today}}',name:'发证日期'},
          {value:'{{certNo}}',name:'证书编号'},
        ],
      }
    },
    created(){

    },
    mounted(){
      this.initialize();
      // this.examElExamTypeList();
      this.systemDeptCurrentDept();
    },
    methods:{
      initialize(){
        if(this.propsData.id){
          this.$set(this,'newData',{
            id:this.propsData.id,
            templateName:this.propsData.templateName,
            templateType:this.propsData.templateType,
            deptId:this.propsData.deptId,
            templateWordPath:this.propsData.templateWordPath,
            description:this.propsData.description,
            shareStatus:this.propsData.shareStatus,
          });
          this.$set(this,'upData',[{
            name:this.propsData.templateName+'.docx'
          }]);
        }
      },
      // 返回按钮
      backPage(){
        this.$parent.tableButton(6);
      },
      /** 提交按钮 */
      submitForm() {
        let self = this;
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(this.newData.id){
              this.examElCertificateTemplateEdit();
            }else{
              this.examElCertificateTemplateAdd();
            }
          }
        })
      },
      examElCertificateTemplateAdd(){
        let obj = JSON.parse(JSON.stringify(this.newData));
        obj.enableStatus = 1;
        examElCertificateTemplateAdd(obj).then(response => {
          this.msgSuccess(response.message);
          this.$parent.tableButton(6);
        });
      },
      examElCertificateTemplateEdit(){
        let obj = JSON.parse(JSON.stringify(this.newData));
        obj.enableStatus = 1;
        examElCertificateTemplateEdit(obj).then(response => {
          this.msgSuccess(response.message);
          this.$parent.tableButton(6);
        });
      },
      //上传
      handleAvatarSuccess(res, file) {
        this.$set(this.newData,'templateWordPath',res.data.url);
        this.$set(this,'upData',[res.data]);
        this.$forceUpdate()
      },
      beforeAvatarUpload(file) {
        if (!this.checkFileType(file)) {
          return;
        }
        let type = false;
        if (file.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
          type = true;
        }else{
          this.msgError('只能上传docx格式文件');
          type = false;
        }
        return type;
      },
      //文件校验
      checkFileType(file) {
        // 提取文件后缀并转小写
        const fileName = file.name || '';
        const fileExt = fileName.split('.').pop().toLowerCase();
        const validTypes = ['docx'];
        if (!validTypes.includes(fileExt)) {
          this.$message.error('只能上传 docx 格式的文件！');
          return false;
        }
        const isLt20M = file.size / 1024 / 1024 < this.fileSizeLimit;
        if (!isLt20M) {
          this.$message.error('上传文件大小不能超过 '+this.fileSizeLimit+'MB！');
          return false;
        }
        return true;
      },
      //考试类型
      examElExamTypeList(){
        examElExamTypeList({}).then(response => {
          this.$set(this,'optionList',response.data);
        });
      },
      //学院列表
      systemDeptCurrentDept(){
        systemDeptCurrentDept({}).then(response => {
          const list = response.data || [];
          this.formatTreeData(list);
          this.$set(this,'optionDeptList',list);
        });
      },
    },
  }
</script>

<style scoped lang="scss">
  .certificateTemplate-addPage{
    .content-box{
      flex:1;
      display: flex;
      .left-content-box{
        flex:1;
      }
      .right-content-box{
        width:600px;
        border-left:1px solid #dedede;
        padding:20px 30px;
        .right-title-p{
          font-size:16px;
          line-height:20px;
          font-weight:700;
          margin:10px 0 30px 0;
        }
        .right-text-p{
          background-color: #F0F9EB;
          border-radius: 4px;
          font-size:14px;
          padding:10px;
          line-height:20px;
          color:#74C578;
        }
        .right-text-box{
          margin-top:20px;
          background-color: #dedede;
          padding:5px 10px;
          border-radius:4px;
          .right-for-box{
            display: flex;
            p{
              line-height:30px;
              font-size:14px;
            }
            p:nth-child(1){
              width:100px;
            }
            p:nth-child(2){
              flex:1;
              margin-left:20px;
            }
          }
        }
      }
    }
  }
</style>
