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

<!--
<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="chat-log-content boder-box">
        <div class="table-condition flex flex-space-between m-b-23">
          <div class="table-condition-left"><el-input placeholder="请输入导购姓名/手机号/code" v-model="conditionObj.searchInput" class="w-369" @keyup.native="value => toInput(value, conditionObj.searchInput)" clearable @clear="clearInput"> </el-input><el-date-picker class="m-l-10 m-r-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><el-button style="vertical-align: middle;" @click="showDialogLayer('store', conditionObj.storeGroup)">门店架构选人</el-button></div>
          <div class="table-condition-right">
            <el-button type="primary" @click="exportExcel"><i class="iconfont icon-icon_yunxiazai p-r-6"></i>导出</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">
              <div class="flex">
                <el-popover placement="top-start" width="400" trigger="hover" @show="showSingleInfo(scope.row.applyId)">
                  <div class="apply-info-detail">
                    <div class="flex">
                      <div class="apply-info-img flex-align-center flex-pack-center bg-82C5FF ">
                        <i v-if="!scope.row.headPic" class="iconfont icon-yewuduanmorentouxian"></i>
                        <img v-else :src="scope.row.headPic" alt="img" />
                      </div>
                      <div class="flex flex-column apply-info-right flex-space-between">
                        <div class="apply-info-name">
                          {{ scope.row.clerkName }}
                          <i :class="[scope.row.sex == 2 ? 'icon-xingbienv color-FF585C' : 'icon-xingbienan color-508CEE', 'iconfont']"></i>
                        </div>
                        <div class="apply-info-code">
                          <span class="w-80">员工代码：</span><span class="w-130">{{ scope.row.code || '--' }}</span>
                        </div>
                        <div class="apply-info-phone">
                          <span class="w-80">手机号：</span><span class="w-130">{{ scope.row.nationcode == '86' ? scope.row.phoneNumber : '+' + scope.row.nationcode + '-' + scope.row.phoneNumber }}</span>
                        </div>
                        <div class="apply-info-job">
                          <span class="w-80">职位：</span><span class="w-130">{{ scope.row.positionName || '--' }}</span>
                        </div>
                        <div class="apply-info-store">
                          <span class="w-80">所属门店：</span><span class="w-130">{{ scope.row.storeName || '--' }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div slot="reference">
                    <div class="flex flex-align-center flex-pack-center bg-82C5FF table-head-pic">
                      <i v-if="!scope.row.clerkImgUrl" class="iconfont icon-yewuduanmorentouxian"></i>
                      <img v-else :src="scope.row.clerkImgUrl" alt="img" />
                    </div>
                  </div>
                </el-popover>
                <div class="flex flex-column apply-info">
                  <span>{{ scope.row.clerkName }}</span>
                  <span class="font-13">{{ scope.row.storeName }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="" label="导购手机号" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.clerkPhoneNumber || '--' }}</template>
          </el-table-column>
          <el-table-column prop="" label="会员信息" show-overflow-tooltip>
            <template slot-scope="scope">
              <div class="flex">
                <div class="flex flex-align-center flex-pack-center bg-82C5FF table-head-pic">
                  <i v-if="!scope.row.memberImgUrl" class="iconfont icon-yewuduanmorentouxian"></i>
                  <img v-else :src="scope.row.memberImgUrl" alt="img" />
                </div>
                <div class="flex flex-column apply-info">
                  <span class="text-ellipsis">{{ scope.row.clerkName }}</span>
                  <span class="font-13 text-ellipsis">{{ scope.row.storeName }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="" label="会员手机号" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.memberPhoneNumber || '--' }}</template>
          </el-table-column>
          <el-table-column label="发送时间" show-overflow-tooltip>
            <template slot-scope="scope">
              <div class="color-606266 line-18">{{ scope.row.createTime | timeStampToYmd }}</div>
              <div class="color-606266 line-18">{{ scope.row.createTime | timeStampToHms }}</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 @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>
      <chat-log-list :brandId="brandId" :itemRow="itemRow" :showFlag="showFlag" @hideDetail="hideDetail"></chat-log-list>
      <vue-select-store ref="storeSelector" :currentBrand="activeGroup" :appScene="appScene" :treeSet="storeTreeSet" :selectType="'all'" :defaultList="defaultStoreList" @handleSelectedList="handleSelectedList"> </vue-select-store>
    </div>
  </div>
</template>
<script>
import vueSelectStore from 'components/common/vueSelectStore';
import commonDetailTop from '@/components/app/common-detail-top.vue';
import chatLogList from '@/components/app/chat-log-list.vue';
import { getRequest, postExcel } from '@/api/api';
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,
    chatLogList
  },
  data() {
    return {
      activeBrand: this.brandId, // 商户(品牌) id
      activeGroup: this.activeGroupId, // 商户(品牌) groupId
      activeId: '2',
      topMenuData: [
        {
          id: '1',
          name: '在线沟通设置',
          path: `/onlineChatSet?appIcon=${this.$route.query.appIcon}&activeTab=${this.$route.query.activeTab}`
        },
        {
          id: '2',
          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;
        }
      },
      // 门店选择
      appScene: 2,
      defaultStoreList: [],
      storeTreeSet: {
        isSelectPerson: false, // 控制只能选部门(false)
        dialogVisible: false, // 控制显示/隐藏
        isSingle: false // 是否单选
      },
      // 分页参数
      currentPage: 1,
      pageSize: 20,
      total: 0,
      showFlag: false,
      itemRow: {}
    };
  },
  methods: {
    /**
     * 导出
     */
    exportExcel() {
      let that = this;
      let storeGroups = [];
      let filterStoreIds = [];
      let clerkIds = [];
      that.conditionObj.storeGroup.forEach(ele => {
        if (ele.type == 1) {
          clerkIds.push(ele.employeeClerkId);
        }
        if (ele.type == 2) {
          storeGroups.push(ele.groupId);
        }
        if (ele.type == 3) {
          filterStoreIds.push(ele.storeId);
        }
      });
      if (!that.conditionObj.dateRange) {
        that.conditionObj.dateRange = [];
      }
      let para = {
        relatedId: that.$route.query.relatedId,
        type: that.$route.query.tabType,
        keyWord: that.conditionObj.searchInput || '', // 搜索字段
        groupIds: storeGroups.join(',') || '', // 门店分组, 门店
        storeIds: filterStoreIds.join(',') || '', // 门店分组,分组
        clerkIds: clerkIds.join(',') || '', //
        startTime: that.conditionObj.dateRange[0] || '',
        endTime: that.conditionObj.dateRange[1] || '',
        brandId: that.activeBrand
        // taskType: 1 //0不良评价，1话务任务
      };
      postExcel('//haoban-app-member-web/customer/export_message_log', para)
        .then(res => {
          if (!res.data) {
            errMsg.errorMsg('暂无数据');
            return false;
          }
          // let resData = res.data;
          const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
          const fileName = `${that.tableData[0] ? that.tableData[0].storeName : ''}发送记录报表.csv`;
          const elink = document.createElement('a');
          elink.download = fileName;
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
          // errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 输入
     */
    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();
    },
    /**
     * 弹窗显示事件
     */
    showDialogLayer(type, selData) {
      const that = this;
      that.selectType = type;
      that.changed = type;
      that.defaultStoreList = selData;
      that.storeTreeSet = {
        dialogVisible: true,
        isSingle: false,
        isSelectPerson: false
      };
    },
    /**
     * 处理已选部门
     */
    handleSelectedList(group) {
      const that = this;
      // type:	1:员工,2:部门,3:门店;
      that.conditionObj.storeGroup = group;
      that.getTableList();
    },

    /**
     * 分页---页码变化
     */
    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.showFlag = true;
      let rowObj = JSON.parse(JSON.stringify(row));
      rowObj.userMessageId = '';
      that.itemRow = rowObj;
    },

    hideDetail() {
      const that = this;
      that.showFlag = false;
      that.itemRow = {};
      that.$nextTick(() => {
        document.body.style.overflow = 'auto';
      });
    },

    /**
     * 获取列表数据
     */
    getTableList(val) {
      const that = this;
      let storeGroups = [];
      let filterStoreIds = [];
      let clerkIds = [];
      that.conditionObj.storeGroup.forEach(ele => {
        if (ele.type == 1) {
          clerkIds.push(ele.employeeClerkId);
        }
        if (ele.type == 2) {
          storeGroups.push(ele.groupId);
        }
        if (ele.type == 3) {
          filterStoreIds.push(ele.storeId);
        }
      });
      if (!that.conditionObj.dateRange) {
        that.conditionObj.dateRange = [];
      }
      let para = {
        relatedId: that.$route.query.relatedId,
        type: that.$route.query.tabType,
        search: that.conditionObj.searchInput || '', // 搜索字段
        groupIds: storeGroups.join(',') || '', // 门店分组, 门店
        storeIds: filterStoreIds.join(',') || '', // 门店分组,分组
        clerkIds: clerkIds.join(',') || '', //
        startTime: that.conditionObj.dateRange[0] || '',
        endTime: that.conditionObj.dateRange[1] || '',
        pageNum: that.currentPage, // 当前页
        pageSize: that.pageSize, // 一页显示个数
        brandId: that.activeBrand
        // taskType: 1 //0不良评价，1话务任务
      };
      getRequest('/haoban-app-member-web/cardCoupon/find-send-card-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-369 {
    width: 369px;
  }
  .el-input {
    /deep/ .el-input-group__prepend {
      background-color: #fff;
    }
  }
  .chat-log-content {
    padding: 20px;
    .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>
