<template>
    <el-card shadow="never" class="aui-card--fill">
        <div class="mod-home">
          <div class="page-title">{{ pageTitle }}</div>
          <div class="query">
            <div class="query-left">
              <el-form :inline="true" :model="queryParams" @keyup.enter.native="getList">
                <el-form-item label="善行少年编号" style="margin-right: 50px;">
                  <el-input v-model="queryParams.uniqueNo" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="用户名" style="margin-right: 50px;">
                  <el-input v-model="queryParams.realName" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="渠道方">
                  <el-select v-model="queryParams.channelId" placeholder="请选择渠道方" class="select-box">
                      <el-option v-for="item in channelOptions" :key="item.id" :label="item.channelName" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
            <div class="query-right">
              <div class="form-btns">
                <el-button type="primary" @click="getList">查询</el-button>
                <el-button type="default" @click="reset" style="margin-left: 24px;">重置</el-button>
              </div>
            </div>
          </div>
          <div class="table-title adfacjb">
            <div class="table-title-left">会员列表共（{{ total }}）人</div>
            <div class="table-title-right adfac">
              <el-button type="default" @click="handleDownloadTieket" v-if="$hasPermission('core:appuser:downloadTicket')">下载专享券导入模板</el-button>
              <el-upload v-if="$hasPermission('core:appuser:importTicket')"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :on-success="uploadFileSuccess"
                :before-upload="beforeAvatarUpload"
                :limit="1">
                <el-button type="primary" style="margin-left: 10px;">导入专享券</el-button>
              </el-upload>
              <el-button type="default" @click="handleDownloadLove" style="margin-left: 10px;" v-if="$hasPermission('core:appuser:downloadLove')">下载爱心值导入模板</el-button>
              <el-upload v-if="$hasPermission('core:appuser:importLove')"
                :action="uploadUrl2"
                :headers="uploadHeaders"
                :on-success="uploadFileSuccess"
                :before-upload="beforeAvatarUpload"
                :limit="1">
                <el-button type="primary" style="margin-left: 10px;">导入爱心值</el-button>
              </el-upload>
              <el-button type="primary" @click="handleAdd" v-if="$hasPermission('core:appuser:save')" style="margin-left: 10px;">新增会员</el-button>
              <el-button type="default" @click="handleExcel" v-if="$hasPermission('core:appuser:export')">导出Excel</el-button>
            </div>
          </div>
          <el-table :data="dataList" border cell-class-name="vertical-top-cell" v-loading="loading" empty-text="暂无会员" style="margin-top: 22px;">
            <el-table-column prop="xxx" label="序号" width="70">
              <template #default="{ $index }">{{ ($index + 1) + (queryParams.page - 1) * queryParams.limit }}</template>
            </el-table-column>
            <el-table-column prop="xxx" label="会员信息" width="180">
              <template #default="{ row }">
                <div class="userinfo adfac">
                  <img :src="row.avatarPath||require('@/assets/img/default_avatar.png')">
                  <div class="userinfo-text">
                    <div class="userinfo-text-name">{{ row.nickName||'' }}</div>
                    <div class="userinfo-text-phone">{{ row.phoneCopy||'' }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="uniqueNo" label="善行少年编号" width="220"></el-table-column>
            <el-table-column prop="channelName" label="渠道方" width="150"></el-table-column>
            <el-table-column prop="realName" label="用户名"></el-table-column>
            <el-table-column prop="phoneCopy" label="手机号"></el-table-column>
            <!-- <el-table-column prop="welfareName" label="家庭公益名称" width="130"></el-table-column>
            <el-table-column prop="welfareSlogan" label="家庭公益口号" width="130"></el-table-column> -->
            <el-table-column prop="totalConsumeLove" label="累计捐献爱心值" width="140">
              <template #default="{ row }">{{ row.totalConsumeLove||0 }}</template>
            </el-table-column>
            <el-table-column prop="totalImportLove" label="累计导入爱心值" width="140"></el-table-column>
            <el-table-column prop="welfareCount" label="参与公益次数" width="130">
              <template #default="{ row }">{{ row.welfareCount||0 }}次</template>
            </el-table-column>
            <el-table-column prop="userLevel" label="会员等级">
              <template #default="{ row }">Lv.{{ row.userLevel||0 }}</template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                  <el-button link type="text" @click="handleDetail(scope.row)" v-if="$hasPermission('core:appuser:detail')">会员详情</el-button>
                  <!-- <el-button link type="text" @click="handleCreateCode(scope.row)" v-if="$hasPermission('core:appuser:code')">生成邀请码</el-button> -->
                  <el-button link type="text" @click="handleDelete(scope.row)" v-if="$hasPermission('core:appuser:delete')">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="queryParams.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="queryParams.limit"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="pageSizeChangeHandle"
            @current-change="pageCurrentChangeHandle">
          </el-pagination>
        </div>
    </el-card>
</template>

<script>
import Cookies from 'js-cookie'
import qs from 'qs'
export default {
  data () {
    return {
      pageTitle: '',
      queryParams: {
        page: 1,
        limit: 10,
        uniqueNo: '',
        realName: '',
        channelId: ''
      },
      total: 0,
      channelOptions: [],
      dataList: [],
      loading: false,
      uploadUrl: `${window.SITE_CONFIG['apiURL']}/core/activity/coupon/import`,
      uploadUrl2: `${window.SITE_CONFIG['apiURL']}/core/love/value/record/import`,
      uploadHeaders: {
        token: Cookies.get('token')
      }
    }
  },
  created () {
    this.getSupplierOptions()
  },
  mounted () {
    this.pageTitle = this.$router.currentRoute.meta.title
    this.getList()
  },
  methods: {
    getSupplierOptions () {
      this.$http.get('/core/channel/page', { params: { page: 1, limit: -1 } }).then(res => {
        this.channelOptions = res.data.data.list.filter(item => item.type === 1) || []
      })
    },
    getList () {
      this.loading = true
      this.$http.get('/core/app/user/page', { params: this.queryParams }).then(res => {
        this.dataList = res.data.data.list || []
        this.dataList.forEach(item => {
          item.phoneCopy = item.phone && item.phone.replace(/^(\d{3})\d*(\d{4})$/, '$1****$2')
        })

        this.total = res.data.data.total || 0
        this.loading = false
      })
    },
    reset () {
      this.queryParams = {
        page: 1,
        limit: 10,
        uniqueNo: '',
        nickName: '',
        channelId: ''
      }
      this.getList()
    },
    handleDownloadTieket () {
      window.location.href = `${window.SITE_CONFIG['apiURL']}/core/activity/coupon/download?token=${Cookies.get('token')}`
    },
    handleExportTicket () {

    },
    handleDownloadLove () {
      window.location.href = `${window.SITE_CONFIG['apiURL']}/core/love/value/record/download?token=${Cookies.get('token')}`
    },
    handleExportHeart () {

    },
    beforeAvatarUpload (file) {
      const isXls = file.type === 'application/vnd.ms-excel'
      const isXlsx = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isXls && !isXlsx) {
        this.$message.error('上传文件只能是 xls 或 xlsx 格式!')
      }
      return isXls || isXlsx
    },
    uploadFileSuccess (response, file, fileList) {
      if (response && response.code === 0) {
        this.$message.success('导入成功！')
        this.getList()
      } else {
        this.$message.error(response.msg || '文件上传失败！')
      }
    },
    handleAdd () {
      this.$router.push({ name: 'memberAdd' })
    },
    handleExcel () {
      let newDataForm = Object.assign({}, this.queryParams)
      var params = qs.stringify({
        'token': Cookies.get('token'),
        ...newDataForm
      })
      window.location.href = `${window.SITE_CONFIG['apiURL']}/core/app/user/export?${params}`
    },
    handleDetail (row) {
      this.$router.push({ name: 'memberDetail', query: { id: row.id, avatar: row.avatarPath } })
    },
    handleCreateCode (row) {

    },
    handleDelete (row) {
      this.$confirm(`确定要删除会员【${row.nickName}】吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.delete('/core/app/user', { 'data': [row.id] }).then(res => {
          if (res.data.code !== 0) return this.$message.error(res.data.msg)
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    pageSizeChangeHandle (val) {
      this.queryParams.limit = val
      this.getList()
    },
    pageCurrentChangeHandle (val) {
      this.queryParams.page = val
      this.getList()
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-upload-list{
  display: none;
}
.page-title{
    font-family: PingFang-SC, PingFang-SC;
    font-weight: bold;
    font-size: 16px;
    color: #252525;
    line-height: 22px;
}

.query{
  margin-top: 14px;
  display: flex;
  justify-content: space-between;
  &-right{
    .form-btns{
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}

.table-title{
  margin-top: 10px;
  &-left{
    font-family: PingFang-SC, PingFang-SC;
    font-weight: bold;
    font-size: 16px;
    color: #252525;
    line-height: 22px;
    width: 200px;
  }
  &-right{
    width: calc(100% - 200px);
    justify-content: flex-end;
  }
}

.userinfo{
  img{
    width: 36px;
    height: 36px;
    border-radius: 50%;
  }
  &-text{
    margin-left: 5px;
    &-name{
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #252525;
      line-height: 14px;
    }
    &-phone{
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #252525;
      line-height: 14px;
      margin-top: 10px;
    }
  }
}
</style>
