<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-03-16 09:59:39
 * @LastEditors: 无尘
 * @LastEditTime: 2020-08-26 10:05:31
 -->
<template>
  <div class="material-set-wrap ">
    <div class=" border-box">
      <div class="material-top border-box">
        <el-input placeholder="请输入素材名称" maxlength="50" v-model="searchInput" style="width: 394px;" @keyup.native="value => toInput(value, searchInput)" clearable @clear="clearSearch"> <i slot="prefix" class="el-input__icon el-icon-search"></i> </el-input>
      </div>
      <div class="material-body flex">
        <div class="material-left">
          <div class="material-left-add m-t-10 text-center">
            <div class="add-group font-14 color-909399 cursor-pointer line-h-32" @click="addGroup"><span class="el-icon-plus"></span><span class="p-l-5">新建分组</span></div>
          </div>
          <div class="group-body">
            <div :class="['no-group m-t-10 line-h-32 font-14 color-606266 cursor-pointer', currentCategoryId == '-1' ? 'current-group' : '']" @click="selectNoGroup"><span style="color: transparent;" :class="['color-c0c4cc font-12 cursor-pointer p-l-10 el-icon-caret-bottom el-icon-caret-right']"></span>未分组</div>
            <ul class="group-ul padding-lr-12">
              <template v-for="(item, index) in groupData">
                <li class="group-cell" :key="index + 'group'">
                  <div class="cursor-pointer group-cell-div" @click.stop="selectGroup(item)">
                    <span :class="['color-c0c4cc font-12 cursor-pointer', item.children.length ? 'color-c0c4cc' : 'color-transparent', item.expand ? 'el-icon-caret-bottom' : 'el-icon-caret-right']"></span><span :class="['group-name font-14 color-606266 p-l-10', currentCategoryId == item.categoryId ? 'current-group' : '']">{{ item.categoryName }}</span
                    ><el-popover placement="bottom" width="75" trigger="hover" popper-class="group-popover">
                      <ul>
                        <li class="line-h-32 font-14 color-606266" @click.stop="addChildGroup(item)">新增子分组</li>
                        <li class="line-h-32 font-14 color-606266" @click.stop="editGroup(item)">编辑</li>
                        <li v-if="!item.children.length" class="line-h-32 font-14 color-606266" @click.stop="delGroup(item)">删除</li>
                      </ul>
                      <span class="iconfont icongengduo color-afaeae cursor-pointer operate-icon" slot="reference"></span>
                    </el-popover>
                  </div>
                  <ul v-if="item.expand" class="p-l-10">
                    <template v-for="(itemTwo, ind) in item.children">
                      <li class="group-cell" :key="ind + 'group'">
                        <div class="cursor-pointer group-cell-div" @click.stop="selectGroup(itemTwo)">
                          <span :class="['font-12 cursor-pointer', itemTwo.children.length ? 'color-c0c4cc' : 'color-transparent', itemTwo.expand ? 'el-icon-caret-bottom' : 'el-icon-caret-right']"></span><span :class="['group-name font-14 color-606266 p-l-10', currentCategoryId == itemTwo.categoryId ? 'current-group' : '']">{{ itemTwo.categoryName }}</span
                          ><el-popover placement="bottom" width="75" trigger="hover" popper-class="group-popover">
                            <ul>
                              <li class="line-h-32 font-14 color-606266" @click.stop="addChildGroup(itemTwo)">新增子分组</li>
                              <li class="line-h-32 font-14 color-606266" @click.stop="editGroup(itemTwo)">编辑</li>
                              <li v-if="!itemTwo.children.length" class="line-h-32 font-14 color-606266" @click.stop="delGroup(itemTwo)">删除</li>
                            </ul>
                            <span class="iconfont icongengduo color-afaeae cursor-pointer operate-icon" slot="reference"></span>
                          </el-popover>
                        </div>
                        <ul v-if="itemTwo.expand" class="p-l-10">
                          <template v-for="(itemThree, i) in itemTwo.children">
                            <li class="group-cell" :key="i + 'group'">
                              <div class="cursor-pointer group-cell-div" @click.stop="selectGroup(itemThree)">
                                <span :class="['font-12 cursor-pointer color-transparent', itemThree.expand ? 'el-icon-caret-bottom' : 'el-icon-caret-right']"></span><span :class="['group-name font-14 color-606266 p-l-10', currentCategoryId == itemThree.categoryId ? 'current-group' : '']">{{ itemThree.categoryName }}</span
                                ><el-popover placement="bottom" width="75" trigger="hover" popper-class="group-popover">
                                  <ul>
                                    <!-- <li class="line-h-32 font-14 color-606266" @click.stop="addChildGroup(itemThree)">新增子分组</li> -->
                                    <li class="line-h-32 font-14 color-606266" @click.stop="editGroup(itemThree)">编辑</li>
                                    <li class="line-h-32 font-14 color-606266" @click.stop="delGroup(itemThree)">删除</li>
                                  </ul>
                                  <span class="iconfont icongengduo color-afaeae cursor-pointer operate-icon" slot="reference"></span>
                                </el-popover>
                              </div>
                            </li>
                          </template>
                        </ul>
                      </li>
                    </template>
                  </ul>
                </li>
              </template>
            </ul>
          </div>
        </div>
        <div class="material-right">
          <div class="material-table">
            <div class="add-btn-wrap">
              <el-button v-if="activeName == 1" type="primary" @click="addText">新建文本</el-button><el-button v-if="activeName == 2" type="primary" @click="addImage">新建图片</el-button><el-button v-if="activeName == 3" type="primary" @click="addWeb">新建网页</el-button><el-button v-if="activeName == 4" type="primary" @click="addVideo">新建视频</el-button><el-button v-if="activeName == 5" type="primary" @click="addFile">新建文件</el-button
              ><el-select style="vertical-align: top;" class="m-l-10" v-model="multOpt" placeholder="批量操作" @change="changeOpt">
                <el-option label="批量删除" value="1"></el-option>
                <el-option label="批量转移" value="2"></el-option>
              </el-select>
            </div>
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane name="1">
                <span slot="label"><i class="iconfont iconwenzi p-r-5"></i>文本</span>
                <text-table v-loading="loading" :currentPage="currentPage" :pageSize="pageSize" :total="total" :textTableData="tableData" :categoryId="currentCategoryId" @handleSelectionChange="handleSelText" @refreshTable="refreshTable" @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange"></text-table>
              </el-tab-pane>
              <el-tab-pane label="图片" name="2">
                <span slot="label"><i class="iconfont icontupian p-r-5 "></i>图片</span>
                <image-table v-loading="loading" :currentPage="currentPage" :pageSize="pageSize" :total="total" :categoryId="currentCategoryId" :textTableData="tableData" @handleSelectionChange="handleSelText" @refreshTable="refreshTable" @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange"></image-table>
              </el-tab-pane>
              <el-tab-pane label="网页" name="3">
                <span slot="label"><i class="iconfont icondaima p-r-5 "></i>网页</span>
                <web-table v-loading="loading" :currentPage="currentPage" :pageSize="pageSize" :total="total" :categoryId="currentCategoryId" :textTableData="tableData" @handleSelectionChange="handleSelText" @refreshTable="refreshTable" @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange"></web-table>
              </el-tab-pane>
              <el-tab-pane label="视频" name="4">
                <span slot="label"><i class="iconfont iconshipin p-r-5 "></i>视频</span>
                <video-table v-loading="loading" :currentPage="currentPage" :pageSize="pageSize" :total="total" :categoryId="currentCategoryId" :textTableData="tableData" @handleSelectionChange="handleSelText" @refreshTable="refreshTable" @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange"></video-table>
              </el-tab-pane>
              <el-tab-pane label="文件" name="5">
                <span slot="label"><i class="iconfont iconwenjian p-r-5 "></i>文件</span>
                <file-table v-loading="loading" :currentPage="currentPage" :pageSize="pageSize" :total="total" :categoryId="currentCategoryId" :textTableData="tableData" @handleSelectionChange="handleSelText" @refreshTable="refreshTable" @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange"></file-table>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
    </div>
    <group-dialog v-if="addShow" :categoryParentId="categoryParentId" :editRow="editGroupRow" @closeGroup="closeGroup" @submitGroup="submitGroup"></group-dialog>
    <text-edit v-if="textShow" :categoryId="currentCategoryId" @closeText="closeText" @submitText="submitText"></text-edit>
    <image-edit v-if="imageShow" :categoryId="currentCategoryId" @closeText="closeText" @submitText="submitText"></image-edit>
    <web-edit v-if="webShow" :categoryId="currentCategoryId" @closeText="closeText" @submitText="submitText"></web-edit>
    <video-edit v-if="videoShow" :categoryId="currentCategoryId" @closeText="closeText" @submitText="submitText"></video-edit>
    <file-edit v-if="fileShow" :categoryId="currentCategoryId" @closeText="closeText" @submitText="submitText"></file-edit>
    <select-group v-if="multTrans" :materialIds="materialIds" @closeGroup="closeGroup" @submitGroup="submitGroup"></select-group>
  </div>
</template>
<script>
import selectGroup from '@/components/set/select-group.vue';
import textEdit from '@/components/set/text-edit.vue';
import imageEdit from '@/components/set/image-edit.vue';
import webEdit from '@/components/set/web-edit.vue';
import videoEdit from '@/components/set/video-edit.vue';
import fileEdit from '@/components/set/file-edit.vue';
import textTable from '@/components/set/text-table.vue';
import imageTable from '@/components/set/image-table.vue';
import webTable from '@/components/set/web-table.vue';
import videoTable from '@/components/set/video-table.vue';
import fileTable from '@/components/set/file-table.vue';
import groupDialog from '@/components/set/group-dialog.vue';
import { getRequest, postRequest } from '@/api/api';
import { _debounce } from '@/common/js/public';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';

export default {
  props: {},
  data() {
    return {
      wxEnterpriseId: localStorage.getItem('userInfos') ? JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId : '',
      searchInput: '',
      currentCategoryId: '-1', // 当前选中的分组
      groupData: [],
      categoryParentId: '',
      addShow: false,
      editGroupRow: {},
      expandArr: [],
      loading: false,
      tableData: [],
      // 分页参数
      currentPage: 1,
      pageSize: 20,
      total: 0,
      activeName: '1',
      // 批量操作
      multOpt: '',
      multData: [],
      // 文本
      textShow: false,
      imageShow: false,
      webShow: false,
      videoShow: false,
      fileShow: false,
      multTrans: false,
      materialIds: []
    };
  },
  methods: {
    /**
     * 批量操作
     */
    changeOpt(e) {
      const that = this;
      if (!that.multData.length) {
        showMsg.showmsg('请先选择素材', 'warning');
        that.multOpt = '';
        return false;
      }
      if (e == 1) {
        that
          .$confirm('确定删除选中的素材?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            that.postMultDel();
          })
          .catch(() => {});
      } else {
        that.materialIds = that.multData.map(ele => ele.materialId).join(',');
        that.multTrans = true;
      }
    },
    postMultDel() {
      const that = this;
      let para = {
        materialIds: that.multData.map(ele => ele.materialId).join(',')
      };
      postRequest('/haoban-manage3-web/material-del', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('删除成功', 'success');
            that.multOpt = '';
            that.refreshTable();
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    handleSelText(arr) {
      const that = this;
      that.multData = arr;
    },
    /**
     * 文本
     */
    addText() {
      const that = this;
      that.textShow = true;
    },
    /**
     * 文本弹窗关闭
     */
    closeText() {
      const that = this;
      that.textShow = false;
      that.imageShow = false;
      that.webShow = false;
      that.videoShow = false;
      that.fileShow = false;
    },
    submitText() {
      const that = this;
      that.textShow = false;
      that.imageShow = false;
      that.webShow = false;
      that.videoShow = false;
      that.fileShow = false;
      that.refreshTable();
    },
    /**
     * 图片
     */
    addImage() {
      const that = this;
      that.imageShow = true;
    },
    /**
     * 网页
     */
    addWeb() {
      const that = this;
      that.webShow = true;
    },
    /**
     * 视频
     */
    addVideo() {
      const that = this;
      that.videoShow = true;
    },
    /**
     * 文件
     */
    addFile() {
      const that = this;
      that.fileShow = true;
    },
    /**
     * 刷新列表
     */
    refreshTable() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },
    /**
     * 切换tab
     */
    handleClick() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },
    /**
     * 选中分组
     *  @param {Object} item
     */
    selectGroup(item) {
      const that = this;
      item.expand = item.expand ? false : true;
      that.currentCategoryId = item.categoryId;
      // 为了保存展开/收起状态，存储数据
      if (item.expand) {
        that.expandArr.push(item.categoryId);
      } else {
        that.expandArr.splice(that.expandArr.indexOf(item.categoryId), 1);
      }
      that.currentPage = 1;
      that.getTableList();
      that.$forceUpdate();
    },
    selectNoGroup() {
      const that = this;
      that.currentCategoryId = '-1';
      that.currentPage = 1;
      that.getTableList();
    },
    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    }, 500),
    /**
     * 搜索标签清空
     */
    clearSearch() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },
    /**
     * 新增分组
     */
    addGroup() {
      const that = this;
      that.addShow = true;
      that.categoryParentId = '';
      that.editGroupRow = {};
    },
    closeGroup() {
      const that = this;
      that.multTrans = false;
      that.addShow = false;
      that.multOpt = '';
    },
    submitGroup() {
      const that = this;
      that.multTrans = false;
      that.addShow = false;
      that.getGroupData();
      that.currentPage = 1;
      that.getTableList();
      that.multOpt = '';
    },
    addChildGroup(item) {
      const that = this;
      that.editGroupRow = {};
      that.categoryParentId = item.categoryId;
      that.addShow = true;
    },
    editGroup(item) {
      const that = this;
      that.addShow = true;
      that.categoryParentId = '';
      that.editGroupRow = item;
    },
    delGroup(item) {
      const that = this;
      that
        .$confirm('是否删除当前选中的分组?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.postDelData(item);
        })
        .catch(() => {});
    },
    /**
     * 获取数据
     *  @param {Object} item
     */
    postDelData(item) {
      const that = this;
      let para = {
        categoryId: item.categoryId
      };
      getRequest('/haoban-manage3-web/category-del', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('删除成功', 'success');
            that.getGroupData();
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 简单数组-->父子数组对象
     *  @param {Array} data
     */
    treeData(data) {
      let tree = data.filter(father => {
        //循环所有项
        let branchArr = data.filter(child => {
          return father.categoryId == child.categoryParentId; //返回每一项的子级数组
        });
        if (branchArr.length > 0) {
          father.children = branchArr; //如果存在子级，则给父级添加一个children属性，并赋值
        } else {
          father.children = [];
        }
        return father.categoryParentId == 0; //返回第一层
      });
      return tree;
    },
    /**
     * 获取数据
     */
    getGroupData() {
      const that = this;
      let para = {
        wxEnterpriseId: that.wxEnterpriseId
      };
      getRequest('/haoban-manage3-web/category-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (!!resData.result && !!resData.result.length) {
              resData.result.forEach(ele => {
                ele.expand = that.expandArr.includes(ele.categoryId) ? true : false;
              });
              that.groupData = that.treeData(resData.result) || [];
            }
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     *  分页---页码变化
     *  @param {Number} val
     */
    handleSizeChange(val) {
      const that = this;
      that.currentPage = 1;
      that.pageSize = val;
      that.getTableList();
    },

    /**
     * 分页---当前页变化
     *  @param {Number} val
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
      that.getTableList();
    },
    /**
     * 获取列表数据
     */
    getTableList(val) {
      const that = this;
      that.loading = true;
      let para = {
        wxEnterpriseId: that.wxEnterpriseId,
        keyword: that.searchInput,
        categoryId: that.currentCategoryId,
        materialType: that.activeName,
        pageNum: that.currentPage,
        pageSize: that.pageSize
      };
      getRequest('/haoban-manage3-web/material-list', para)
        .then(res => {
          let resData = res.data;
          that.loading = false;
          if (resData.errorCode == 1) {
            that.tableData = resData.result.result || [];
            that.total = resData.result.totalCount;
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loading = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {},
  mounted() {
    const that = this;
    that.$emit('showTab', 3);
    document.documentElement.style.backgroundColor = '#f0f2f5';
    that.getGroupData();
    that.getTableList();
  },
  destroyed() {
    document.documentElement.style.backgroundColor = '#fff';
  },
  components: { groupDialog, selectGroup, textTable, imageTable, webTable, videoTable, fileTable, textEdit, imageEdit, webEdit, videoEdit, fileEdit }
};
</script>
<style type="text/less" lang="less" scoped>
.bg-ebecf0 {
  background: #ebecf0;
}
.color-afaeae {
  color: #afaeae;
}
.color-c0c4cc {
  color: #c0c4cc;
}
.color-transparent {
  color: transparent;
}
.condition-tips {
  display: inline-block;
  vertical-align: middle;
  line-height: 32px;
}
.p-l-30 {
  padding-left: 30px;
}
.p-l-40 {
  padding-left: 40px;
}
.p-l-55 {
  padding-left: 55px;
}
.p-l-85 {
  padding-left: 85px;
}
.p-r-5 {
  padding-right: 5px;
}
.m-l-20 {
  margin-left: 20px;
}
.line-50 {
  height: 50px;
  line-height: 50px;
}
.el-alert--info {
  width: 608px;
  font-size: 14px;
  color: #606266;
  background: rgba(240, 245, 255, 1);
  border-radius: 2px;
  border: 1px solid rgba(133, 165, 255, 1);
}
.el-icon-info {
  width: 12px;
  font-size: 12px;
  color: #2f54eb;
}
.line-h-32 {
  line-height: 32px;
}
.material-top {
  padding: 20px;
}
.operate-icon {
  display: none;
  position: absolute;
  right: 0;
  top: 8px;
  height: 16px;
  z-index: 1;
  &::before {
    content: '\E603';
    position: relative;
    top: -7px;
  }
  &:hover {
    background: #f0f5ff;
  }
}
.material-set-wrap {
  min-width: 1200px;
  background: #fff;
}
.material-body {
  position: relative;
  width: 100%;
  border-top: 1px solid #e4e7ed;
  .material-left {
    position: relative;
    width: 194px;
    min-width: 194px;
    max-width: 194px;
    .add-group {
      width: 154px;
      height: 32px;
      margin: 0 auto;
      background: rgba(255, 255, 255, 1);
      border: 1px dashed rgba(192, 196, 204, 1);
      &:hover {
        color: #2f54eb;
        border-color: #2f54eb;
      }
    }
    .group-body {
      padding: 0 12px;
      .group-ul {
        .group-cell {
          position: relative;
          min-height: 32px;
          line-height: 32px;
          .group-name {
            display: inline-block;
            vertical-align: top;
            max-width: 132px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .group-cell-div {
            &:hover {
              .operate-icon {
                display: inline-block;
              }
              .group-name {
                color: #2f54eb;
              }
            }
          }
        }
      }
      .current-group {
        color: #2f54eb;
      }
    }
  }
  .material-right {
    position: relative;
    min-width: calc(100% - 194px);
    min-height: calc(100vh - 158px);
    border-left: 1px solid #e4e7ed;
    .material-table {
      position: relative;
      margin-top: 10px;
      .add-btn-wrap {
        position: absolute;
        right: 20px;
        top: -2px;
        z-index: 2;
      }
    }
  }
}
</style>
