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

<!--
<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="imageTextWechatId">
            <div class="search-div">
              <el-input placeholder="请输入图文标题" v-model="searchInput" class="w-264" style="width: 264px;" clearable @keyup.native="value => toInput(value, searchInput)" @clear="clearInput"> <i slot="prefix" class="el-input__icon el-icon-search"></i> </el-input>
            </div>
            <div class="chat-log-content boder-box m-t-20">
              <el-table :data="tableData" style="width: 100%">
                <el-table-column label="" width="50">
                  <template slot-scope="scope">
                    <el-radio :disabled="$route.query.materialId ? true : false" v-model="formData.imageTextWechatId" :label="scope.row.imageTextWechatId" @change="changeId($event, scope.row)">{{ '' }}</el-radio>
                  </template>
                </el-table-column>
                <el-table-column prop="imageUrl" label="图片" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <div class="cell">
                      <img class="img-40" :src="scope.row.imageUrl ? scope.row.imageUrl : defaultImg" alt="" />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="titleName" label="图文标题" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <div class="cell color-1890ff cursor-pointer" @click="showPreviewDetail(scope.row)">{{ scope.row.titleName || '--' }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="作者" show-overflow-tooltip>
                  <template slot-scope="scope">
                    {{ scope.row.authorName || '--' }}
                  </template>
                </el-table-column>
                <el-table-column prop="storeMode" label="使用记录" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <div class="cell color-1890ff cursor-pointer" @click="showRecord(scope.row)">{{ scope.row.useCount || '0' }}</div>
                  </template>
                </el-table-column>
              </el-table>
              <div class="block common-wrap__page text-right m-t-24" v-if="tableData.length != 0">
                <el-pagination background @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" layout=" prev, pager, next" :total="total"> </el-pagination>
              </div>
            </div>
          </el-form-item>
          <!-- <el-form-item label="图文链接：" prop="imageTextUrl">
            <limitInput :disflag="$route.query.materialId ? true : false" :inputWidth="320" :inputValue.sync="formData.imageTextUrl" :holder="'请输入图文链接'" :getByType="'char'" :maxLength="300"> </limitInput>
          </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="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="">
            <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>
    <use-record :materialId="imageTextWechatId" :detailShow="detailShow" @hideDetailDialog="hideDetailDialog"> </use-record>
  </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 useRecord from '@/components/app/material/use-record.vue';
import limitInput from '@/components/limit-input.vue';
import limitTextarea from '@/components/limit-textarea.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,
    useRecord,
    limitInput,
    limitTextarea
  },
  data() {
    const validRange = (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: `/imageText?appIcon=${this.$route.query.appIcon}`
        },
        {
          id: '2',
          name: '选择图文'
        }
      ],
      tableData: [], // 图文列表
      // 条件
      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 // 是否单选
      },
      // eslint-disable-next-line
      defaultImg: require('../../../assets/head_default.jpg'),
      // 分页参数
      currentPage: 1,
      pageSize: 6,
      total: 0,
      enterpriseId: JSON.parse(localStorage.getItem('userInfo')).enterpriseId,
      userId: JSON.parse(localStorage.getItem('userInfo')).userId,
      formData: {
        materialId: '',
        imageTextWechatId: '', // 选择的参数
        imageTextGicId: '', // 选择的参数
        titleName: '', // 预览需要
        imageUrl: '', // 预览需要
        imageTextUrl: '',
        rangeList: [],
        materialTitle: '', // 标题
        materialContent: '', // 发送内容
        topFlag: false // 置顶
      },
      rules: {
        imageTextWechatId: [{ required: true, message: '请选择图文', trigger: 'change' }],
        materialTitle: [{ required: true, message: '请请输入素材标题', trigger: 'blur' }],
        materialContent: [{ required: true, message: '请请输入发送内容', trigger: 'blur' }],
        // imageTextUrl: [{ required: true, message: '请请输入图文链接', trigger: 'blur' }],
        rangeList: [{ validator: validRange, trigger: 'change' }]
      },
      // 预览
      previewVisible: false,
      materialPreviewData: {},
      // 记录
      detailShow: false,
      imageTextWechatId: ''
    };
  },
  methods: {
    /**
     * 使用记录
     */
    showRecord(row) {
      const that = this;
      if (!row.useCount) {
        return false;
      }
      that.detailShow = true;
      that.imageTextWechatId = row.imageTextWechatId;
    },
    hideDetailDialog() {
      const that = this;
      that.detailShow = false;
      that.imageTextWechatId = '';
    },
    /**
     * 预览
     */
    showPreviewDetail(row) {
      window.open(row.mediaUrl);
      /* that.materialPreviewData = {
        materialTitle: row.titleName, // 标题
        materialContent: row.mediaUrl, // 发送内容
        mediaUrl: row.mediaUrl
      };
      that.previewVisible = true; */
    },

    /**
     * 确认新建
     */
    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,
        imageTextWechatId: that.formData.imageTextWechatId,
        imageTextGicId: that.formData.imageTextGicId,
        materialContent: that.formData.materialContent,
        imageTextUrl: that.formData.imageTextUrl,
        materialTitle: that.formData.materialTitle,
        rangeListStr: JSON.stringify(rangeList),
        topFlag: that.formData.topFlag ? 1 : 0,
        relatedType: 1,
        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(`/imageText?appIcon=${that.$route.query.appIcon}`);
            } else {
              that.formData = {
                materialId: '',
                imageTextWechatId: '', // 选择的参数
                imageTextGicId: '', // 选择的参数
                titleName: '', //预览需要
                imageUrl: '', //预览需要
                imageTextUrl: '',
                rangeList: [],
                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.tableData.forEach(ele => {
            if (ele.imageTextWechatId == that.formData.imageTextWechatId) {
              that.formData.imageUrl = ele.imageUrl;
              that.formData.titleName = ele.titleName;
              that.formData.mediaUrl = ele.mediaUrl;
            }
          });
          that.materialPreviewData = that.formData;
          that.previewVisible = true;
        }
      });
    },
    toReturn() {
      const that = this;
      that
        .$confirm('是否确认返回，返回后当前页面内容将丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.$router.push(`/imageText?appIcon=${that.$route.query.appIcon}`);
        })
        .catch(() => {});
    },
    /**
     *  选择 id
     */
    changeId(e, row) {
      const that = this;
      that.formData.imageTextWechatId = e;
      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;
      }
      that.formData.rangeList = [...that.defaultStoreList, ...that.defaultSelection];
    },
    /**
     * 删除选的部门
     */
    delDepart(index, obj, type) {
      const that = this;
      if (that.$route.query.materialId) {
        return false;
      }
      obj.splice(index, 1);
      that.formData.rangeList = [...that.defaultStoreList, ...that.defaultSelection];
    },

    /**
     * 分页---页码变化
     */
    handleSizeChange(val) {
      const that = this;
      that.pageSize = val;
      that.getTableList();
    },

    /**
     * 分页---当前页变化
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
      that.getTableList();
    },

    /**
     * 获取图文数据
     */
    getImageData() {
      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,
              imageTextUrl: resData.result.imageTextUrl,
              titleName: '', // 预览需要
              imageUrl: '', // 预览需要
              materialTitle: resData.result.materialTitle,
              materialContent: resData.result.materialContent,
              topFlag: resData.result.topFlag == 1 ? true : false,
              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
          });
        });
    },

    /**
     * 获取列表数据
     */
    getTableList(val) {
      const that = this;
      let para = {
        title: that.searchInput || '', // 搜索字段
        pageNum: that.currentPage, // 当前页
        pageSize: that.pageSize, // 一页显示个数
        brandId: that.activeBrand
        // taskType: 1 //0不良评价，1话务任务
      };
      getRequest('/haoban-app-material-web/wechat-material-detail', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.tableData = resData.result.list || [];
            that.total = resData.result.total;
            if (that.$route.query.materialId) {
              that.getImageData();
            }
            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.getTableList();
      }
    },
    activeGroupId: function(newData, oldData) {
      const that = this;
      if (!!newData) {
        that.activeGroup = newData;
      }
    }
  },
  mounted() {
    const that = this;
    that.$emit('showTab', '1');
    if (that.brandId) {
      that.getTableList();
    }
  }
};
</script>
<style type="text/less" lang="less" scoped>
.w-240 {
  width: 240px;
}
.w-90 {
  width: 90px;
}
.m-l-40 {
  margin-left: 40px;
}
.img-40 {
  width: 40px;
  height: 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>
