<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-date-picker
        v-model="listQuery.lastTimes" type="datetimerange" range-separator="至"
        start-placeholder="上次消费开始时间" end-placeholder="上次消费结束时间" size="mini"
        class="filter-item" style="line-height: 1;" value-format="yyyy-MM-dd HH:mm:ss"
      />
      <el-date-picker
        v-model="listQuery.dates" type="datetimerange" range-separator="至"
        start-placeholder="成为客户开始时间" end-placeholder="成为客户结束时间" size="mini"
        class="filter-item" style="margin-left: 10px;line-height: 1;" value-format="yyyy-MM-dd HH:mm:ss"
      />
      <el-input
        v-model="listQuery.phone" clearable size="mini" class="filter-item"
        maxlength="11" style="width: 200px;margin-left: 10px;" placeholder="请输入手机号"
      />
      <el-select
        v-model="listQuery.state" clearable size="mini" class="filter-item"
        style="width: 200px;margin-left: 10px;" placeholder="请选择客户标签"
      >
        <el-option v-for="item in tagList" :key="item.labelId" :label="item.labelName" :value="item.labelId" />
      </el-select>
      <el-button
        size="mini" class="filter-item" type="primary" icon="el-icon-search"
        style="margin-left:10px;"
        @click="handleSearch"
      >
        查找
      </el-button>
      <el-button size="mini" type="info" class="filter-item" @click="handleReset">
        重置
      </el-button>
      <br />
      <el-button
        size="mini" type="primary" icon="el-icon-plus"
        @click="$refs.EditModal && $refs.EditModal.handleOpen({ buyerUserId: '' })"
      >
        添加
      </el-button>
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="handleDataExport">
        导出客户
      </el-button>
    </div>

    <!-- 查询结果 -->
    <div v-tableHeight>
      <el-table
        v-loading="listLoading" height="100%" element-loading-text="正在查询中。。。" :data="list"
        v-bind="{ stripe: true, size: 'small', border: true, fit: true, highlightCurrentRow: true }"
      >
        <el-table-column align="center" width="100" label="客户ID" prop="buyerUserId" fixed="left" />
        <el-table-column prop="name" label="客户昵称" width="120" show-overflow-tooltip />
        <el-table-column prop="phone" label="手机号" show-overflow-tooltip />
        <el-table-column prop="frequency" label="消费次数" show-overflow-tooltip />
        <el-table-column prop="total" label="累计消费金额（元）" show-overflow-tooltip />
        <el-table-column prop="lastTime" label="上次消费时间" show-overflow-tooltip />
        <el-table-column prop="time" label="成为客户时间" show-overflow-tooltip />
        <el-table-column align="center" width="150" label="注册IP" prop="registerIp" show-overflow-tooltip />
        <el-table-column align="center" width="150" label="最后登录IP" prop="lastLoginIp" show-overflow-tooltip />
        <el-table-column prop="labelName" label="客户标签" show-overflow-tooltip />
        <el-table-column prop="userGrade" label="客户等级" show-overflow-tooltip />
        <el-table-column align="center" label="操作" width="300" fixed="right" class-name="small-padding fixed-width">
          <template slot-scope="{ row }">
            <el-button type="warning" size="mini" @click="handleDetail(row)">
              详情
            </el-button>
            <el-button type="success" size="mini" @click="$refs.TagAdd && $refs.TagAdd.handleOpen(row)">
              加标签
            </el-button>
            <el-button size="mini" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="mini" @click="$refs.VoucherTransfer && $refs.VoucherTransfer.handleOpen(row)">
              代金券转赠
            </el-button>
            <!-- <el-popconfirm title="确定删除此标签？" @onConfirm="deleteTagFn(scope.row.labelId)">
              <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm> -->
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div>
      <el-pagination
        :current-page="listQuery.page" :page-sizes="[10, 20, 50, 100]" :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total"
        @size-change="(val) => ((listQuery.pageSize = val) && getList())"
        @current-change="(val) => ((listQuery.page = val) && getList())"
      />
    </div>

    <!-- 加标签 -->
    <TagAdd ref="TagAdd" @success="getList() && getTagList()" />
    <!-- 代金券转赠 -->
    <VoucherTransfer ref="VoucherTransfer" @success="getList() && getTagList()" />
    <!-- 新增编辑 -->
    <EditModal ref="EditModal" @success="getList() && getTagList()" />
    <!-- 查看详情 -->
    <DetailModal ref="DetailModal" />
  </div>
</template>

<script>
import TagAdd from './components/TagAdd'
import VoucherTransfer from './components/VoucherTransfer'
import EditModal from './components/EditModal'
import DetailModal from './components/DetailModal'
import { getCustomerList, getLabelData, deleteLabel, userExport } from '@/api/customer'
export default {
  name: 'CustomerList',
  components: {
    TagAdd,
    VoucherTransfer,
    EditModal,
    DetailModal
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        dates: [], // 成为客户时间数组
        lastTimes: [], // 上次消费时间
        phone: '', // 手机号
        page: 1, // 当前页
        pageSize: 20, // 每页数
        labelId: null
      },
      tagList: []
    }
  },
  created() {
    this.getList()
    this.getTagList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      try {
        const res = await getCustomerList(this.listQuery)
        this.list = res.data.list
        this.total = res.data.total
      } finally {
        this.listLoading = false
      }
    },
    async getTagList() {
      const res = await getLabelData()
      this.tagList = res.data
    },
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = { dates: [], lastTimes: [], phone: '', page: 1, pageSize: 10, labelId: null }
      this.getList()
    },
    handleDetail(row) {
      this.$refs.DetailModal && this.$refs.DetailModal.handleOpen(row)
    },
    handleEdit(row) {
      this.$refs.EditModal && this.$refs.EditModal.handleOpen(row)
    },
    deleteTagFn(id) {
      deleteLabel({ labelId: id }).then((res) => {
        if (res.code === '') {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listQuery.page = 1
          this.getList()
        } else {
          this.$message({
            message: res.message,
            type: 'error'
          })
        }
      })
    },
    // 导出用户
    async handleDataExport() {
      this.$message({
        message: '数据导出中，请勿重复操作！',
        type: 'success'
      })
      const res = await userExport(this.listQuery)
      if (!res) {
        return
      }
      const blob = new Blob([ res ], { type: 'application/vnd.ms-excel' })
      const fileName = '用户列表.xls'
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.href = URL.createObjectURL(blob)
        elink.style.display = 'none'
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
	padding: 20px;
	display: flex;
	flex-direction: column;

	.filter-container {
		.filter-item {
			display: inline-block;
			vertical-align: middle;
			margin-bottom: 10px;
		}
	}

	.small-padding {
		.cell {
			padding-left: 5px;
			padding-right: 5px;
		}
	}

	.fixed-width {
		.el-button--mini {
			padding: 7px 10px;
		}
	}
}
</style>
