<template>
  <el-form
    ref="formData"
    :model="formData"
    :rules="rules"
    label-width="150px"
    label-suffix="："
    class="basic-form"
  >
  <el-form-item label="后台标题" prop="titleManager">
    <el-col :span="13">
      <el-input
        size="small"
        v-model="formData.titleManager"
        placeholder="请输入后台显示的活动标题"
        style="width:70%;"
        @change="returnTypeData('titleManager')"
      ></el-input>
      <span class="word-num">{{(formData.titleManager).replace(/\s+/g,"").length}}/30</span>
    </el-col>
  </el-form-item>
  <el-form-item label="前台主标题" prop="titleViewMain">
    <el-col :span="13">
      <el-input
        size="small"
        v-model="formData.titleViewMain"
        placeholder="请输入前台显示的活动主标题"
        style="width:70%;"
        @change="returnTypeData('titleViewMain')"
      ></el-input>
      <span class="word-num">{{(formData.titleViewMain).replace(/\s+/g,"").length}}/30</span>
    </el-col>
  </el-form-item>
    <el-form-item label="前台副标题" prop="titleViewSub">
      <el-col :span="13">
        <el-input
          size="small"
          v-model="formData.titleViewSub"
          placeholder="请输入前台显示的活动副标题"
          style="width:70%;"
          @change="returnTypeData('titleViewSub')"
        ></el-input>
        <span class="word-num">{{(formData.titleViewSub).replace(/\s+/g,"").length}}/30</span>
      </el-col>
    </el-form-item>
    <el-form-item label="关联小圈" prop="circleId"  class="required-label">
      <el-select
        v-model="formData.circleId"
        @change="returnTypeData('circleId')"
        placeholder="请选择小圈"
        size="small">
        <el-option
          v-for="(item,index) in circleList"
          :key="index"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="项目时间：" required>
      <el-col :span="5">
        <el-form-item prop="beginTime">
          <el-date-picker
            v-model="formData.beginTime"
            size="small"
            type="datetime"
            placeholder="请选择开始时间"
            style="width: 100%;"
            :picker-options="pickerOptions0"
          ></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="endTime">
          <el-date-picker
            v-model="formData.endTime"
            size="small"
            type="datetime"
            placeholder="请选择结束时间"
            default-time="23:59:59"
            style="width: 100%;"
            :picker-options="pickerOptions1"
          ></el-date-picker>
        </el-form-item>
      </el-col>
    </el-form-item>
    <el-form-item label="活动链接模块" v-if="formData.appModuleDto.linkType == 4" class="required-label">
      <el-col :span="18">
      <el-select filterable v-model="formData.appModuleDto.name" @change="moduleChange" placeholder="请选择模块" style="width:88%">
        <el-option
          v-for="item2 in moduleArray.nameList"
          :key="item2.id"
          :label="item2.name"
          :value="item2.name">
        </el-option>
      </el-select>
      </el-col>
    </el-form-item>
    <div v-for="(i,j) in formData.appModuleDto.paramList2" :key="j" class="required-label" v-if="formData.appModuleDto.linkType == 4">
      <el-form-item label="选择参数" v-if="formData.appModuleDto.paramFlag == 1">
        <el-col :span="18">
        <el-select v-model="formData.appModuleDto.paramList[j].value" filterable placeholder="请选择参数" style="width:88%">
          <el-option
            v-for="(item3,index3) in i" 
            :key="index3"
            :label="item3.name"
            :value="item3.id + '&'+ item3.name">
          </el-option>
        </el-select>
        </el-col>
      </el-form-item>
    </div>
    <el-form-item label="报名需审核" class="required-label">
      <el-radio-group v-model="formData.auditFlag" @change="" size="small" class="required-label">
        <el-radio :label="1">是</el-radio>
        <el-radio :label="2">否</el-radio>
      </el-radio-group>
    </el-form-item>




    <div class="basic-item-icon">
      <el-form-item label="活动列表页图片" class="required-label">
        <el-upload
          v-model="formData.listImage"
          class="bg-uploader"
          action="#"
          :show-file-list="false"
          :before-upload="beforeUploadPic1"
        >
          <img
            v-if="formData.listImage"
            :src="formData.listImage"
            @mouseover.stop="imgMouseOver1=true"
            class="bg-img"
          />
          <img v-if="!formData.listImage" 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>限制大小: 500kb</p>
            <p>最小尺寸：160*160</p>
            <p>支持jpeg, png格式</p>
          </div>
        </el-upload>
      </el-form-item>
      <p class="upload-message" v-if="uploadImgMessage1">活动列表页图片</p>
    </div>
    <div class="basic-item-icon">
      <el-form-item label="报名页介绍图片" class="required-label">
        <el-upload
          v-model="formData.introImage"
          class="bg-uploader"
          action="#"
          :show-file-list="false"
          :before-upload="beforeUploadPic2"
        >
          <img
            v-if="formData.introImage"
            :src="formData.introImage"
            @mouseover.stop="imgMouseOver2=true"
            class="bg-img"
          />
          <img v-if="!formData.introImage" 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 class="limit-text">
            <p>限制大小: 500kb</p>
            <p>最小尺寸：160*160</p>
            <p>支持jpeg, png格式</p>
          </div>
        </el-upload>
      </el-form-item>
      <p class="upload-message" v-if="uploadImgMessage2">报名介绍页图片</p>
    </div>



  

    <div style="margin-top: 60px;margin-left: 250px;">
      <el-button type="primary" @click="save()" center>保存</el-button>
      <el-button @click="cancle()">取 消</el-button>
    </div>

    <el-dialog
      class="dialog-title-border-old"
      title="图片裁剪"
      :visible.sync="showCropper"
      :width="currentOption.cropDialogWidth"
      center>
      <div slot="title" style="text-align: left;">
        <span style="font-weight: 700;">图片裁剪</span>
      </div>
      <div v-if="showCropper" style="margin-bottom: 20px;">
        <Cropper
          :cropOption="currentOption"
          @getCropImg="getCropImg(arguments)"
          :originImg="slide2.oriUrl"
        />
      </div>
    </el-dialog>
  </el-form>
</template>
<script>
  let vm = null;
  import { openLoading, closeLoading } from "../../utils/utils";
  import { doUpload, getFilePath } from "../../utils/qiniu-util";
  import { getOnlineCircleList } from "../../utils/activitymanagement/activitymanagementApi";
  import {getLinkType,getModuleData,getParamData} from "../../utils/yqrange/yqrangeApi";
  import Cropper from '@/components/common/cropper.vue'
  export default {
    name: "baseinfo",
    components: {
      Cropper
    },
    props: {
      formData: {
        default: () => {
          return {}
        }
      }
    },
    created() {
      vm = this;
      vm.getCircleList();//可以放在自组件优化
  
    },
    data() {
      let checkProjectStr = (rule, value, callback) => {
        if (value.indexOf("\\") != -1) {
          //存在
          callback(new Error("请勿输入字符“ \\ ”"));
        } else if (value.indexOf(".") != -1) {
          callback(new Error("请勿输入字符“ . ”"));
        } else {
          callback();
        }
      };
      return {
        showCropper: false,
        currentOption: {
          offset_x: 120,
          offset_y: 185,
          width: 160,
          height: 120,
          cvWidth: 1000,
          cvHeight: 800,
          uploadType: 1,
          cropDialogWidth: '900px',
          cropBoxResizable: true,
          minCropBoxWidth: 100,
          minCropBoxHeight: 100,
          aspectRatio: 16/9
        },
        slide2: {
          oriUrl: '', // 原图
        },
        rules: {
          titleManager: [
            { required: true, message: "请输入后台显示的活动标题", trigger: "blur" },
            {
              min: 1,
              max: 30,
              message: "输入长度为1-30的内容，可包含中英文、数字及特殊符号",
              trigger: "blur"
            },
            { validator: checkProjectStr, trigger: "blur" }
          ],
          titleViewMain:[
            { required: true, message: "请输入前台显示的活动主标题", trigger: "blur" },
            {
              min: 1,
              max: 30,
              message: "输入长度为1-30的内容，可包含中英文、数字及特殊符号",
              trigger: "blur"
            },
            { validator: checkProjectStr, trigger: "blur" }
          ],
          titleViewSub:[
            { required: true, message: "请输入前台显示的活动副标题", trigger: "blur" },
            {
              min: 1,
              max: 30,
              message: "输入长度为1-30的内容，可包含中英文、数字及特殊符号",
              trigger: "blur"
            },
            { validator: checkProjectStr, trigger: "blur" }
          ],
          beginTime: [
          {
            required: true,
            message: "请选择开始时间",
            trigger: "change"
          }
        ],
        endTime: [
          {
            required: true,
            message: "请选择结束时间",
            trigger: "change"
          }
        ],
          listImage: [
            { required: true, message: "请选择活动列表页图片", trigger: "blur" }
          ],
          type: [
            { required: true, message: "请选择圈子类型", trigger: "blur" },
          ],
          circleId: [
            { required: true, message: "请选择小圈", trigger: "blur" }
          ]
        },
        imgMouseOver1: false,
        imgMouseOver2:false,
        uploadImgMessage2: false,
        uploadImgMessage1: false,//未上传图片，校验提示语
        circleList: [
        ],
        pickerOptions0: {
        disabledDate: time => {
          if (
            this.formData.endTime != "" &&
            this.formData.endTime != null
          ) {
            return (
              time.getTime() > new Date(this.formData.endTime).getTime()
            );
          }
        }
      },
      pickerOptions1: {
        disabledDate: time => {
          return (
            time.getTime() < new Date(this.formData.beginTime).getTime()
          ); //减去一天的时间代表可以选择同一天;
        }
      },
      moduleArray: [],
        shareFlag: false
      }
    },

    methods: {
     
      // 获取模块下拉数据
      getModuleData() {
      
        getModuleData().then(function (res) {
          if(res.code == "000000") {
            vm.moduleArray = JSON.parse(JSON.stringify(res.data));
              for(let j = 0;j < vm.moduleArray.nameList.length; j++) {
                if(vm.formData.appModuleDto.name == vm.moduleArray.nameList[j].name){// 通过name找到对应的id
                  vm.getParamData(vm.moduleArray.nameList[j].id,vm.formData.appModuleDto.paramFlag,j,1)
                }
              }
          }
        }).catch(function (error) {
          vm.$message.error(error);
        });
      },
      // 获取参数下拉数据
      getParamData(id,flag,index,a) {
        if(flag != 1) return; // 判断是否有参数选择
        let req = {
          id: id
        }
        getParamData(req).then(function (res) {
          if(res.code == "000000") {
            vm.paramArray = res.data.paramList;
            vm.paramConfig = res.data.config;
            // for(let i=0;i<vm.tabContent.length;i++) {
            //   if(i == index) {
                vm.formData.appModuleDto.paramFlag = 1
                vm.formData.appModuleDto.paramList2 = vm.paramArray
                if(a == 2) { // 判断是初始化还是改变module调的获取参数接口
                  vm.formData.appModuleDto.paramList = [];
                  for(let j = 0 ;j < vm.paramArray.length; j++) {
                    vm.formData.appModuleDto.paramList.push({
                      id: vm.paramConfig[j].id,
                      seqNo: vm.paramConfig[j].seqNo,  // 选择参数的索引值
                      value: '',
                      key: vm.paramConfig[j].paramKey,
                      type: vm.paramConfig[j].type  // 通过选择参数中获取
                      // status: 2
                    })
                  }
                }else{
                  //for(let k = 0;k < vm.paramConfig.length; k++) {
                  // vm.formData.paramList[k].seqNo = vm.paramConfig[k].seqNo
                  // vm.formData.paramList[k].key = vm.paramConfig[k].paramKey
                  // vm.formData.paramList[k].type = vm.paramConfig[k].type
                  // vm.formData.paramList.push({
                  //     seqNo: vm.paramConfig[k].seqNo,
                  //     key: vm.paramConfig[k].paramKey,
                  //     type: vm.paramConfig[k].type
                  // })
                  let arr = vm.formData.appModuleDto.paramList;
                  vm.formData.appModuleDto.paramList = [];
                  if(arr.length < vm.paramConfig.length) {
                    for(let k = 0;k < arr.length; k++) {
                      vm.formData.appModuleDto.paramList.push({
                        id: vm.paramConfig[k].id,
                        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.formData.appModuleDto.paramList.push({
                        id: vm.paramConfig[j].id,
                        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++) {

                      console.log("id: " + vm.paramConfig[k].id);
                      console.log("value: " + arr[k].value);
                      vm.formData.appModuleDto.paramList.push({
                        id: vm.paramConfig[k].id,
                        seqNo: vm.paramConfig[k].seqNo,
                        key: vm.paramConfig[k].paramKey,
                        type: vm.paramConfig[k].type,
                        value: arr[k].value
                      })
                    }
                  }
                  // }
                }
            //     break
            //   }
            // }
          }
        }).catch(function (error) {
          vm.$message.error(error);
        })

      },
        // change模块选择数据
        moduleChange(value) {
        for(let i = 0; i < vm.moduleArray.nameList.length; i++) {
          if(value == vm.moduleArray.nameList[i].name) {
            vm.getCodeAndType(vm.moduleArray.nameList[i].code,vm.moduleArray.nameList[i].type,vm.moduleArray.nameList[i].paramFlag)
            vm.getParamData(vm.moduleArray.nameList[i].id,vm.moduleArray.nameList[i].paramFlag,vm.moduleIndexValue,2)
          }
        }
      },
      getCodeAndType(code,type,paramFlag) {
        // for(let i = 0; i < vm.tabContent.length; i++) {
        //   if(vm.moduleIndexValue == i) {
            vm.formData.appModuleDto.code = code
            vm.formData.appModuleDto.type = type
            vm.formData.appModuleDto.paramFlag = paramFlag
        //   }
        // }
      },
      returnTypeData(name) {
        this.$emit('returnTypeData', {
          name: name,
          val: this.formData[name]

        })
      },
      checkName(){
        if(vm.formData.appModuleDto.linkType == 4 && vm.formData.appModuleDto.name == ""){
          vm.$message.error("请选择模块！");
          return false;
        }
        else {
          return true;
        }
      },

      checkParamList(){
        if(vm.formData.appModuleDto.linkType == 4
          && vm.formData.appModuleDto.name != ""
          && vm.formData.appModuleDto.paramFlag == 1){

          if(vm.formData.appModuleDto.paramList.length == 0){
            vm.$message.error("请选择参数！");
            return false;
          }
          else {
            for(let i = 0; i < vm.formData.appModuleDto.paramList.length; i++){
              if(vm.formData.appModuleDto.paramList[i].value == ""){
                vm.$message.error("请选择参数！");
                return false;
              }
            }

          }
          return true;

        }
        else {
          return true;
        }
      },
      //表单校验
      submitForm() {
        if(!vm.checkName()){
            return;
          }
          if(!vm.checkParamList()){
            return;
          }
        let formName = "formData";
        let flag = null;
        if (!this.formData.listImage){
          this.uploadImgMessage1 = true;
        }
        if (!this.formData.introImage){
          this.uploadImgMessage2 = true;
        }

        this.$refs[formName].validate(valid => {
          if (valid && vm.formData.listImage!=""&& vm.formData.introImage!="") {
            flag = true;
          } else {
            console.log("error submit!!");
            flag = false;
          }
        });

        
        this.$emit('returnIsNext', flag);
      },
      //上传活动列表页图片
      beforeUploadPic1(file) {
        this.currentOption.aspectRatio = 1/1;
        this.currentOption.cropBoxResizable = true;
        this.currentOption.minCropBoxWidth = 160;
        this.currentOption.minCropBoxHeight = 160;
        let fileLimit = {
          width: 160,
          height: 160,
          size: 0.5,
          sizeText: "500K",
          key: "listImage",
          more: "imgUrl1More",
          show: "uploadImgMessage1"
        };
        this.beforeUpload(file, fileLimit);
      },
       //上传报名页介绍图片
       beforeUploadPic2(file) {
        this.currentOption.aspectRatio = 1/1;
        this.currentOption.cropBoxResizable = true;
        this.currentOption.minCropBoxWidth = 160;
        this.currentOption.minCropBoxHeight = 160;
        let fileLimit = {
          width: 160,
          height: 160,
          size: 0.5,
          sizeText: "500K",
          key: "introImage",
          more: "imgUrl1More",
          show: "uploadImgMessage2"
        };
        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;
        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
          vm.slide2.oriUrl = theFile.target.result;
          image.onload = function () {
            let _this = this;
            // if (_this.width != fileLimit.width || _this.height != fileLimit.height) {
            if (_this.width < fileLimit.width ||  _this.height < fileLimit.height) {
              vm.$message.error("图片必须是jpeg或png格式，同时长宽尺寸和图片大小需符合要求");
              return;
            }
            // else if(_this.width > fileLimit.width ||  _this.height > fileLimit.height){
            //   vm.showCropper = true;
            //   vm.currentOption.cvWidth = _this.width;
            //   vm.currentOption.cvHeight = _this.height;
            //   return;
            // }
            else {
              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.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.listImage = "";
          vm.imgMouseOver1 = false;
        }else if (type ==2) {
          vm.formData.introImage= ""
          vm.imgMouseOver2 = false;
        }
      },
      // 获取裁剪的图片数据
      getCropImg(argument) {
        this.showCropper = false;
        this.cropData = argument[1]
        vm.doUploadQiNiu(argument[2])
        argument[3] && argument[3].destroy();
        // vm.slide2.oriUrl = "";
      },
      // 上传七牛
      doUploadQiNiu(file){

        doUpload(this,file, getFilePath(file,null), 'preview4', 'uploadProgress1', '').then(function (path) {

          vm.formData.listImage = path.fullPath;

          vm.$message.success('上传成功');
        });

      },

      save(){
        this.submitForm();
      },
      cancle(){
        const _this = this;
        setTimeout(function () {
          _this.$router.go(-1)
        }, 100);
      },
      changeType(){

        if(vm.formData.type == 1 || vm.formData.type == 2){
          vm.shareFlag = true;
        }
        else {
          vm.shareFlag = false;
        }

      },

      getCircleList(){
        openLoading(vm);
        getOnlineCircleList().then(res => {
          closeLoading(vm);
          if (res.code == "000000") {
             vm.circleList = res.data
             vm.getModuleData();
          }
        }).catch(err => {
          this.$message.error('请求失败');
        });
      }
    }
  }
</script>

<style lang="less">
.first-step {
  margin-top: 20px;

  .p-title {
    padding-left: 10px;
    margin-bottom: 15px;
  }

  .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 {
    .bg-img {
      float: left;
      width: 84px;
      height: 100px;
    }

    .limit-text {
      float: left;
      margin-left: 10px;
      margin-top: -10px;

      p {
        font-size: 12px;
        color: #999;
        text-align: left;
      }
    }
  }

  .el-upload__tip {
    position: absolute;
    top: -6px;
    left: 130px;
  }
}

.required-label .el-form-item__label::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
.label-type {
  width: 100%;
  margin-top: 10px;
}
</style>
