<template>
  <div style="padding:20px">
    <div class="logTop">
      <el-cascader
        style="width:260px;height:32px;margin-bottom:3px"
        placeholder="全部类型/全部事由"
        :options="options"
        filterable
        clearable
        :props="{ checkStrictly: true }"
        ref="CascaderRef"
        @change="filterMethod">
      </el-cascader>
      <el-date-picker style="width: 256px; margin-left:10px;" v-model="dateDefault" type="daterange" range-separator="~" start-placeholder="创建开始日期" end-placeholder="创建结束日期" :default-time="['00:00:00', '23:59:59']" :picker-options="pickerOptions()" value-format="yyyy-MM-dd" @change="handleSearch" :clearable="false"> </el-date-picker>
      <p class="font14 tip-p" v-if="!memberId">展示近一年的日志</p>
    </div>
    <el-table :data="tableData"  style="width: 100%; min-height: 210px;">
      <el-table-column prop="createTime" label="时间" min-width="138px">
        <template slot-scope="scope">
          {{ scope.row.createTime | formatDate('ymd') }} <br /> {{ scope.row.createTime | formatDate('hms') }}
        </template>
      </el-table-column>
      <el-table-column prop="operType" label="日志类型" min-width="166px" :formatter="(row, col, val) => val || '--'" />
      <el-table-column prop="operReason" label="事由" min-width="138px" :formatter="(row, col, val) => val || '--'" />
      <el-table-column prop="operContent" label="日志详情" min-width="301px" show-overflow-tooltip :formatter="(row, col, val) => val || '--'"/>
      <el-table-column prop="operRemark" label="备注" min-width="290px">
        <template slot-scope="{ row }">
          <div v-if="row.operRemark" style="width: 100%" ref="operRemark">
            <el-tooltip placement="top" :disabled="row.hideTip">
              <div style="max-width: 400px" slot="content" v-html="row.operRemark"></div>
              <span style="display:block; max-width: 90%;overflow: hidden; text-overflow:ellipsis;white-space:nowrap;vertical-align:middle" v-html="row.operRemark"></span>
            </el-tooltip>
            <el-button v-if="memberId && (row.operType == '客户合并' && row.referLogId && (row.referLogId != -1 && row.referLogId != ''))" type="text" @click="goLink('/customerLog',row.referLogId)">查看</el-button>
          </div>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="" label="操作" min-width="77px" v-if="memberId">
        <template slot-scope="{ row }">
          <el-button v-if="row.operType == '客户合并' && row.referLogId && (row.referLogId != -1 && row.referLogId != '')" type="text" @click="goLink('/customerLog',row.referLogId)">查看</el-button>
          <p v-else>--</p>
        </template>
      </el-table-column> -->
    </el-table>
    <div class="page mTop20" v-if="totalCount > 0">
      <dm-pagination
        v-if="!memberId"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="logPageParam.currentPage"
        :page-sizes="[20, 40, 60, 80]"
        :page-size="logPageParam.pageSize"
        layout="total, sizes, prev, pager, next"
        :total="totalCount"
      />
      <dm-pagination
        v-else
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="logPageParam.currentPage"
        :page-size="logPageParam.pageSize"
        layout="prev, pager, next"
        :total="totalCount"
      />
    </div>
  </div>
</template>

<script>
import mixin from '../../wechatmembers/cardMixin';
import url from '../../axios/url';
import { doFetch, doFetchGet } from '../../axios/api';
import {formatYMD} from '@/common/filters/custom.js';
export default {
  name: 'customerLog',
  mixins: [mixin],
  props: {
    memberId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      tableLoading: false,
      tableData: [],
      logPageParam: {
        pageSize: 20,
        currentPage: 1,
        operReason: null,
        operType: null,
        beginTime: '',
        endTime: ''
      },
      totalCount: 0,
      options: []
    };
  },
  created() {
    this.setDefalutTime()
    this.getLogPage();
    this.getLogTypeData();
  },
  methods: {
    // 级联搜索
    filterMethod(e) {
      this.$refs.CascaderRef.dropDownVisible = false;
      if(e && e.length > 0) {
        // if(e[0]) {
          this.logPageParam.operType = e[0];
        // }else if (e[1]) {
          this.logPageParam.operReason = e[1]
        // }
      }else {
        this.logPageParam.operType = null;
        this.logPageParam.operReason = null;
      }
      this.logPageParam.currentPage = 1;
      this.getLogPage();
    },
    // 客户日志类型列表
    getLogTypeData() {
      doFetchGet(url.getMemberLogType,{}).then(res=>{
        if(res.data.errorCode == 0) {
          this.options = res.data.result || [];
          console.log(this.options,'999');
        }
      })
    },
    // 客户日志列表
    getLogPage () {
      this.tableLoading = true;
      this.logPageParam.beginTime = this.dateDefault[0];
      this.logPageParam.endTime = this.dateDefault[1];
      doFetch(url.logPage, {
        ...this.logPageParam,
        memberId: this.memberId || this.$route.query.memberId,
      })
        .then(res => {
          this.tableLoading = false;
          if (res.data.errorCode === 0) {
            this.tableData = res.data.result.page.result || [];
            this.tableData = this.tableData.map(el => {
              if (typeof el.operRemark == 'string') { el.operRemark = el.operRemark.replace(/\n/g, ' <br />'); }
              return el;
            });
            this.totalCount = res.data.result.page.totalCount;
            this.$nextTick(() => {
              const maxWidth = this.$refs.operRemark.clientWidth;
              const div = document.createElement('div');
              div.style.position = 'fixed';
              div.style.zIndex = -1;
              div.style.opacity = 0;
              document.body.appendChild(div);
              this.tableData = this.tableData.map(el => {
                div.innerHTML = el.operRemark;
                el.hideTip = div.clientWidth / maxWidth < 0.8;
                return el;
              })
              document.body.removeChild(div);
            })
          } else {
            checkFalse(res.data.message);
            return false;
          }
        })
        .catch(err => {
          this.tableLoading = false;
          checkStatus(err);
        })
        .finally(_ => this.count++);
    },
     handleSizeChange (v) {
      this.logPageParam.pageSize = v;
      this.logPageParam.currentPage = 1;
      this.getLogPage();
    },
    handleCurrentChange (v) {
      this.logPageParam.currentPage = v;
      this.getLogPage();
    },
    handleSearch() {
       if(!this.dateDefault) {
        this.setDefalutTime();
      }
      this.logPageParam.currentPage = 1;
      this.getLogPage();
    },
    goLink (v,referLogId) {
      console.log(this.memberId, 'this.memberId');
      if (v) this.$router.push({ path: v, query: { memberId: referLogId } });
      // if (v) this.$router.push({ path: v, query: { memberId: this.memberId } });
    },
  },
   watch: {
    'dateDefault': {
      handler: function(selectTime) {
        if(!selectTime){
          let start = new Date();
          start.setFullYear(start.getFullYear() - 1);
          start.setDate(start.getDate() + 1);
          start = `${start.getFullYear()}-${start.getMonth() + 1}-${start.getDate()}`;
          let end = new Date();
          end = `${end.getFullYear()}-${end.getMonth() + 1}-${end.getDate()}`;
          selectTime = [formatYMD(new Date(start).getTime()), formatYMD(new Date(end).getTime())]
          this.dateDefault = [formatYMD(new Date(start).getTime()), formatYMD(new Date(end).getTime())]
        }
      },
      immediate: true
    }
  },
};
</script>
<style>
/* .el-cascader-menu {
  min-width: 130px !important;
  width: 130px !important;
} */
.el-tooltip__popper {
  max-width: 400px;
}
</style>
<style lang="scss" scoped>
.logTop {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  margin-right: 10px;
  // line-height: normal;
  vertical-align: middle;
}
.tip-p{
  margin-left: 20px;
    color: #6B6D71;
    // padding-bottom: 16px;
}
  /deep/ .el-table {
    th > .cell:first-child,
  td > .cell:first-child {
    padding-left: 10px;
  }
}
</style>