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

<!--
<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 border-box">
      <common-detail-top :topMenuData="topMenuData" :activeId="activeId"></common-detail-top>
      <div class="chat-log-content border-box">
        <div class="condition-tip m-b-20">
          <div role="alert" class="el-alert el-alert--info">
            <i class="el-alert__icon el-icon-info font-12 color-1890ff"></i>
            <div class="el-alert__content"><span class="el-alert__title color-606266 font-14">纷享素材内容自定义，包含文字内容及图片编辑</span></div>
          </div>
        </div>
        <div class="table-condition flex flex-space-between m-b-23">
          <div class="table-condition-left">
            <el-input placeholder="请输入标题" v-model="conditionObj.searchInput" class="w-264" @keyup.native="value => toInput(value, conditionObj.searchInput)" clearable @clear="clearInput"> </el-input>
            <el-date-picker class="m-l-10" prefix-icon="el-icon-time" :picker-options="pickerOptions" v-model="conditionObj.dateRange" @change="changeDate" :editable="false" :value-format="'yyyy-MM-dd'" type="daterange" align="right" unlink-panels range-separator="~" start-placeholder="开始时间" end-placeholder="结束时间"> </el-date-picker>
          </div>
          <div class="table-condition-right">
            <el-button type="primary" @click="toCreate">新建素材</el-button>
          </div>
        </div>
        <el-table class="select-table" ref="multipleTable" :data="tableData" tooltip-effect="dark" :style="{ width: '100%', minHeight: tableH }">
          <el-table-column label="标题" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.materialTitle || '--' }}</template>
          </el-table-column>
          <el-table-column prop="" label="图片" min-width="320"
            ><!-- width="470" -->
            <template slot-scope="scope">
              <div class="imgs-set">
                <template v-for="(item, i) in scope.row.imgList">
                  <el-popover :key="i + 'img'" popper-class="notice-img-popover" placement="right" width="400" trigger="hover">
                    <div class="img-preview flex flex-align-center flex-pack-center">
                      <img :src="item.imgUrl" alt="" style="max-width: 400px;" />
                    </div>
                    <img class="table-img" slot="reference" :src="item.imgUrl" alt="" />
                  </el-popover>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="" label="点赞数" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.thumbsUpCount || '--' }}</template>
          </el-table-column>
          <el-table-column prop="" label="转发数" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.tranferCount || '--' }}</template>
          </el-table-column>
          <el-table-column prop="" label="发布时间" show-overflow-tooltip>
            <template slot-scope="scope">
              <div>{{ scope.row.createTime | timeStampToYmd }}</div>
              <div>{{ scope.row.createTime | timeStampToHms }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="219" fixed="right">
            <template slot-scope="scope">
              <el-button @click="toSetTop(scope.row.materialId, scope.row.topFlag)" type="text">{{ scope.row.topFlag == 1 ? '取消置顶' : '置顶' }}</el-button>
              <el-button type="text" size="small" @click="showDetail(scope.$index, scope.row)">查看</el-button>
              <el-button type="text" size="small" @click="showRecord(scope.$index, scope.row)">记录</el-button>
              <el-button type="text" size="small" @click="toDel(scope.$index, scope.row)">删除</el-button>
            </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 @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        </div>
      </div>
    </div>
    <material-record :materialId="materialId" :detailShow="detailShow" @hideDetailDialog="hideDetailDialog"> </material-record>
  </div>
</template>
<script>
import commonDetailTop from '@/components/app/common-detail-top.vue';
import materialRecord from '@/components/app/material/material-record.vue';
import { getRequest, postRequest } from '@/api/api';
import errMsg from '@/common/js/error';
import showMsg from '@/common/js/showmsg';
import { _debounce } from '@/common/js/public';
export default {
  name: 'chat-log',
  props: {
    brandId: {
      type: String,
      default() {
        return '';
      }
    },
    activeGroupId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  components: {
    commonDetailTop,
    materialRecord
  },
  data() {
    return {
      activeBrand: this.brandId, // 商户(品牌) id
      activeGroup: this.activeGroupId, // 商户(品牌) groupId
      activeId: '1',
      topMenuData: [
        {
          id: '1',
          name: '纷享素材'
        }
      ],
      tableData: [],
      // 条件
      conditionObj: {
        searchInput: '',
        searchType: '1',
        storeGroup: [],
        dateRange: []
      },
      choiceDateCopy: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }
        ],
        onPick: ({ maxDate, minDate }) => {
          this.choiceDateCopy = [minDate.getTime()];
          if (maxDate) {
            this.choiceDateCopy = [];
          }
        },
        disabledDate: time => {
          if (this.choiceDateCopy.length) {
            const one = 365 * 24 * 3600 * 1000;
            const minTime = this.choiceDateCopy[0] - one;
            const maxTime = this.choiceDateCopy[0] + one;
            return time.getTime() < minTime || time.getTime() > maxTime || time.getTime() > Date.now() - 8.64e6;
          }
          return time.getTime() > Date.now() - 8.64e6;
        }
      },

      // 分页参数
      currentPage: 1,
      pageSize: 20,
      total: 0,
      detailShow: false,
      materialId: ''
    };
  },
  methods: {
    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    }, 500),
    // 搜索清除
    clearInput() {
      const that = this;
      that.currentPage = 1;
      that.getTableList();
    },
    /**
     *  选择日期
     */
    changeDate(val) {
      const that = this;
      if (!val) {
        that.choiceDateCopy = [];
        that.conditionObj.dateRange = [];
      }
      that.getTableList();
    },
    /**
     * 新建素材
     */
    toCreate() {
      const that = this;
      that.$router.push('/newEnjoy');
    },
    /**
     * 设置置顶
     */
    toSetTop(materialId, topFlag) {
      const that = this;
      that
        .$confirm(topFlag == 0 ? '置顶后，该素材将出现在手机好办营销素材顶部，确认置顶该素材吗' : '确定「取消置顶」该条素材吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.postTop(materialId, topFlag);
        });
    },
    postTop(materialId, topFlag) {
      const that = this;
      let para = {
        materialId: materialId,
        topFlag: topFlag == 0 ? 1 : 0
      };
      getRequest('/haoban-app-material-web/material-to-top', para)
        .then(res => {
          let data = res.data;
          if (data.errorCode == 1) {
            if (topFlag == 0) {
              showMsg.showmsg('置顶成功', 'success');
            } else {
              showMsg.showmsg('取消置顶成功', 'success');
            }
            that.currentPage = 1;
            that.getTableList();
          } else {
            showMsg.showmsg(data.message, 'warning');
          }
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

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

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

    /**
     * 显示详情
     */
    showDetail(index, row) {
      const that = this;
      that.$router.push(`/newEnjoy?materialId=${row.materialId}&appIcon=${that.$route.query.appIcon}`);
    },

    /**
     * 显示记录
     */
    showRecord(index, row) {
      const that = this;
      that.detailShow = true;
      that.materialId = row.materialId;
    },
    /**
     * 关闭记录弹层
     */
    hideDetailDialog() {
      const that = this;
      that.detailShow = false;
      that.materialId = '';
    },
    /**
     * 删除
     */
    toDel(index, item) {
      const that = this;
      that
        .$confirm('是否要删除该素材?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.postDel(item, index);
        })
        .catch(() => {});
    },
    /**
     * 删除
     */
    postDel(item, index) {
      const that = this;
      let para = {
        materialId: item.materialId
      };
      postRequest('/haoban-app-material-web/material-del', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('删除成功', 'success');
            that.getTableList();
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * 获取列表数据
     */
    getTableList(val) {
      const that = this;
      if (!that.conditionObj.dateRange) {
        that.conditionObj.dateRange = [];
      }
      let para = {
        materialTitle: that.conditionObj.searchInput || '', // 搜索字段
        startTimeStr: that.conditionObj.dateRange[0] || '',
        endTimeStr: that.conditionObj.dateRange[1] || '',
        relatedType: 2,
        pageNum: that.currentPage, // 当前页
        pageSize: that.pageSize, // 一页显示个数
        brandId: that.activeBrand
      };
      getRequest('/haoban-app-material-web/material-page', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.tableData = resData.result.list || [];
            that.total = resData.result.total;
            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', '2');
    if (that.brandId) {
      that.getTableList();
    }
  }
};
</script>
<style type="text/less" lang="less" scoped>
.chat-log {
  width: 100%;
  .w-103 {
    width: 103px;
  }
  .w-264 {
    width: 264px;
  }
  .el-input {
    /deep/ .el-input-group__prepend {
      background-color: #fff;
    }
  }
  .imgs-set {
    white-space: nowrap;
  }
  .condition-tip {
    width: 740px;
    .el-alert--info {
      background: #e6f7ff;
      border: 1px solid rgba(145, 213, 255, 1);
      .el-alert__icon {
        font-size: 12px;
      }
    }
  }
  .chat-log-content {
    padding: 20px;
    .table-img {
      width: 40px;
      height: 40px;
      margin-right: 10px;
    }
    .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>
