<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-09-18 15:25:12
 * @LastEditors  : 无尘
 * @LastEditTime : 2019-12-24 10:29:49
 -->

<!--
<chat-log :brandId="brandId"></chat-log>
import chatLog from '@/components/app/chat-log.vue';
components: {
  chatLog
}
-->

<template>
  <div class="app-detail-wrap">
    <div class="chat-log boder-box">
      <common-detail-top :topMenuData="topMenuData" :activeId="activeId"></common-detail-top>
      <div class="new-card-body">
        <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
          <el-form-item label="发送内容标题：" prop="materialTitle">
            <limitInput :disflag="$route.query.materialId ? true : false" :inputWidth="320" :inputValue.sync="formData.materialTitle" :holder="'请输入素材标题'" :getByType="'word'" :maxLength="15"> </limitInput>
          </el-form-item>
          <el-form-item label="发送内容：" prop="materialContent">
            <limitTextarea :disInput="$route.query.materialId ? true : false" :inputWidth="320" :inputValue.sync="formData.materialContent" :holder="'请输入素材内容'" :maxLength="1500"> </limitTextarea>
          </el-form-item>
          <el-form-item label="图片上传：" prop="imgUrlList">
            <mult-upload-image :disabled="$route.query.materialId ? true : false" :originList="originList" :imageList="formData.imgUrlList" @deleteImage="deleteImage" @uploadOnSuccess="uploadOnSuccess" @sortImg="sortImg"> </mult-upload-image>
            <div class="font-12 color-606266">单个图片大小不超过5M，最多支持上传9张</div>
          </el-form-item>
          <el-form-item label="发送范围：" class="input-item is-required" prop="rangeList">
            <div class="form-item-tip fonr-14 color-909399">下面两项可二选一，非全选。可选择行政架构或门店架构</div>
            <div class="flex">
              <div class="flex-column item-cell-select inline-block ">
                <div class="depart-item-wrap">
                  <div style="width:240px" class="el-select el-select--large depart-item-content" @click="showDialogLayer('depart', defaultSelection)">
                    <span class="font-14 color-c0c4cc p-l-10" v-if="!defaultSelection.length">请选择行政架构</span>
                    <div class="el-select__tags">
                      <span>
                        <template v-for="(item, index) in defaultSelection">
                          <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, defaultSelection, 'depart')"></i>
                          </span>
                        </template>
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="flex m-t-20">
              <div class="flex-column item-cell-select inline-block">
                <div class="depart-item-wrap">
                  <div style="width:240px" class="el-select el-select--large depart-item-content" @click="showDialogLayer('store', defaultStoreList)">
                    <span class="font-14 color-c0c4cc p-l-10" v-if="!defaultStoreList.length">请选择门店架构</span>
                    <div class="el-select__tags">
                      <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, 'store')"></i>
                          </span>
                        </template>
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="更多设置：" prop="">
            <div>
              <el-checkbox :disabled="$route.query.materialId ? true : false" v-model="formData.topFlag">置顶</el-checkbox>
              <!-- <el-tooltip class="item" effect="dark" content="最多支持3条公告置顶，次数超出限制时，请在公告列表中设置公告置顶" placement="right">
              <span style="cursor: pointer"><i class="iconfont icon-xinxixianshi font-12 color-909399" style="font-size: 12px;"></i></span>
            </el-tooltip> -->
            </div>
          </el-form-item>
          <el-form-item>
            <el-button @click="toReturn">取消</el-button>
            <el-button type="primary" @click="previewData('ruleForm')">预览</el-button>
            <el-button :disabled="$route.query.materialId ? true : false" type="primary" @click="submitForm('ruleForm')">发布</el-button>
            <el-button :disabled="$route.query.materialId ? true : false" type="primary" @click="submitForm('ruleForm', 'flag')">发布并添加下一个</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <vue-select-employee :appScene="appScene" :defaultSelection="defaultSelection" :onlyPerson="onlyPerson" :treeSet="treeSet" :changed="changed" @handleSelectedList="handleSelectedList"> </vue-select-employee>
    <vue-select-store ref="storeSelector" :currentBrand="activeGroup" :appScene="appScene" :treeSet="storeTreeSet" selectType="group-store" :defaultList="defaultStoreList" @handleSelectedList="handleSelectedList"> </vue-select-store>
    <material-preview ref="materialPreview" :materialPreviewData="materialPreviewData" v-model="previewVisible"></material-preview>
  </div>
</template>
<script>
import commonDetailTop from '@/components/app/common-detail-top.vue';
import vueSelectStore from 'components/common/vueSelectStore';
import vueSelectEmployee from '@/components/common/vueSelectEmployee.vue';
import materialPreview from '@/components/app/material/material-preview.vue';
import limitInput from '@/components/limit-input.vue';
import limitTextarea from '@/components/limit-textarea.vue';
import multUploadImage from '@/components/mult-upload-img.vue';
import { getRequest, postRequest } from '@/api/api';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
export default {
  name: 'chat-log',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  components: {
    commonDetailTop,
    vueSelectStore,
    vueSelectEmployee,
    materialPreview,
    limitInput,
    limitTextarea,
    multUploadImage
  },
  data() {
    const validRange = (rule, value, callback) => {
      if (value == '' || !value.length) {
        return callback(new Error('请选择选择行政架构或门店架构'));
      } else {
        callback();
      }
    };
    const validImg = (rule, value, callback) => {
      if (value == '' || !value.length) {
        return callback(new Error('请上传图片'));
      } else {
        callback();
      }
    };
    return {
      activeBrand: this.brandId, // 商户(品牌) id
      activeGroup: this.activeGroupId, // 商户(品牌) groupId
      activeId: '2',
      topMenuData: [
        {
          id: '1',
          name: '纷享素材',
          path: `/enjoyMaterial?appIcon=${this.$route.query.appIcon}`
        },
        {
          id: '2',
          name: !!this.$route.query.materialId ? '查看素材' : '新建素材'
        }
      ],
      // 条件
      searchInput: '',
      // 行政
      selectType: '',
      treeSet: {
        isSelectPerson: false, // 控制只能选部门(false)
        dialogVisible: false, // 控制显示/隐藏
        isSingle: false, // 是否单选
        openNextBool: true // 展开下级不调用接口
      },
      defaultSelection: [],
      changed: '',
      onlyPerson: false, // 控制只能选人(true)
      // 门店选择
      appScene: 2,
      defaultStoreList: [], //  默认的数据
      storeTreeSet: {
        isSelectPerson: false, // 控制只能选部门(false)
        dialogVisible: false, // 控制显示/隐藏
        isSingle: false // 是否单选
      },

      // 分页参数
      currentPage: 1,
      pageSize: 6,
      total: 0,
      enterpriseId: JSON.parse(localStorage.getItem('userInfo')).enterpriseId,
      userId: JSON.parse(localStorage.getItem('userInfo')).userId,
      formData: {
        materialId: '',
        rangeList: [],
        imgUrlList: [],
        materialTitle: '', // 标题
        materialContent: '', // 发送内容
        topFlag: false // 置顶
      },
      rules: {
        materialTitle: [{ required: true, message: '请请输入素材标题', trigger: 'blur' }],
        materialContent: [{ required: true, message: '请请输入发送内容', trigger: 'blur' }],
        rangeList: [{ validator: validRange, trigger: 'change' }],
        imgUrlList: [{ required: true, validator: validImg, trigger: 'change' }]
      },
      originList: [],
      // 预览
      previewVisible: false,
      materialPreviewData: {}
    };
  },
  methods: {
    /**
     * 上传
     */
    uploadOnSuccess(list, origin) {
      const that = this;
      that.formData.imgUrlList = list;
      that.originList = origin;
      /* eslint-disable */
      console.log('上传list:',list);
    },
    /**
     * 上传图片删除
     */
    deleteImage(index) {
      const that = this;
      that.formData.imgUrlList.splice(index,1);
      that.originList.splice(index,1);
      /* eslint-disable */
      console.log('删除list2:',that.formData.imgUrlList);
    },
    sortImg(list,origin) {
      const that = this;
      that.formData.imgUrlList = list;
      that.originList = origin;
    },
    /**
     * 确认新建
     */
    submitForm(formName, flag) {
      const that = this;
      that.formData.rangeList = [...that.defaultStoreList, ...that.defaultSelection];
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.postSaveCard(flag);
        }
      });
    },
    postSaveCard(flag) {
      const that = this;
      let rangeList = [];
      that.formData.rangeList.forEach(ele => {
        rangeList.push({
          groupId: ele.type == 2 ? ele.groupId : '',
          storeId: ele.type == 3 ? ele.storeId : '',
          storeFlag: ele.isStoreGroup
        });
      });
      let para = {
        enterpriseId: that.enterpriseId,
        imgListStr: JSON.stringify(that.formData.imgUrlList),
        materialContent: that.formData.materialContent,
        materialTitle: that.formData.materialTitle,
        rangeListStr: JSON.stringify(rangeList),
        topFlag: that.formData.topFlag ? 1 : 0,
        relatedType: 2,
        brandId: that.brandId,
        userId: that.userId
      };
      postRequest('/haoban-app-material-web/material-add', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('新建成功', 'success');
            if (!flag) {
              that.$router.push(`/enjoyMaterial?appIcon=${that.$route.query.appIcon}`);
            } else {
              that.formData = {
                materialId: '',
                imgUrlList: [],
                materialTitle: '', // 标题
                materialContent: '', // 发送内容
                topFlag: false // 置顶
              };
              that.defaultStoreList = [];
              that.defaultSelection = [];
            }
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 预览
     */
    previewData(formName) {
      const that = this;
      that.formData.rangeList = [...that.defaultStoreList, ...that.defaultSelection];
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.materialPreviewData = that.formData;
          that.previewVisible = true;
        }
      });
    },
    /**
     * 关闭
     */
    closePre() {
      const that = this;
      that.materialPreviewData = {};
    },
    toReturn() {
      const that = this;
      that
        .$confirm('是否确认返回，返回后当前页面内容将丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.$router.push(`/enjoyMaterial?appIcon=${that.$route.query.appIcon}`);
        })
        .catch(() => {});
    },
    /**
     *  选择 id
     */
    changeId(e, row) {
      const that = this;
      that.formData.imageTextWechatId = '';
      that.formData.imageTextGicId = row.imageTextId;
    },
    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    }, 200),
    // 搜索清除
    clearInput() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },

    // 门店弹窗显示
    showDialogLayer(type, selData) {
      const that = this;
      // 查看不能操作
      if (that.$route.query.materialId) {
        return false;
      }
      that.selectType = type;
      that.changed = type;
      if (type === 'store') {
        that.defaultStoreList = selData;
        that.storeTreeSet = {
          dialogVisible: true,
          isSingle: false,
          isSelectPerson: false,
          openNextBool: true // 展开下级不调用接口
        };
        return;
      }
      that.treeSet = {
        dialogVisible: true,
        isSingle: false,
        isSelectPerson: false,
        openNextBool: true // 展开下级不调用接口
      };
      that.defaultSelection = selData;
    },
    /**
     * 处理已选部门
     */
    handleSelectedList(group) {
      // type:	1:员工,2:部门,3:门店;
      const that = this;
      if (that.selectType === 'store') {
        that.defaultStoreList = group;
      } else {
        that.defaultSelection = group;
      }
    },
    /**
     * 删除选的部门
     */
    delDepart(index, obj, type) {
      const that = this;
      if (that.$route.query.materialId) {
        return false;
      }
      obj.splice(index, 1);
    },

    /**
     * 获取数据
     */
    getData() {
      const that = this;
      let para = {
        materialId: that.$route.query.materialId,
        brandId: that.brandId
      };
      getRequest('/haoban-app-material-web/material-detail', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            let defaultStoreList = []; // 门店架构
            let defaultSelection = []; // 行政架构
            if (resData.result.rangeVOList) {
              resData.result.rangeVOList.forEach(ele => {
                ele.groupId = ele.type == 2 ? ele.id : '';
                ele.storeId = ele.type == 3 ? ele.id : '';
                ele.isStoreGroup = ele.storeFlag;
                if (ele.storeFlag == 1) {
                  // 1门店架构0行政架构
                  defaultStoreList.push(ele);
                } else {
                  defaultSelection.push(ele);
                }
              });
            }
            that.formData = {
              materialId: resData.result.materialId,
              imageTextWechatId: resData.result.imageTextWechatId,
              materialTitle: resData.result.materialTitle,
              materialContent: resData.result.materialContent,
              topFlag: resData.result.topFlag == 1 ? true : false,
              imgUrlList: resData.result.imgList,
              rangeList: resData.result.rangeVOList,
              createTime: resData.result.createTime
            };

            that.defaultStoreList = defaultStoreList || [];
            that.defaultSelection = defaultSelection || [];
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    brandId: function(newData, oldData) {
      const that = this;
      if (!!newData) {
        that.activeBrand = newData;
        !!that.$route.query.materialId ? that.getData() : '';
      }
    },
    activeGroupId: function(newData, oldData) {
      const that = this;
      if (!!newData) {
        that.activeGroup = newData;
      }
    }
  },
  mounted() {
    const that = this;
    that.$emit('showTab', '2');
    if (that.brandId && !!that.$route.query.materialId) {
      that.getData();
    }
  }
};
</script>
<style type="text/less" lang="less" scoped>
.w-240 {
  width: 240px;
}
.w-90 {
  width: 90px;
}
.m-l-40 {
  margin-left: 40px;
}
.depart-item-content {
  width: 213px;
  height: 32px;
  overflow: hidden;
  white-space: nowrap;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  .el-select__tags {
    overflow: hidden;
    white-space: nowrap;
  }
}

.el-form-item.is-error {
  /deep/ .el-input__inner {
    border-color: #dcdfe6;
    &:focus {
      border-color: #dcdfe6;
    }
  }
}
.chat-log {
  width: 100%;
  .w-103 {
    width: 103px;
  }
  .w-369 {
    width: 369px;
  }
  .el-input {
    /deep/ .el-input-group__prepend {
      background-color: #fff;
    }
  }
  .new-card-body {
    padding: 20px;
    .search-tip {
      display: inline-block;
      line-height: 32px;
    }
  }
  .chat-log-content {
    .el-button--primary.is-plain {
      color: #1890ff;
      background: #fff;
      border-color: #1890ff;
      &:hover {
        color: #fff;
        background: #1890ff;
        border-color: #1890ff;
      }
      &.is-disabled.is-plain {
        background-color: #f5f7fa;
        border-color: #dcdfe6;
        color: #c0c4cc;
      }
    }
  }
}
</style>
