<template>
  <div class="editeach-popup">
     <bread-crumb :curmbFirst="curmbFirst" :curmbSecond="curmbSecond"></bread-crumb>
      <div class="component-content screenSet" id="screenSet">
        <div class="header-title">{{showTitle}}弹窗</div>
        <div class="formInfo">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="标题" prop="title">
              <el-input v-model="ruleForm.title" class="form-input" placeholder="请输入标题" maxlength="10" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="内容" prop="content">
            <el-input type="textarea" v-model="ruleForm.content" class="form-input" placeholder="请输入内容" maxlength="20" show-word-limit></el-input>
          </el-form-item>
           <el-form-item label="页面类型" class="form-input" prop="contentTitle">
          <el-select v-model="contentTitle" class="form-input">
            <el-option label="项目详情页" value="项目详情页"></el-option>
          </el-select>
           </el-form-item>
          <el-form-item label="所属项目"  prop="projectIds">
            <el-select multiple v-model="ruleForm.projectIds" filterable class="form-input" placeholder="请选择所属项目">
            <el-option
                v-for="item in optionsProject"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="链接类型" prop="linkType">
            <el-select v-model="ruleForm.linkType" class="form-input" placeholder="请选择链接类型" clearable>
            <el-option
                v-for="item in linkSelect"  :key="item.value"  :label="item.label" :value="item.value">
            </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择模块" prop="appModuleDto" v-if="ruleForm.linkType == 4">
            <el-select v-model="ruleForm.appModuleDto.name" filterable class="form-input" @change="moduleChange" placeholder="请选择模块" clearable>
            <el-option
                v-for="item in moduleArray.nameList"  :key="item.id"  :label="item.name" :value="item.name">
            </el-option>
            </el-select>
          </el-form-item>
          <div v-for="(iteml,index) in parameterList" :key="index">
            <el-form-item label="选择参数:" prop="param" v-if="ruleForm.appModuleDto.paramFlag == 1 && ruleForm.linkType == 4">
                <el-select v-model="ruleForm.appModuleDto.paramList[index].value" filterable placeholder="请选择参数" class="form-input">
                    <el-option
                    v-for="(item1,index1) in iteml"
                    :key="index1"
                    :label="item1.name"
                    :value="item1.id + '&' + item1.name">
                    </el-option>
                </el-select>
            </el-form-item>
         </div>
        <div class="basic-item-icon">
          <el-form-item label="弹框配图" class="required-label" prop="boxImgUrl">
            <el-upload
              v-model="ruleForm.boxImgUrl"
              class="bg-uploader"
              action="#"
              :show-file-list="false"
              :before-upload="beforeUploadPic1"
            >
              <img
                v-if="ruleForm.boxImgUrl"
                :src="ruleForm.boxImgUrl"
                @mouseover.stop="imgMouseOver1=true"
                class="bg-img"
              />
              <img v-if="!ruleForm.boxImgUrl" class="bg-img" src="../../assets/image/small.png" />
              <div
                class="img-delete"
                v-show="imgMouseOver1"
                @click.stop="deleteImg(1)"
                @mouseout.stop="imgMouseOver1=false"
              >
                <i class="el-icon-delete"></i>
              </div>
              <div class="limit-text">
                <p>宽度：650PX,高度：小于860PX</p>
                <p>大小：1.5M以内</p>
                <p>仅支持JPEG/PNG/GIF格式</p>
              </div>
            </el-upload>
          </el-form-item>
        </div>
          <el-form-item label="显示规则" prop="ruleType">
            <el-select v-model="ruleType">
              <el-option label="每次打开均弹" value="每次打开均弹"></el-option>
            </el-select>
        </el-form-item>
          <el-form-item label="展示频次" prop="showTimes">
            1天最多 <el-input v-model="ruleForm.showTimes" class="form-input-Show" maxlength="2" placeholder="请输入次数"></el-input> 次
          </el-form-item>
          <el-form-item v-if="showType != 1">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button :style="{marginLeft:'100px'}" type="primary"  @click="seeLook">预览</el-button>
          </el-form-item>
          </el-form>
        </div>
      </div>
      <el-dialog
        title="预览"
        :visible.sync="dialogVisibleJp"
        width="50%"
        :before-close="handleClose">
        <div id="qrcode" class="qrcode-wrap"></div>
        <span slot="footer" class="dialog-footer">
      </span>
    </el-dialog>
  </div>
</template>

<script>
import BreadCrumb from "../../components/breadcrumb.vue";
import { doUpload, getFilePath } from "../../utils/qiniu-util";
import { openLoading, closeLoading } from "../../utils/utils";
import { getEdUrl } from "@/utils/index";
import QRCode  from "qrcodejs2"
let vm = null
export default {
  components: {
    BreadCrumb,
    QRCode
  },
  data() {
    return {
      curmbFirst: "教培项目",
      curmbSecond: "弹窗管理",
      showType:'',
      showId:'',
      ruleForm: {
          title: "",
          content:"",
          boxImgUrl:"",
          pageType:0,
          projectIds:[],
          ruleType:0,
          unit:1,
          unitTimes:"",
          linkType:"",
          appModuleId:"",
          appModuleIdChild:'',
          appModuleDto:{
            name: '',
            linkType: 4,
            paramFlag: 2,
            code: '',
            paramList: [],
            paramList2: []
        }
      },
      contentTitle:'项目详情页',
      ruleType:'每次打开均弹',
      rules: {
        linkType: [
            { required: true, message: '请选择链接类型', trigger: 'change' }
          ],
         projectIds: [
            { required: true, message: '请选择所属项目', trigger: 'change' }
          ],
         boxImgUrl: [
            { required: true, message: '请上传配图', trigger: 'change' }
          ],
        //  appModuleDto: [
        //     { required: true, message: '请选择模块', trigger: 'change' }
        //   ],
         showTimes:[
            { required: true, message: '请输入次数', trigger: 'change' },
            { pattern: /^\d+$|^\d+[.]?\d+$/, message: '请输入正确格式,只允许数字哦'}
          ],
      },
      rankList:[],
      hiddenFileList: false,
      fileList:[],
      imgMouseOver1: false,
      qrcodeBox: null,
      dialogVisibleJp:false,
      linkSelect:[],
      moduleArray:[],
      optionsProject:[],
      parameterList:[],
      paramFlag:''
    }
  },
  created() {
    vm = this
    const { id, showType } = vm.$route.query;
    vm.showType = showType;
    vm.showId = id;
    if (id) {
      vm.getIdDetail();
    }
    vm.getLinkType();
    vm.getModuleData();
    vm.initOption();
  },
  computed: {
    showTitle() {
      if (vm.showType == 3) {
        return '新增'
      }else if (vm.showType == 1) {
        return '查看'
      }else {
         return '编辑'
      }
    }
  },
  methods: {
     // 获取弹窗详情
    getIdDetail() {
       openLoading(vm);
       vm.GET(`portal/popBox/getPopBoxDetails/${vm.showId}`).then((res) => {
          closeLoading(vm);
          if (res.code == "000000") {
            vm.getModuleData();
            vm.ruleForm = {...res.data, appModuleDto:res.data.moduleInfo ? res.data.moduleInfo : {
            name: '',
            linkType: 4,
            paramFlag: 2,
            code: '',
            paramList: [],
            paramList2: []
        }, linkType:res.data.moduleInfo ? res.data.moduleInfo.linkType : 8};
          } else {
            vm.$message.error(res.data.message);
          }
        })
        .catch(function(error) {
          closeLoading(vm);
          vm.$message.error(error);
        });
    },
    // 取消
    cancel() {
      // if (vm.ruleForm.title || vm.ruleForm.content ||  vm.ruleForm.startTime || vm.ruleForm.endTime || vm.ruleForm.imageUrl || vm.ruleForm.limitNum || vm.ruleForm.originalPrice || vm.ruleForm.rank) {
      //   vm.dialogVisibleDown = true;
      // }else {
        this.$router.push(`/teaching-popup`);
      // }
    },
    moduleChange(value) {
      for(let i = 0; i < vm.moduleArray.nameList.length; i++) {
          if(value == vm.moduleArray.nameList[i].name) {
              vm.ruleForm.appModuleDto.code = vm.moduleArray.nameList[i].code
              vm.ruleForm.appModuleDto.type = vm.moduleArray.nameList[i].type
              vm.ruleForm.appModuleDto.paramFlag = vm.moduleArray.nameList[i].paramFlag
              vm.getParamData(vm.moduleArray.nameList[i].id,vm.moduleArray.nameList[i].paramFlag,2)
              break
          }
      }
    },
    getParamData(id, flag ,a) {
      if (flag != 1) return; // 判断是否有参数选择
      vm.GET(`contents/moduleConfig/selectParam?id=${id}`)
        .then( res => {
          if (res.code == "000000") {
            vm.parameterList = res.data.paramList || [];
            vm.paramConfig = res.data.config
            vm.ruleForm.appModuleDto.paramFlag = 1
            if(a == 2) { // 判断是初始化还是改变module调的获取参数接口
                vm.ruleForm.appModuleDto.paramList = []
                for(let j = 0 ;j < vm.parameterList.length; j++) {
                    vm.ruleForm.appModuleDto.paramList.push({
                        seqNo: vm.paramConfig[j].seqNo,  // 选择参数的索引值
                        value: '',
                        key: vm.paramConfig[j].paramKey,
                        type: vm.paramConfig[j].type,  // 通过选择参数中获取
                        status: 2
                    })
                }
            }else {

                let arr = vm.ruleForm.appModuleDto.paramList
                vm.ruleForm.appModuleDto.paramList= [];
                if(arr.length < vm.paramConfig.length) {
                    for(let k = 0;k < arr.length; k++) {
                        vm.ruleForm.appModuleDto.paramList.push({
                            seqNo: vm.paramConfig[k].seqNo,
                            key: vm.paramConfig[k].paramKey,
                            type: vm.paramConfig[k].type,
                            value: arr[k].value
                        })
                    }
                    for(let j = arr.length;j < vm.paramConfig.length;j++) {
                            vm.ruleForm.appModuleDto.paramList.push({
                            seqNo: vm.paramConfig[j].seqNo,
                            key: vm.paramConfig[j].paramKey,
                            type: vm.paramConfig[j].type,
                            value: ''
                        })
                    }
                }else {
                    for(let k = 0;k < vm.paramConfig.length; k++) {
                        vm.ruleForm.appModuleDto.paramList.push({
                            seqNo: vm.paramConfig[k].seqNo,
                            key: vm.paramConfig[k].paramKey,
                            type: vm.paramConfig[k].type,
                            value: arr[k].value
                        })
                    }
                }
            }
          }
        })
        .catch(function (error) {
          vm.$message.error(error);
        });
    },
    // 获取链接类型下拉数据
    getLinkType() {
      vm.GET(`contents/commonComstant/selectByTypeCode?code=${'C005'}`)
        .then(function (res) {
          if (res.code == "000000") {
            let linkObject = JSON.parse(JSON.stringify(res.data)); //通过这个实现深拷贝
            let keys = Object.keys(linkObject);
            for (var i = 0; i < keys.length; i++) {
              vm.linkSelect.push({
                label: linkObject[keys[i]],
                value: keys[i] - 0,
              });
            }
          }
        })
        .catch(function (error) {
          vm.$message.error(error);
        });
    },
     // 获取模块下拉数据
    getModuleData() {
       vm.GET(`contents/moduleConfig/selectName`)
        .then(function (res) {
          if (res.code == "000000") {
           vm.moduleArray = res.data || [];
           for(let j = 0;j < vm.moduleArray.nameList.length; j++) {
              if(vm.ruleForm.appModuleDto.name == vm.moduleArray.nameList[j].name){
                  vm.getParamData(vm.moduleArray.nameList[j].id,vm.ruleForm.appModuleDto.paramFlag,1)
                  break
              }
            }
          }
        })
        .catch(function (error) {
          vm.$message.error(error);
        });
    },
      // 设置选择框选项
    setOption(data) {
      let list = [];
      for(let i = 0; i<data.length ; i++) {
        let obj = {
          value: data[i].projectId,
          label: data[i].projectName,
        }
        list.push(obj);
      }
      return list;
    },
     // 初始化项目选择框
    initOption() {
      let req = {
        status: 0,
        type: 2
      };
      openLoading(vm);
      vm.GET("portal/entryInfo/getProjectList", req).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          console.log('000000');
          vm.optionsProject = vm.setOption(res.data);
        }
      });
    },
    //上传圈子头像
    beforeUploadPic1(file) {
      let fileLimit = {
        width: 650,
        height: 860,
        size: 1.5,
        sizeText: "500K",
        key: "boxImgUrl",
        more: "imgUrl1More",
        show: "uploadImgMessage1"
      };
      this.beforeUpload(file, fileLimit);
    },
    //上传图片
    beforeUpload(file, fileLimit) {
      let vm = this;
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 /1024 < fileLimit.size;
      console.log(file.size / 1024 /1024);
      console.log(fileLimit.size);
      console.log(isLt2M, 'isLt2M');
      if (!isJPG && !isPNG) {
        vm.$message.error("图片必须是jpeg或png格式，同时长宽尺寸和图片大小需符合要求");
        return;
      }
      if (!isLt2M) {
        vm.$message.error("图片大小不符合规范，请根据规范上传图片 ");
        return;
      }
      console.log(file.width, 'file.width');
      let _img = new FileReader();
      _img.readAsDataURL(file);
      _img.onload = function (theFile) {
        let image = new Image()
        image.src = theFile.target.result
        image.onload = function () {
          let _this = this;
          if (_this.width != 650) {
          vm.$message.info('图片尺寸不一致，无法提交!');
          return;
      }
          console.log(_this.width);
          openLoading(vm);
            doUpload(vm, file, getFilePath(file, null), "preview4", "progress1", 1).then(function (path) {
              closeLoading(vm);
              console.log('上传成功后路径', path);
              if (fileLimit.show == "uploadImgMessage1") {
                vm.uploadImgMessage1 = false;
              } else if (fileLimit.show == "uploadImgMessage2") {
                vm.uploadImgMessage2 = false;
              }
              vm.ruleForm[fileLimit.key] = path.fullPath;
              vm.ruleForm[fileLimit.more] = {
                attachmentName: path.name,
                attachmentExt: path.ext,
                attachmentSize: path.size
              };
              vm.$message.success("上传成功");
            });
        };
      };
      return isJPG && isLt2M;
    },
    //删除图片
    deleteImg(type) {
      if (type == 1) {
        vm.ruleForm.boxImgUrl = "";
        vm.imgMouseOver1 = false;
      }
    },
    seeLook() {
      vm.submitForm('ruleForm', 'pre')
      // vm.preViewFn();
    },
    preViewFn() {
      let downloadUrl = getEdUrl('url');
      console.log(downloadUrl, 'downloadUrldownloadUrldownloadUrl');
      vm.link = `${downloadUrl}?showjpId=${vm.showId}`
      vm.dialogVisibleJp = true;
      vm.$nextTick (function () {
       vm.qrcode();
      })
    },
    // 提交
    submitForm(formName, pre) {
      console.log(vm.ruleForm, 'vm.ruleFormvm.ruleForm');
      if(vm.ruleForm.linkType == 4){
          if(!vm.ruleForm.appModuleDto.name){
              vm.$message.info("请选择模块")
              return
          }
      }
      if(vm.ruleForm.appModuleDto.paramFlag == 1){
          for(let i=0;i<vm.ruleForm.appModuleDto.paramList.length;i++) {
              if(!vm.ruleForm.appModuleDto.paramList[i].value){
                  vm.$message.info("请选择参数")
                  return
              }
          }
      }
      vm.$refs[formName].validate((valid) => {
        if (valid) {
          let req = {
            title:vm.ruleForm.title,
            content:vm.ruleForm.content,
            pageType:vm.ruleForm.pageType,
            jumpFlag: vm.ruleForm.linkType == 8 ? 0 : 1,
            projectIds:vm.ruleForm.projectIds,
            boxImgUrl:vm.ruleForm.boxImgUrl,
            ruleType:vm.ruleForm.ruleType,
            unit:vm.ruleForm.unit,
            unitTimes:vm.ruleForm.unit,
            showTimes:vm.ruleForm.showTimes,
            appModuleDto:vm.ruleForm.appModuleDto
          };
          if (vm.showId) {
            req = {...req, id:vm.showId}
          }
          openLoading(vm);
          vm.POST("portal/popBox/saveOrUpdate", req)
            .then((res) => {
              if (res.code == "000000") {
                closeLoading(vm);
                if (pre == 'pre') {
                   vm.showId = res.data;
                    vm.preViewFn();
                  }else {
                    vm.$message({
                      message: '保存成功',
                      type: 'success'
                    });
                    vm.$router.go(-1);
                  }
              } else {
                vm.$message.info(res.message);
              }
            })
            .catch(function (error) {
              vm.$message.error(error);
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
     //  生成二维码
    qrcode () {
      if (vm.qrcodeBox) {
        vm.qrcodeBox.makeCode(vm.link);
        return;
      }
      vm.qrcodeBox = new QRCode('qrcode', {
        width: 400,
        height: 400,
        text: vm.link,   // 二维码内容
        // render: 'canvas' ,   // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
        // background: '#f0f',   // 背景色
        // foreground: '#ff0'    // 前景色
      })
    },
    // 关闭预览弹框
     handleClose() {
      vm.dialogVisibleJp = false;
     },
  }
}
</script>

<style lang="scss">
  .editeach-popup{
     .component-content {
      background: #fff;
      padding: 10px;
      .header-title {
        padding: 10px 12px;
        font-size: 12px;
        color: #449284;
        border-bottom: 1px solid #efefef;
      }
      .formInfo{
        margin-top: 30px;
        .form-input {
         width: 500px;
        }
        .form-input-Show{
          width: 125px;
        }
        .avatar-uploader-icon {
            background-color: #fbfdff;
            border: 1px dashed #c0ccda;
            border-radius: 6px;
            box-sizing: border-box;
            width: 148px;
            height: 148px;
            cursor: pointer;
            line-height: 146px;
            vertical-align: top;
        }
        .basic-item-icon{
          width: 500px;
           .bg-uploader{
             .el-upload{
              display: flex;
              align-items: center;
                .limit-text{
                  text-align: left;
                  margin-left: 20px;
                  p{
                    line-height: 20px;
                  }
                }
             }
             .bg-img{
               width: 120px;
             }
        }
        }

      }
    }
    .qrcode-wrap {
  width: 400px;
  height: 400px;
  margin: 0 auto;
}
  }
</style>
