<template>
  <div class="notice-list-wrap">
    <div class="notice-list">
      <common-detail-top :topMenuData="topMenuData" :activeId="activeId"></common-detail-top>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="发送范围" prop="sendArea" class="input-item">
          <!-- <el-input v-model="ruleForm.sendArea"></el-input> -->
          <div class="flex-column item-cell-select inline-block">
            <div class="depart-item-wrap">
              <div style="width:560px" class="el-select el-select--large depart-item-content" @click="showDialogLayer('store', defaultStoreList)">
                <div class="el-select__tags" style="max-width: 181px;">
                  <span>
                    <template v-for="(item, index) in defaultStoreList">
                      <span class="el-tag el-tag--info el-tag--small" :key="index">
                        <span class="el-select__tags-text">{{ item.name || item.storeName }}</span
                        ><i class="el-tag__close el-icon-close" @click.stop="delDepart(index, defaultStoreList)"></i>
                      </span>
                    </template>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="发送对象" prop="receiveType">
          <el-radio-group v-model="ruleForm.receiveType">
            <el-radio label="0">仅店长</el-radio>
            <el-radio label="1">所有人</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="公告标题" prop="title" class="input-item">
          <limitInput :inputWidth="560" :inputValue.sync="ruleForm.title" :holder="'请输入公告标题'" :maxLength="15"> </limitInput>
        </el-form-item>
        <el-form-item label="封面图片" prop="img">
          <el-upload class="upload-demo" :action="uploadUrl()" :show-file-list="false" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
            <div v-if="ruleForm.img" class="avatar-wrap flex flex-align-center flex-pack-center"><img :src="ruleForm.img" class="avatar" /></div>
            <el-button v-else size="mini" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">建议尺寸700*525，支持 jpg、jpeg、bmp、png 类型文件，3M以内</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="公告内容" prop="content" class="input-item ">
          <limitTextarea :inputWidth="560" :inputValue.sync="ruleForm.content" :holder="'请输入公告内容'" :maxLength="200"> </limitTextarea>
        </el-form-item>
        <el-form-item label="发送方式" prop="sendType">
          <el-radio-group v-model="ruleForm.sendType">
            <el-radio label="0">立即发送</el-radio>
            <el-radio label="1">定时发送</el-radio>
          </el-radio-group>
          <el-date-picker class="my-date-picker" v-model="dateValue" type="datetime" placeholder="选择日期时间"> </el-date-picker>
        </el-form-item>
        <el-form-item>
          <div class="btn-wrap">
            <el-button @click="cancelSend" plain>取消</el-button>
            <el-button @click="sendData('ruleForm')" type="primary">发布</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <!-- 发送范围的门店选择 -->
    <vue-select-store ref="storeSelector" :currentBrand="activeGroup" :appScene="appScene" :treeSet="storeTreeSet" :selectType="'group-store'" :defaultList="defaultStoreList" @handleSelectedList="handleSelectedList"> </vue-select-store>
    <vue-gic-footer></vue-gic-footer>
  </div>
</template>
<script>
import commonDetailTop from '@/components/app/common-detail-top.vue';
import limitInput from '@/components/limit-input.vue';
import vueSelectStore from 'components/common/vueSelectStore';
import limitTextarea from '@/components/limit-textarea.vue';
import { postRequest } from '@/api/api';
export default {
  name: 'addNotice',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    return {
      projectName: 'haoban-manage-web',
      topMenuData: [
        {
          id: '1',
          name: '企业公告列表',
          path: '/noticeList'
        },
        {
          id: '2',
          name: '新建公告',
          path: ''
        }
      ],
      activeId: '2', // 详情头部选中 id
      activeBrand: this.brandId, // 商户(品牌) id
      activeGroup: this.activeGroupId, // 商户(品牌) groupId
      // brandId: '',
      ruleForm: {
        sendArea: '',
        receiveType: '0',
        title: '',
        img: '',
        content: '',
        sendType: '0',
        sendTime: ''
      },
      rules: {
        sendArea: [{ required: true, message: '请输入发送范围', trigger: 'blur' }],
        receiveType: [{ required: true, message: '请选择发送对象', trigger: 'change' }],
        img: [{ required: true, message: '请上传封面图片', trigger: 'blur' }],
        title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }],
        sendType: [{ required: true, message: '请选择发送方式', trigger: 'change' }]
      },
      wxFlag: 1,
      actionUrl: '/haoban-manage-web/upload-img',
      dateValue: '',
      // 门店选择
      appScene: 2,
      defaultStoreList: [], //  默认的数据
      storeTreeSet: {
        isSelectPerson: true, // 控制只能选部门(false)
        dialogVisible: false, // 控制显示/隐藏
        isSingle: false // 是否单选
      }
    };
  },

  methods: {
    // 返回 的 brandId
    selectBrandId(id, groupId) {
      this.brandId = id;
    },
    // 获取 action 的 url
    uploadUrl() {
      let host = window.location.origin;
      let baseUrl;
      if (host.indexOf('localhost') != '-1') {
        baseUrl = 'http://www.gicdev.com';
      } else {
        baseUrl = host;
      }
      let upUrl = baseUrl + this.actionUrl + '?wxFlag=' + this.wxFlag + '&requestProject=' + this.projectName;
      return upUrl;
    },
    // 上传之前回调
    beforeAvatarUpload(file) {
      let that = this;
      const isJPG = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/bmp';
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isJPG) {
        that.$message.error('上传图片必须是JPG/JPEG/BMP/PNG 格式!');
      }
      if (!isLt3M) {
        that.$message.error('上传图片大小不能超过 3MB!');
      }
      const isSize = new Promise(function(resolve, reject) {
        let width = 700;
        let height = 525;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          let valid = img.width >= width && img.height >= height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          this.$message.error('上传图片的尺寸必须是700*525!');
          return Promise.reject();
        }
      );
      return isJPG && isLt3M && isSize;
    },
    /**
     * 上传成功
     */
    handleAvatarSuccess(res, file) {
      let that = this;
      if (res.errorCode == 1) {
        that.$message.success('上传成功');
        that.ruleForm.img = res.result[0].qcloudImageUrl;
      } else {
        this.$message.error(res.message);
      }
    },
    // 取消
    cancelSend() {
      let that = this;
      that
        .$confirm('是否确认返回，返回后当前页面内容将丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.$router.go(-1);
        })
        .catch(() => {});
    },
    // 门店弹窗显示
    showDialogLayer(type, selData) {
      const that = this;
      that.defaultStoreList = selData;
      that.storeTreeSet = {
        dialogVisible: true,
        isSingle: false,
        isSelectPerson: false
      };
    },
    /**
     * 处理已选部门
     */
    handleSelectedList(group) {
      let that = this;
      // type:	1:员工,2:部门,3:门店;
      that.defaultStoreList = group;
      that.ruleForm.sendArea = group;
    },
    /**
     * 删除选的部门
     */
    delDepart(index, item) {
      let that = this;
      item.splice(index, 1);
      that.ruleForm.sendArea = item;
    },
    // 发布
    sendData(formName) {
      let that = this;
      let groupIds = [];
      let storeIds = [];
      that.defaultStoreList.forEach(ele => {
        if (ele.type == 2) {
          groupIds.push(ele.groupId);
        }
        if (ele.type == 3) {
          storeIds.push(ele.storeId);
        }
      });
      that.$refs[formName].validate(valid => {
        if (valid) {
          let para = {
            groupIds: groupIds.join(','),
            storeIds: storeIds.join(','),
            receiveType: that.ruleForm.receiveType,
            title: that.ruleForm.title,
            imgUrl: that.ruleForm.img,
            content: that.ruleForm.content,
            sendType: that.ruleForm.sendType,
            sendTime: that.ruleForm.sendTime,
            brandId: that.brandId,
            userId: '',
            enterpriseId: ''
          };
          postRequest('/haoban-app-announcement-web/announcement-add', para).then(res => {
            let data = res.data;
            if (data.errorCode == 1) {
              that.$message.success('发布成功');
              that.$router.go(-1);
            } else {
              that.$message.error(data.message);
            }
          });
        } else {
          return false;
        }
      });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      if (!!newData) {
        that.activeBrand = newData;
      }
    }
  },
  components: {
    commonDetailTop,
    limitInput,
    limitTextarea,
    vueSelectStore
  }
};
</script>
<style type="text/scss" lang="scss" scoped>
.notice-list-wrap {
  height: 100%;
  .notice-list {
    background: #fff;
    margin-bottom: 34px;
    min-height: 100%;
    // min-height: calc(100% + 24px);
  }
}
.demo-ruleForm {
  padding-top: 30px;
}
.input-item {
  width: 680px;
  position: relative;
}
.input-item-textarea /deep/ textarea {
  height: 94px;
  font-size: 14px;
  color: #606266;
  font-family: 'Helvetica Neue';
}
.el-upload__tip {
  line-height: 20px;
}
.active-info-num {
  position: absolute;
  right: 0;
  bottom: -31px;
  color: #909399;
  font-size: 12px;
}
.my-date-picker {
  margin-left: 15px;
}
.demo-ruleForm /deep/ .el-form-item__label {
  color: #606266;
}
.btn-wrap {
  font-size: 0;
}
// 发送范围
.depart-item-content {
  width: 100%;
  height: 32px;
  overflow: hidden;
  white-space: nowrap;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  box-sizing: border-box;
}

.item-cell-select {
  /deep/ .el-select__tags {
    white-space: nowrap;
    overflow: hidden;
  }
}

.avatar-wrap {
  width: 100px;
  height: 100px;
  max-width: 100px;
  max-height: 100px;
  img {
    max-width: 100px;
    max-height: 100px;
  }
}
</style>
