<template>
  <div class="edit-simple-adv-wrap">
    <bread-crumb :curmbFirst="curmbFirst" :curmbSecond="title"></bread-crumb>
    <div class="component-content screenSet" id="screenSet">
      <div class="header-title">{{ title }}</div>
      <el-form
        ref="formData"
        :model="formData"
        :rules="rules"
        label-width="150px"
        class="basic-form"
      >
        <el-form-item label="链接类型：">
          <el-col :span="10">
            <el-select
              v-model="formData.jumpType"
              collapse-tags
              style="width: 300px"
              placeholder="请选择链接类型"
              filterable
            >
              <el-option
                label="URL链接"
                value="1"
              ></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="跳转URL：" prop="jumpUrl">
          <el-col :span="13">
            <el-input
              maxlength="100"
              type="input"
              placeholder="请输入跳转URL："
              v-model="formData.jumpUrl"
              style="width: 300px"
            ></el-input>
            <span class="word-num">{{(formData.jumpUrl).replace(/\s+/g,"").length}}/100</span>
          </el-col>
        </el-form-item>
        <el-form-item label="页面类型：" prop="pageType">
          <el-col :span="10">
            <el-select
              v-model="formData.pageType"
              collapse-tags
              style="width: 300px"
              placeholder="请选择页面类型"
              filterable
            >
              <el-option label="项目详情页" value="1"></el-option>
              <!-- <el-option label="项目列表页" value="0"></el-option> -->
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="所属项目：" prop="projectId">
          <el-col :span="10">
            <el-select
              v-model="formData.projectId"
              style="width: 300px"
              placeholder="所属项目"
              filterable
            >
              <el-option
                size="small"
                v-for="item in optionsProject"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="页面位置：">
          <el-col :span="10">
            <el-select
              v-model="formData.position"
              collapse-tags
              style="width: 300px"
              placeholder="请选择页面位置"
              filterable
            >
              <el-option label="顶部广告位" value="0"></el-option>
              <el-option label="底部广告位" value="1"></el-option>
            </el-select>
          </el-col>
        </el-form-item>

        <div class="basic-item-icon">
          <span class="require">*</span>
          <el-form-item label="上传图片：" prop="imageUrl" style="height: 100px;">
            <el-upload
              style="height: 100px;"
              v-model="formData.imageUrl"
              class="bg-uploader"
              action="#"
              :show-file-list="false"
              :before-upload="beforeUploadListPic"
            >
              <img
                v-if="formData.imageUrl"
                :src="formData.imageUrl"
                class="bg-img"
              />
              <img
                v-if="!formData.imageUrl"
                class="bg-img"
                src="../../../assets/image/small.png"
              />
              <!-- <div
                class="img-delete"
                v-show="imgMouseOver"
                @click.stop="deleteImg(1)"
                @mouseout.stop="imgMouseOver=false"
              >
                <i class="el-icon-delete"></i>
              </div> -->
              <div class="limit-text">
                <p>尺寸:750*120</p>
                <p>限制大小: 2.0M</p>
                <p>支持.jpg,.png格式</p>
              </div>
            </el-upload>
          </el-form-item>
          <p class="upload-message" v-if="uploadImgMessage">请选择列表图片</p>
        </div>
        <el-form-item label="状态：" >
          <el-select v-model="formData.status" placeholder="请选择状态" style="width: 300px">
            <el-option v-for="(item, index) in statusList" :key="index" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="btn-list" style="margin: 40px 0;">
          <el-button @click="submitForm('formData')" type="primary">提 交</el-button>
          <el-button @click="goBack">取 消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <DialogComponet :dialogObj="dialogObj" @hide="insertOrUpdate" @confirm="dialogObj.visible=false"></DialogComponet>
  </div>
</template>
<script>
import BreadCrumb from "../../../components/breadcrumb.vue";
import DialogComponet from "@/components/education/template/dialog";
import { doUpload, getFilePath } from "../../../utils/qiniu-util";
import { mapGetters } from "vuex";
import { openLoading, closeLoading } from "../../../utils/utils";
import * as commonUtil from "../../../utils/utils";
import * as operationData from "../../../utils/operation";
let vm = null;
export default {
  components: {
    BreadCrumb,
    DialogComponet
  },
  data() {
    return {
      curmbFirst: "教培项目",
      curmbSecond: "广告位管理",
      title: "编辑广告位",
      id: null,
      uploadImgMessage: false,
      imgMouseOver: false,
      formData: {
        id: "",
        jumpType: "1",
        jumpUrl: "",
        pageType: "1",
        position: "0",
        projectId: "",
        imageUrl: "",
        status: 0,
      },
      optionsProject: [],
      statusList: [
        {
          name: '不发布',
          value: 0
        },{
          name: '发布',
          value: 1
        },{
          name: '下线',
          value: 2
        }
      ],
      dialogObj: {
        visible: false,
        title: "",
        message: "此位置已存在广告位，是否替换原有的广告位？",
        tip: "",
        confirmMsg: "取 消",
        hideMsg: "确 定"
      },
      rules: {
        jumpUrl: [
          { required: true, message: "请输入跳转URL", trigger: "blur" }
        ],
        projectId: [
          { required: true, message: "请选择所属项目", trigger: "blur" }
        ],
        imageUrl: [
          { required: true, message: "请上传图片", trigger: "blur" }
        ],
      }
    };
  },
  computed: {

  },
  created() {
    vm = this;
    vm.id = vm.getUrlSearch(window.location.href, "id");
    vm.initTitle();
    vm.initOption();
  },
  mounted: function() {
    commonUtil.resizeHeight();
  },
  methods: {

    // 初始化Title
    initTitle() {
      if (!vm.id) {
        vm.title = "新建广告位";
      } else {
        vm.title = "编辑广告位";
      }
    },

    // 设置信息
    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() {
      vm.optionsProject = [];
      let req = {
        status: 4,
        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);
          vm.getAdvertInfo();
        }
      });
    },

    // 返回到上一页
    goBack() {
      vm.$router.back(-1);
    },

    // 提交前校验
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.checkAdvert();
          // this.insertOrUpdate();
        } else {
          console.log("error submit!!");
        }
      });
    },

    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    //  删除图片
    deleteImg() {
      vm.formData.imageUrl = "";
      vm.imgMouseOver = false;
    },

    // 上传
    beforeUploadListPic(file) {
      let fileLimit = {
        width: 750,
        height: 120,
        size: 2,
        sizeText: "2M",
        key: "imageUrl",
        show: "uploadImgMessage"
      };
      this.beforeAvatarUpload(file, fileLimit);
    },

    beforeAvatarUpload(file, fileLimit) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < fileLimit.size;
      if (!isJPG && !isPNG) {
        this.$message.error("图片不符合规范，请根据规范上传图片");
        return;
      }
      if (!isLt2M) {
        this.$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;
          if (_this.width != fileLimit.width || _this.height != fileLimit.height) {
            vm.$message.error("图片不符合规范，请根据规范上传图片");
          } else {
            openLoading(vm);
            doUpload(
              vm,
              file,
              getFilePath(file, null),
              "preview4",
              "progress1",
              1
            ).then(function(path) {
              closeLoading(vm);
              console.log(path);
              vm.formData.imageUrl = path.fullPath;
              vm.$message.success("上传成功");
            });
          }
        };
      };
    },



    // 获取广告配置详情
    getAdvertInfo() {
      if (!vm.id) {
        return;
      }
      let req = {
        id: vm.id
      };
      openLoading(vm);
      vm.GET(`portal/jump/${vm.id}`, req).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          // this.formData = res.data;
          vm.setEditData(res.data);
        } else {
          vm.$message(res.message);
        }
      });
    },

    // 添加或修改 结果 0：无替换的配置 1：有需要替换的配置，提示替换
    checkAdvert() {
      vm.POST("portal/jump/check",
        this.formData
        ).then(res => {
        if (res.code == "000000") {
          if(res.data == 0) {
            this.insertOrUpdate();
          } else {  // 弹出确认框
            this.dialogObj.visible = true;
          }
        } else {
          vm.$message.error(res.message);
        }
      });
    },

    // 添加或修改
    insertOrUpdate() {
      openLoading(vm);
      vm.POST("portal/jump/insertOrUpdate",
        this.formData
        ).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          vm.$message({
            message: '创建成功',
            type: 'success'
          });
          vm.$router.back(-1);
        } else {
          vm.$message.error(res.message);
        }
      });
    },

    // 设置编辑数据
    setEditData(resData) {
      this.formData = resData;
      this.formData.jumpType = resData.jumpType + '';
      this.formData.pageType = resData.pageType + '';
      this.formData.position = resData.position + '';      
    },
  }
};
</script>
<style lang="scss">
.edit-simple-adv-wrap {
  .component-content {
    position: relative;
    padding: 10px;
    background: #fff;
    .header-title {
      padding: 10px 12px;
      font-size: 12px;
      color: #449284;
      border-bottom: 1px solid #efefef;
    }
    .basic-form {
      height: 100px !important;
      ::-webkit-scrollbar
      {
          width: 4px;
          height: 20px;
          background-color: #D8D8D8;
      }
      ::-webkit-scrollbar-thumb {
          background-color: #D8D8D8;
      }
      position: relative;
      margin-top: 10px;
      .basic-item-icon {
        position: relative;
        .require {
          position: absolute;
          left: 67px;
          top: 11px;
          color: #f56c6c;
        }
        .upload-message {
          position: absolute;
          left: 160px;
          top: 105px;
          font-size: 12px;
          color: #f56c6c;
        }
        .img-delete {
          position: absolute;
          left: 0px;
          top: 0px;
          width: 84px;
          height: 100px;
          background: #000;
          opacity: 0.7;
          z-index: 999;
          i {
            color: #fff;
            margin-top: 39px;
            margin-left: 0px;
          }
        }
      }
      .word-num {
        font-size: 12px;
        color: #999;
        padding-top: 5px;
      }
      .line {
        margin-left: 10px;
        width: 20px;
      }
      .bg-uploader {
        img {
          float: left;
        }
        .bg-img {
          width: 100px;
          height: 100px;
        }
        .limit-text {
          float: left;
          margin-left: 10px;
          margin-top: -10px;
          p {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
  }
}
</style>