<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="appModuleId" v-if="ruleForm.linkType == 4">
            <el-select v-model="ruleForm.appModuleId" filterable class="form-input" placeholder="请选择模块" clearable>
            <el-option
                v-for="item in nameList"  :key="item.id"  :label="item.name" :value="item.id">
            </el-option>
            </el-select>
          </el-form-item>
           <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:""
      },
      contentTitle:'项目详情页',
      ruleType:'每次打开均弹',
      rules: {
        linkType: [
            { required: true, message: '请选择链接类型', trigger: 'change' }
          ],
         projectIds: [
            { required: true, message: '请选择所属项目', trigger: 'change' }
          ],
         boxImgUrl: [
            { required: true, message: '请上传配图', trigger: 'change' }
          ],
         appModuleId: [
            { 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:[],
      nameList:[],
      optionsProject:[]
    }
  },
  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.ruleForm = {...res.data, appModuleId:res.data.moduleInfo ? res.data.moduleInfo.id : "", 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`);
      // }
    },
    // 获取链接类型下拉数据
    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.nameList = res.data.nameList || [];
          }
        })
        .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;
      }
      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;
          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) {
      vm.$refs[formName].validate((valid) => {
        if (valid) {
          let req = {
            appModuleId: vm.ruleForm.linkType == 8 ? 0 : vm.ruleForm.appModuleId || 0,
            boxImgUrl:vm.ruleForm.boxImgUrl,
            content:vm.ruleForm.content,
            pageType:vm.ruleForm.pageType,
            projectIds:vm.ruleForm.projectIds,
            ruleType:vm.ruleForm.ruleType,
            showTimes:vm.ruleForm.showTimes,
            title:vm.ruleForm.title,
            unit:vm.ruleForm.unit,
            unitTimes:vm.ruleForm.unit,
          };
          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>