<!--基础信息-->
<template>
  <div class="base-message-wrap">
    <el-form
      ref="formData"
      :model="formData"
      :rules="rules"
      label-width="150px"
      class="basic-form"
    >
      <el-form-item label="项目名称：" prop="projectName">
        <el-col :span="13">
          <el-input
            size="small"
            v-model="formData.projectName"
            placeholder="请输入项目名称"
            style="width:70%;"
            ref="projectName"
          ></el-input>
          <span class="word-num">{{(formData.projectName).replace(/\s+/g,"").length}}/24</span>
        </el-col>
      </el-form-item>

      <el-form-item label="发起机构名称：">
        <el-col :span="13" v-for="(item, index) in formData.organizationNameList" :key="index">
          <el-input
            size="small"
            v-model="formData.organizationNameList[index]"
            placeholder="请输入发起机构名称"
            style="width:70%;"
            maxlength=16
            @input="changeOrganizationName"
            @blur = "blurName"
            @focus = "focusName(index)"
          ></el-input>
          <span class="word-num">{{(formData.organizationNameList[index]).replace(/\s+/g,"").length}}/16</span>
          <img @click="plusOrg(index)" class="edit-img" src="../../../assets/image/plus.png" />
          <img @click="deleteOrg(index)" v-if="index >= 1" class="edit-img" src="../../../assets/image/trash.png" />
        </el-col>
        <el-popover
          class="popover-content" :style="{'top': orgListIndex * 41 + 'px'}"
          placement="bottom"
          :content="organizationContent"
          v-model="visibleName"
          @click="checkDefault">
          <p @click="checkDefault"> 我的机构： {{ formData.creatorOrganizationName }} </p>
        </el-popover>
      </el-form-item>

      <div>
        <el-form-item label="项目时间：" required>
          <el-col :span="5">
            <el-form-item prop="projectBegintime">
              <el-date-picker
                v-model="formData.projectBegintime"
                size="small"
                type="datetime"
                placeholder="请选择开始时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions0"
                style="width: 100%;"
                :disabled="formData.status4Flag == 1"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="1">~</el-col>
          <el-col :span="5">
            <el-form-item label prop="projectEndtime">
              <el-date-picker
                v-model="formData.projectEndtime"
                size="small"
                type="datetime"
                placeholder="请选择结束时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions1"
                default-time="23:59:59"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <p class="time-message"><i class="el-icon-warning-outline"></i>项目有效期为{{formData.expireDay}}天,选择项目起止时间须在有效期内</p>
      </div>

      <div class="basic-item-icon">
        <span class="require">*</span>
        <el-form-item label="列表图片：">
          <el-upload
            v-model="formData.attachmentUrl1"
            class="bg-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeUploadListPic"
            disabled
          >
            <img v-if="formData.attachmentUrl1" @mouseover.stop="imgMouseOver=true" :src="formData.attachmentUrl1" class="bg-img">
            <img
              v-if="!formData.attachmentUrl1"
              class="bg-img"
              src="../../../assets/image/small.png"
            >
            <div class="img-delete" v-show="imgMouseOver && false" @click.stop="deleteImg(1)" @mouseout.stop="imgMouseOver=false"><i class="el-icon-delete"></i></div>
            <div class="limit-text">
              <p>尺寸:230*172</p>
              <p>限制大小: 500Kb</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-radio-group
          size="small"
          v-model="formData.type"
          @change="changeCover"
          disabled
        >
          <el-radio :label="1">图片</el-radio>
          <el-radio :label="2">视频</el-radio>
        </el-radio-group>
      </el-form-item>

      <div class="basic-item-icon">
        <span class="require">*</span>
        <el-form-item label="封面文件：">
          <el-upload
            v-model="formData.attachmentUrl2"
            class="bg-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeUploadCoverPic"
            disabled
          >
            <img
              v-if="formData.type == 1 && formData.attachmentUrl2"
              :src="formData.attachmentUrl2"
              @mouseover.stop="imgMouseOver2=true"
              class="bg-img"
            >
            <video
              v-if="formData.type == 2 && formData.attachmentUrl2"
              width="100"
              controls
              class="bg-video"
              @mouseover.stop="imgMouseOver2=true"
            >
              <source :src="formData.attachmentUrl2" type="video/mp4">浏览器不支持mp4
            </video>
            <img
              v-if="!formData.attachmentUrl2"
              class="bg-img"
              src="../../../assets/image/small.png"
            >
            <div class="img-delete" v-show="imgMouseOver2 && false" @click.stop="deleteImg(2)" @mouseout.stop="imgMouseOver2=false"><i class="el-icon-delete"></i></div>
            <div v-show="formData.type == 1" class="limit-text">
              <p>尺寸:750*420</p>
              <p>限制大小: 2.0 Mb</p>
              <p>支持.jpg,.png格式</p>
            </div>
            <div v-show="formData.type == 2" class="limit-text">
              <p></p>
              <p>限制大小: 500 Mb</p>
              <p>支持.mp4</p>
            </div>
          </el-upload>
        </el-form-item>
        <p class="upload-message" v-if="uploadImgMessage2">请选择封面</p>
      </div>

      <el-form-item label="项目简介：" prop="projectIntro">
        <el-col :span="13">
          <el-input
            size="small"
            type="textarea"
            :autosize="{ minRows: 5}"
            placeholder="请输入项目简介"
            v-model="formData.projectIntro"
            style="width:83%;"
          ></el-input>
          <span class="word-num">{{(formData.projectIntro).replace(/\s+/g,"").length}}/200</span>
        </el-col>
      </el-form-item>
    </el-form>

    <dialog-componet :dialogObj="dialogObj" @confirm="confirm" @hide="hide"></dialog-componet>
  </div>
</template>

<script>
import { doUpload, getFilePath } from "../../../utils/qiniu-util";
import { openLoading, closeLoading } from "../../../utils/utils";
import dialog from "./dialog";
let vm = null;
export default {
  props: {
    openTemplateId: {
      type: String | Number,
      default: ''
    },
    projectId: {
      type: String | Number,
      default: ''
    },
    editor: {
      type: Boolean,
      default: false
    }
  },
  data() {
    let checkProjectStr = (rule, value, callback) => {
      if (value.indexOf("\\") != -1) {
        //存在
        callback(new Error("请勿输入字符“ \\ ”"));
      } else if (value.indexOf(".") != -1) {
        callback(new Error("请勿输入字符“ . ”"));
      } else {
        callback();
      }
    };
    let checkUserTime= (rule, value, callback) => {
      if (value> 1000 || value < 1) {
        callback(new Error("输入长度为1-1000的有效期"));
      } else {
        callback();
      }
    };
    return {
      visibleName: false, //是否显示机构提示
      orgListIndex: 1,
      organizationContent: '',//机构名称
      formData: {
        id: "", //项目 id  26
        projectName: "",    //开放模板名称
        projectBegintime: "",    //模板开始时间
        projectEndtime: "",      //模板结束时间
        projectIntro: "",   //开放模板简介
        projectType: 3, //类型 
        type: 1,               //封面类型 1图片2视频
        projectStatus: 3, //1.草稿 2.未上架 3.审核中/待审核 4.已上架 5.已下架 6.已拒绝/未上架
        expireDay: 1, //模板有效期（天）
        status4Flag: 0, //0表示没有上过架，1表示上过架
        attachmentUrl1: "",
        attachmentUrl2: "",
        attachmentUrl3: "",
        attachmentMore1: {
          attachmentExt: "",
          attachmentName: "",
          attachmentSize: 0
        },
        attachmentMore2: {
          attachmentExt: "",
          attachmentName: "",
          attachmentSize: 0
        },
        organizationName: "",       // 发起机构名称（多个机构拼接
        organizationNameList: [''] //发起机构列表
      },
      attachmentModel:[    //基础信息的图片视频
        {
          attachmentExt: '',// 附件格式
          attachmentName: '',//附件名称
          attachmentSize:'',//附件大小,
          attachmentType: 1,//1：图片 2：视频 3：pdf
          attachmentUrl: '',//附件链接
          id: '', //关联唯一ID
          kind: 1, //1：列表图片 2：封面配置 3：附件配置
          openTemplateId: ''//开放模板id
        },
         {
          attachmentExt: '',// 附件格式
          attachmentName: '',//附件名称
          attachmentSize:'',//附件大小,
          attachmentType: 1,//1：图片 2：视频 3：pdf
          attachmentUrl: '',//附件链接
          id: '', //关联唯一ID
          kind: 1, //1：列表图片 2：封面配置 3：附件配置
          openTemplateId: ''//开放模板id
        }
      ],
      pickerOptions0: {
        disabledDate: time => {
          if (
            vm.formData.projectEndtime != "" &&
            vm.formData.projectEndtime != null
          ) {
            return (
              time.getTime() > new Date(vm.formData.projectEndtime).getTime()
            );
          }
        }
      },
      pickerOptions1: {
        disabledDate: time => {
          return (
            time.getTime() < new Date(vm.formData.projectBegintime).getTime() || time.getTime() > new Date(vm.formData.projectBegintime).getTime() + 1000 * 60 * 60 * 24 * vm.formData.expireDay
          ); //减去一天的时间代表可以选择同一天;
        }
      },
      imgMouseOver: false,
      imgMouseOver2: false,
      uploadImgMessage: false,
      uploadImgMessage2: false,
      rules: {
        projectName: [
          { required: true, message: "请输入项目名称" },
          {
            min: 2,
            max: 24,
            message: "输入长度为2-24的内容，可包含中英文、数字及特殊符号",
            trigger: "blur"
          },
          { validator: checkProjectStr, trigger: "blur" }
        ],
        projectBegintime: [
          {
            required: true,
            message: "请选择时间",
            trigger: "change"
          }
        ],
        projectEndtime: [
          {
            required: true,
            message: "请选择时间",
            trigger: "change"
          }
        ],
        projectIntro: [
          { required: true, message: "请填写项目简介", trigger: "blur" },
          { min: 1, max: 200, message: "超出可输入的最大长度", trigger: "blur" }
        ]
      },
      disabled: true,
      dialogObj: {
        visible: false,
        title: '该项目模版已下架',
        message: '模版已下架，请重新选择其他项目模版',
        confirmMsg: '取消',
        hideMsg: '重新选择'
      },
    }
  },
  components: {
    dialogComponet:dialog
  },
  created() {
    vm = this;
    if (vm.editor) {
      // 编辑时
      vm.disabled = false;
      vm.getEditorMessage()
    } else{
      // 创建时
      vm.disabled = true;
      vm.getMessage();
    }
  },
  methods: {
    // 设置已有的基本信息
    setBaseMessage(data) {
      vm.formData = Object.assign(vm.formData, data.projectData);
      vm.formData.attachmentUrl1 = data.attachmentData[0].attachmentUrl;
      vm.formData.attachmentMore1 = Object.assign(vm.formData.attachmentMore1, data.attachmentData[0]);
             // 暂存为1   下一步为3
      vm.formData.projectType = vm.formData.projectType == 0 ? 3 : vm.formData.projectType;
      vm.formData.projectBegintime = vm.formData.projectBegintime ? new Date(vm.formData.projectBegintime) : '';
      vm.formData.projectEndtime = vm.formData.projectBegintime ? new Date(vm.formData.projectEndtime) : '';
      if (data.attachmentData[1]) {
        // vm.formData.attachmentUrl2 = data.attachmentData[1].attachmentType == 1 ? data.attachmentData[1].attachmentUrl : '';
        // vm.formData.attachmentUrl3 =  data.attachmentData[1].attachmentType == 2 ? data.attachmentData[1].attachmentUrl : '';
         vm.formData.attachmentUrl2 = data.attachmentData[1].attachmentUrl;
        vm.formData.type = data.attachmentData[1].attachmentType;
        vm.formData.attachmentMore2 = Object.assign(vm.formData.attachmentMore2, data.attachmentData[1]);
      }
    },
    // 获取选择模板后的基本信息
    getMessage() {
      openLoading(vm);
      vm.GET(`portal/openTemplateProject/getOpenTemplateInfoForCreate/${vm.openTemplateId}`)
        .then(res => {
          closeLoading(vm);
          if (res.code == "000000") {
            vm.setBaseMessage(res.data);
          } else {
            vm.$message.info(res.message);
          }
        })
        .catch((err) => {
          closeLoading(vm);
          vm.$message.warning('请稍后重试');
        });
    },
    // 获取编辑时的信息
    getEditorMessage() {
      openLoading(vm);
      vm.GET(`portal/portalInfo/getProjectInfo/${vm.projectId}`)
        .then(res => {
          closeLoading(vm);
          if (res.code == "000000") {
            vm.setBaseMessage(res.data)
          } else {
            vm.$message.info(res.message);
          }
        })
        .catch((err) => {
          closeLoading(vm);
          vm.$message.warning('请稍后重试');
        });
    },
    // 增加发起机构
    plusOrg(index) {
      vm.formData.organizationNameList.splice(index + 1, 0, '');
    },
    // 删除发起机构
    deleteOrg(index) {
      vm.formData.organizationNameList.splice(index, 1);
    },
    // 机构名称输入
    changeOrganizationName() {
      let textLength = vm.formData.organizationName.length;
      // 机构输入提示显示与否
      vm.visibleName = textLength == 0;
    },
    // 离开机构名称焦点
    blurName() {
      vm.visibleName = false;
      setTimeout(() => {
        vm.submitForm("formData");
      }, 200);
    },
    // 机构名称聚焦
    focusName(index) {
      let textLength = vm.formData.organizationNameList[index].length;
      if (textLength == 0) {
        vm.orgListIndex = index + 1;
        vm.visibleName = true;
      } else {
        vm.visibleName = false;
      }
    },
    // 机构选择默认值
    checkDefault() {
      vm.organizationContent = vm.formData.creatorOrganizationName;
      vm.formData.organizationNameList.splice(vm.orgListIndex-1, 1, vm.organizationContent);
      vm.visibleName = false;
    },
     //上传列表图片
    beforeUploadListPic(file) {
      let fileLimit = {
        width: 230,
        height: 172,
        size: 0.5,
        sizeText: "500K",
        key: "attachmentUrl1",
        more: "attachmentMore1",
        show: "uploadImgMessage"
      };
      vm.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) {
        vm.$message.error("图片不符合规范，请根据规范上传图片");
        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 _vm = this;
          if (
            _vm.width != fileLimit.width ||
            _vm.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);
              if (fileLimit.show == "uploadImgMessage") {
                vm.uploadImgMessage = false;
              } else if (fileLimit.show == "uploadImgMessage2") {
                vm.uploadImgMessage2 = false;
              }
              vm.formData[fileLimit.key] = path.fullPath;
              vm.formData[fileLimit.more] = {
                attachmentName: path.name,
                attachmentExt: path.ext,
                attachmentSize: path.size
              };
              vm.$message.success("上传成功");
            });
          }
        };
      };
      return isJPG && isLt2M;
    },
    //  删除图片
    deleteImg(type) {
      if (type == 1) {
        vm.formData.attachmentUrl1 = "";
        vm.imgMouseOver = false;
      } else {
        vm.formData.attachmentUrl2 = "";
        vm.imgMouseOver2 = false;
      }
    },
     //改变封面类型
    changeCover(radio) {
      vm.formData.attachmentUrl2 = "";
    },
     //上传封面图片
    beforeUploadCoverPic(file) {
      let fileLimit = {
        width: 750,
        height: 420,
        size: 2,
        sizeText: "2.0M",
        key: "attachmentUrl2",
        more: "attachmentMore2",
        show: "uploadImgMessage2"
      };
      if (vm.formData.type == 1) {
        vm.beforeAvatarUpload(file, fileLimit);
      } else {
        vm.beforeUploadMp4(file);
      }
    },
     //上传mp4
    beforeUploadMp4(file) {
      console.log(file);
      const isMP4 = file.type === "video/mp4";
      const isLt = file.size / 1024 / 1024 < 500;
      if (!isLt) {
        vm.$message.error("视频不符合规范，请根据规范上传视频");
        return;
      }
      if (!isMP4) {
        vm.$message.error("视频不符合规范，请根据规范上传视频");
      } else {
        openLoading(vm);
        doUpload(
          vm,
          file,
          getFilePath(file, null),
          "preview4",
          "progress1",
          ""
        ).then(function(path) {
          closeLoading(vm);
          console.log(path);
          vm.uploadImgMessage2 = false;
          vm.formData.attachmentUrl2 = path.fullPath;
          vm.$message.success("上传成功");
        });
      }
    },
    // 点击下一步
    nextStep() {
      let flag = true;
      if (!vm.formData.attachmentUrl1) {
          vm.uploadImgMessage = true;
          flag = false;
      } else {
        vm.uploadImgMessage = false;
      }
      if (!vm.formData.attachmentUrl2) {
        vm.uploadImgMessage2 = true;
        flag = false;
      } else {
        vm.uploadImgMessage2 = false;
      }
      if (vm.submitForm('formData') && flag) {
        vm.insertOrupdate(3);
      }
    },
    // 暂存
    save() {
      if (vm.$refs['formData'].projectName == '') {
        vm.$refs['formData'].validateField('projectName')
      } else {
        vm.insertOrupdate(1);
      };
    },
    // 新增或者更新基本信息
    insertOrupdate(status) {
      // 暂存为1   下一步为3
      vm.formData.projectStatus = status;
      // 图片或者视频地址
      vm.formData.attachmentMore1.attachmentUrl = vm.formData.attachmentUrl1;
      vm.formData.attachmentMore2.attachmentUrl = vm.formData.attachmentUrl2;
      // 封面类型
      vm.formData.attachmentMore2.attachmentType =  vm.formData.type;
      vm.formData.attachmentMore2.kind =  2;
      //整合图片视频
      vm.attachmentModel[0] = Object.assign(vm.attachmentModel[0],vm.formData.attachmentMore1);
      vm.attachmentModel[1] = Object.assign(vm.attachmentModel[1],vm.formData.attachmentMore2);
      let baseobj = {};
      baseobj.projectModel =  JSON.stringify(vm.formData);
      baseobj.attachmentModel = JSON.stringify(vm.attachmentModel);
      baseobj.attachmentPDFModel= null;
      baseobj.notifyData= null;
      openLoading(vm);
      vm.POST("portal/portalInfo/insertOrUpdate", baseobj).then(res => {
        closeLoading(vm);
        if (res.code == "000000" && status == 3) {
          // 下一步,并将项目id传递
          vm.$emit('next',res.data.id);
        } else if (res.code == "213061") {
           vm.dialogObj.visible = true;
        } else {
          vm.$message.info(res.message);
        }
      });
    }, 
     //表单校验
    submitForm(formName) {
      let flag = null;
      vm.$refs[formName].validate(valid => {
        if (valid) {
          flag = true;
        } else {
          flag = false;
        }
      });
      return flag;
    },
    // 取消
    confirm() {
      vm.dialogObj.visible = false;
    },
    // 确定
    hide() {
      vm.dialogObj.visible = false;
      vm.$emit('backSelectVue')
    }
  }
}
</script>
<style >
  .subject-slelct .el-input__inner {
    height: 32px;
    line-height: 32px;
  }
</style>
<style lang="scss" scoped>

  .base-message-wrap {
    padding-top: 80px;
    .p_label {
      margin-left: 56px;
      font-size: 12px;
      color: #606266;
    }
    .edit-img {
      width: 20px;
      height: 20px;
      vertical-align: middle;
      margin-left: 10px;
    }
    .day-btn {
      display: inline-block;
      width: 50px;
      height: 32px;
      line-height: 32px;
      background: #838683;
      text-align: center;
      margin-left: -3px;
      border-radius: 0 4px 4px 0;
      z-index: 100;
    }
    .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: 84px;
        height: 100px;
      }
      .bg-video {
        float: left;
        width: 84px;
        height: 100px;
      }
      .limit-text {
        float: left;
        margin-left: 10px;
        margin-top: -10px;
        p {
          font-size: 12px;
          color: #999;
        }
      }
    }
    .el-upload__tip {
      position: absolute;
      top: -6px;
      left: 130px;
    }
    .choose-button {
      background: #fff;
      color: #409eff;
      border: 1px solid #409eff;
    }
    .el-popover--plain {
      padding: 18px 20px;
      top: 40px;
    }
    .ueitem {
      position: relative;
    }
   .ue-warp {
      position: absolute;
      width: 80%;
      height: 100%;
      background: #F5F7FA;
      opacity: 0.5;
      top: 0;
      z-index: 1000;
   }
  }
  .el-form-item__content {
    width: 100%;
    height: 100%;
    background: red;
  }
   .popover-content {
      position: relative;
      top: 0;
      left: 0;
    }
  .time-message {
    margin: -6px 0 20px 150px;
    font-size: 14px;
  }
</style>
