<!--基础信息-->
<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%;"
          ></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"> 我的机构： {{ organizationContent }} </p>
        </el-popover>
      </el-form-item>

      <el-form-item label="有效期：" prop="useTime" v-if="!projectManger">
        <el-col :span="13">
          <el-input
            size="small"
            v-model="formData.useTime"
            placeholder="请填写1-1000之间的数字"
            style="width:70%;"
            oninput = "value=value.replace(/[^\d]|^[0]/g,'')"
          ></el-input>
          <span class="day-btn">天</span>
        </el-col>
      </el-form-item>

       <el-form-item label="项目时间：" required v-if="projectManger">
            <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%;"
                ></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>

      <el-form-item label="所属学科" prop="xueke">
        <el-col :span="13">
          <el-cascader
            class="subject-slelct"
            v-model="formData.xueke"
            :options="options"
            :props="{ checkStrictly: true }"
            @change="handleChange"></el-cascader>
        </el-col>
      </el-form-item>

      <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"
          >
            <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" @click.stop="deleteImg(1)" @mouseout.stop="imgMouseOver=false"><i class="el-icon-delete"></i></div>
            <div class="limit-text">
              <p>尺寸:48*48</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"
        >
          <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"
          >
            <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" @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-item label="项目详情" required prop="richContent" v-if="!projectManger">
        <vue-ueditor-wrap
          ref="ueditor"
          v-model="formData.richContent"
          :destroy="false"
          :config="ueditorConfig"
        >
        </vue-ueditor-wrap>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { doUpload, getFilePath } from "../../../utils/qiniu-util";
import { openLoading, closeLoading } from "../../../utils/utils";
import {getCmsUrl} from '../../../utils'
import VueUeditorWrap from 'vue-ueditor-wrap'
let vm = null;
export default {
  props: {
    formData: {
      type: Object,
      default:() => {
        return null
      }
    },
    projectManger: {
      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: 'hcd',//机构名称
      options: [{
        value: 'zhinan',
        label: '指南',
        children: [{
          value: 'shejiyuanze',
          label: '设计原则',
          children: [{
            value: 'yizhi',
            label: '一致'
          }, {
            value: 'fankui',
            label: '反馈'
          }, {
            value: 'xiaolv',
            label: '效率'
          }, {
            value: 'kekong',
            label: '可控'
          }]
        }]
      }],
      pickerOptions0: {
        disabledDate: time => {
          if (
            this.formData.projectEndtime != "" &&
            this.formData.projectEndtime != null
          ) {
            return (
              time.getTime() > new Date(this.formData.projectEndtime).getTime()
            );
          }
        }
      },
      pickerOptions1: {
        disabledDate: time => {
          return (
            time.getTime() < new Date(this.formData.projectBegintime).getTime()
          ); //减去一天的时间代表可以选择同一天;
        }
      },
      imgMouseOver: false,
      imgMouseOver2: false,
      uploadImgMessage: false,
      uploadImgMessage2: false,
      id: 1,
      richContent: '',
      ueditorConfig: {
        // 编辑器不自动被内容撑高
        autoFloatEnabled: false,
        // 初始容器高度
        initialFrameHeight: 400,
        elementPathEnabled : false,
        // 初始容器宽度
        initialFrameWidth: '80%',
        // 上传文件接口
        // serverUrl: 'http://35.201.165.105:8000/controller.php',
        serverUrl: getCmsUrl('api/PICAuEditorServiceImpl/initQuery'),
        // 是否自动抓取远程图片的地址(默认为true)
        catchRemoteImageEnable: false,
        // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
        UEDITOR_HOME_URL: window.location.host.indexOf("localhost") > -1 || window.location.host.indexOf("127.0.0.1") > -1 ? '/static/UEditor/':'/static/UEditor/',
        toolbars: [[ //insertvideo 表示视频，已经去掉
            'fullscreen', 'source', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
             'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
            'simpleupload', 'insertimage', 'link', 'emotion', 'insertcode', 'pagebreak', 'template', 'background', '|',
            'horizontal', 'date', 'time', 'spechars', 'wordimage', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
            'print', 'searchreplace', 'drafts', 'help'
        ]]
        // 配合最新编译的资源文件，你可以实现添加自定义Request Headers,详情https://github.com/HaoChuan9421/ueditor/commits/dev-1.4.3.3
        // headers: {
        //   access_token: '37e7c9e3fda54cca94b8c88a4b5ddbf3'
        // }
      },
      rules: {
        projectName: [
          { required: true, message: "请输入项目名称" },
          {
            min: 2,
            max: 24,
            message: "输入长度为2-24的内容，可包含中英文、数字及特殊符号",
            trigger: "blur"
          },
          { validator: checkProjectStr, trigger: "blur" }
        ],
        useTime: [
          { required: true, message: "请输入有效期", trigger: "blur" },
          { validator: checkUserTime, trigger: "blur" }
        ],
        projectBegintime: [
          {
            required: true,
            message: "请选择时间",
            trigger: "change"
          }
        ],
        projectEndtime: [
          {
            required: true,
            message: "请选择时间",
            trigger: "change"
          }
        ],
        xueke: { required: true, message: "请选择学科", trigger: "change" },
        projectIntro: [
          { required: true, message: "请填写项目简介", trigger: "blur" },
          { min: 1, max: 200, message: "超出可输入的最大长度", trigger: "blur" }
        ],
        richContent: [
          { required: true, message: '请填写项目详情', trigger: 'blur' }
        ]
      }
    }
  },
  components:{
    VueUeditorWrap
  },
  created() {
    vm = this;
  },
  methods: {
    // 增加发起机构
    plusOrg(index) {
      this.formData.organizationNameList.splice(index + 1, 0, '');
    },
    // 删除发起机构
    deleteOrg(index) {
      this.formData.organizationNameList.splice(index, 1);
    },
    // 机构名称输入
    changeOrganizationName() {
      let textLength = this.formData.organizationName.length;
      // 机构输入提示显示与否
      this.visibleName = textLength == 0;
    },
    // 离开机构名称焦点
    blurName() {
      this.visibleName = false;
      setTimeout(() => {
        this.submitForm("formData");
      }, 200);
    },
    // 机构名称聚焦
    focusName(index) {
      let textLength = this.formData.organizationNameList[index].length;
      if (textLength == 0) {
        this.orgListIndex = index + 1;
        this.visibleName = true;
      } else {
        this.visibleName = false;
      }
    },
    // 机构选择默认值
    checkDefault() {
      this.formData.organizationNameList.splice(this.orgListIndex-1, 1, this.organizationContent);
      this.visibleName = false;
    },
    handleChange() {},
     //上传列表图片
    beforeUploadListPic(file) {
      let fileLimit = {
        size: 0.5,
        sizeText: "500K",
        key: "attachmentUrl1",
        more: "attachmentMore1",
        show: "uploadImgMessage"
      };
      this.beforeAvatarUpload(file, fileLimit);
    },
     //上传图片校验
    beforeAvatarUpload(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;
      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 ( false
            // _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);
              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) {
        this.formData.attachmentUrl1 = "";
        this.imgMouseOver = false;
      } else {
        this.formData.attachmentUrl2 = "";
        this.imgMouseOver2 = false;
      }
    },
     //改变封面类型
    changeCover(radio) {
      this.formData.attachmentUrl2 = "";
    },
     //上传封面图片
    beforeUploadCoverPic(file) {
      let fileLimit = {
        // width: 750,
        // height: 420,
        size: 2,
        sizeText: "2.0M",
        key: "attachmentUrl2",
        more: "attachmentMore2",
        show: "uploadImgMessage2"
      };
      if (this.formData.type == 1) {
        this.beforeAvatarUpload(file, fileLimit);
      } else {
        this.beforeUploadMp4(file);
      }
    },
     //上传mp4
    beforeUploadMp4(file) {
      console.log(file);
      let vm = this;
      const isMP4 = file.type === "video/mp4";
      const isLt = file.size / 1024 / 1024 < 500;
      if (!isLt) {
        this.$message.error("视频不符合规范，请根据规范上传视频");
        return;
      }
      if (!isMP4) {
        this.$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 (!this.formData.attachmentUrl1) {
          this.uploadImgMessage = true;
          flag = false;
      } else {
        this.uploadImgMessage = false;
      }
      if (!this.formData.attachmentUrl2) {
        this.uploadImgMessage2 = true;
        flag = false;
      } else {
        this.uploadImgMessage2 = false;
      }
      return this.submitForm('formData') && flag;
      // console.log('====================================');
      // console.log(this.formData);
      // console.log('====================================');
    },
     //表单校验
    submitForm(formName) {
      let flag = null;
      this.$refs[formName].validate(valid => {
        if (valid) {
          flag = true;
        } else {
          flag = false;
        }
      });
      return flag;
    },
    // 保存富文本数据
    setEditorMsge(msg) {
      if (!msg) {
        vm.$message.error('请将富文本填写完整!');
        return;
      }
      vm.editData.richContent = msg;
      openLoading(vm);
      let req = {
        richContent: vm.editData.richContent,
        id: vm.id
      };
      vm.$axios
        .post(
          localStorage.getItem("msUrl") + "v2/qualityContent/updateRichContent",
          req
        )
        .then(function(res) {
          closeLoading(vm);
          if (res.data.code == '000000') {
            vm.$message.success('保存富文本成功');
          } else {
            vm.$message.error(res.data.message);
          }
        })
        .catch(function(error) {
          closeLoading(vm);
          vm.$message.error(error);
        });
    },
  }
}
</script>
<style >
  .subject-slelct .el-input__inner {
    height: 32px;
    line-height: 32px;
  }
</style>
<style lang="scss" scoped>

  .base-message-wrap {
    margin-top: 20px;
    .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;
    }
   
  }
   .popover-content {
      position: relative;
      top: 0;
      left: 0;
    }
</style>
