<template>
  <div class="app-container">
    <div class="head-container">
      <el-form :model="query" inline>
        <el-form-item label="搜索">
          <el-input v-model="query.name" placeholder="请输入昵称或手机号"></el-input>
        </el-form-item>
        <el-form-item label="是否为会员">
          <el-select v-model="query.isVip" placeholder="是否是会员">
            <el-option value="" label="全部"></el-option>
            <el-option :value="1" label="是"></el-option>
            <el-option :value="0" label="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getTableData">查询</el-button>
          <el-button @click="resetHandle">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- <div class="head-container">
            <el-button type="primary" icon="el-icon-plus" @click="$refs.addActive.show()">
                添加活动
            </el-button>
        </div> -->
    <div class="head-container">
      <div class="card">
        <!-- <div class="title">统计数据</div> -->
        <div class="row">
          <div class="item">
            <div class="t">会员数</div>
            <div class="n">{{ shopInfo.userTotal || 0 }}</div>
          </div>
          <div class="item">
            <div class="t">会员余额</div>
            <div class="n">{{ shopInfo.balanceTotal || 0 }}</div>
          </div>
          <div class="item">
            <div class="t">充值金额</div>
            <div class="n">{{ shopInfo.chageTotal || 0 }}</div>
          </div>
          <div class="item">
            <el-button type="success" @click="toPage('charge')">充值记录</el-button>
            <!-- <el-button type="danger" @click="toPage('cost')">消费记录</el-button> -->
          </div>
        </div>
      </div>
    </div>
    <div class="head-container">
      <el-table :data="tableData.data" v-loading="tableData.loading">
        <el-table-column label="ID" prop="id"></el-table-column>
        <el-table-column label="用户" prop="headImg" width="200px">
          <template v-slot="scope">
            <div class="user_info">
              <el-image :src="scope.row.headImg" style="width: 40px;height: 40px;flex-shrink: 0;">
                <div slot="error" class="image-slot">
                  <i class="el-icon-user"></i>
                </div>
              </el-image>
              <span class="name">{{ scope.row.nickName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="性别" prop="sex">
          <template v-slot="scope">
            <el-tag type="priamry">{{ scope.row.sex || "未知" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="会员" prop="isVip">
          <template v-slot="scope">
            <el-tag type="warning" v-if="scope.row.isVip">会员等级{{ scope.row.isVip }}</el-tag>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column label="余额" prop="amount">
          <template v-slot="scope">
            <span style="color: #1890ff;cursor: pointer;" @click="moneyevent(scope.row)">
              {{ scope.row.amount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="充值金额" prop="inMoney"></el-table-column>
        <el-table-column label="订单数量" prop="orderNumber">
          <template v-slot="scope">
            <span style="color: #1890ff;cursor: pointer;" @click="orderNumberevent(scope.row)">
              {{ scope.row.orderNumber }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="积分" prop="totalScore"></el-table-column>
        <el-table-column label="手机号" prop="telephone" width="160"></el-table-column>
        <el-table-column label="生日" prop="birthDay" width="200"></el-table-column>
        <el-table-column label="注册时间" prop="createAt" width="200">
          <template v-slot="scope">
            {{ scope.row.createAt | timeFilter }}
          </template>
        </el-table-column>
        <el-table-column label="最近登录时间" prop="lastLoginAt" width="200">
          <template v-slot="scope">
            {{ scope.row.lastLoginAt | timeFilter }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template v-slot="scope">
            <el-button type="text" @click="edituser(scope.row)">编辑</el-button>
            <el-dropdown size="mini" @command="editPop(scope.row)">
              <span class="el-dropdown-link" style="font-size: 12px;margin-left: 10px;"> 更多 </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>增减余额</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="head-container">
      <el-pagination :total="tableData.total" :current-page="tableData.page + 1" :page-size="tableData.size"
        @size-change="sizeChange" @current-change="paginationChange"
        layout="total, sizes, prev, pager, next, jumper"></el-pagination>
    </div>
    <!-- 编辑用户 -->
    <el-dialog title="编辑" :visible.sync="dialogVisibleedit" width="30%">
      <el-form ref="form" :model="userinfos" label-width="80px">
        <el-form-item label="生日">
          <el-date-picker v-model="userinfos.birthDay" type="date" placeholder="选择日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="会员名称">
          <el-input v-model="userinfos.name"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="userinfos.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="状态">
          <el-radio-group v-model="userinfos.status">
            <el-radio label="1">正常</el-radio>
            <el-radio label="0">不可使用</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="联系电话">
          <el-input v-model="userinfos.telephone" @input="checkIfNum"></el-input>
        </el-form-item>


      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleedit = false">取 消</el-button>
        <el-button type="primary" @click="sumbituser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 增减余额弹窗 -->
    <el-dialog title="增减余额" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="userinfo" label-width="80px">
        <el-form-item label="用户">
          {{ userinfo.nickName }}
        </el-form-item>
        <el-form-item label="余额">
          {{ userinfo.amounts }}
        </el-form-item>
        <el-form-item label="增减">
          <el-radio-group v-model="userinfo.operationType">
            <el-radio label="in">增加</el-radio>
            <el-radio label="out">扣除</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金额">
          <el-input v-model="userinfo.amount" @input="amountNum" style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-radio-group v-model="userinfo.type">
            <el-radio label="inMoney" v-show="userinfo.operationType == 'in'">充值</el-radio>
            <el-radio label="consumeIn" v-show="userinfo.operationType == 'in'">消费退款</el-radio>
            <el-radio label="consumeOut" v-show="userinfo.operationType != 'in'">消费</el-radio>
            <el-radio label="inMoneyOut" v-show="userinfo.operationType != 'in'">充值退款</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sumbit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 余额列表 -->
    <el-dialog title="余额明细" :visible.sync="moneyvisible" width="60%">
      <div>
        <el-table :data="moneyList.records" style="width: 100%">
          <el-table-column label="变动金额">
            <template v-slot="scope">
              {{ scope.row.type }} {{ scope.row.amount }}
            </template>
          </el-table-column>
          <el-table-column prop="balance" label="余额">
          </el-table-column>
          <el-table-column prop="biz_name" label="业务名称">
          </el-table-column>
          <el-table-column prop="remark" label="备注">
          </el-table-column>
          <el-table-column prop="create_time" label="时间">
          </el-table-column>
          
        </el-table>
        <div class="head-container">
          <el-pagination :total="moneyList.total" :current-page="pages" @current-change="paginationChanges"
            layout="total,  prev, pager, next, jumper"></el-pagination>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="moneyvisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { queryAllShopUser, queryAllShopInfo, midfiyAccount, tbShopUseredit, queryShopUserFlow } from "@/api/shop";
import dayjs from "dayjs";
import { hasPermission } from '@/utils/limits.js'

let cacheData = {};
export default {
  data() {
    return {
      query: {
        name: "",
        isVip: 1
      },
      shopInfo: {
        balanceTotal: 0,
        userTotal: 0,
        chageTotal: 0
      },
      tableData: {
        data: [],
        page: 0,
        size: 10,
        loading: false,
        total: 0
      },
      dialogVisible: false,
      dialogVisibleedit: false,
      moneyvisible: false,
      userinfo: {
        nickName: '',
        operationType: 'in',
        type: 'consume',
        amount: ''
      },
      userinfos: {
        levelConsume: "0",
        sex: '1',
        status: '1'
      },
      // 余额分页
      moneyList: [],
      pages: 1,
      moneyuserId: '', // 查询当前用户余额的id
    };
  },
  filters: {
    timeFilter(s) {
      return dayjs(s).format("YYYY-MM-DD HH:mm:ss");
    }
  },
  mounted() {

    cacheData = { ...this.query };
    this.getTableData();
    this.getShopInfo();
  },
  methods: {
    moneyevent(d) {
      this.moneyuserId = d.id
      this.moneyevents()
    },
    async moneyevents() {
      let res = await queryShopUserFlow({
        userId: this.moneyuserId,
        page: this.pages,
        pageSize: 10,
      })
      this.moneyList = res
      this.moneyvisible = true
    },
    orderNumberevent(d) {
      this.$router.push({
        path: '/order_manage/order_list',
        query: {
          userId: d.userId
        }
      })
    },
    checkIfNum() {
      this.userinfos.telephone = this.userinfos.telephone.toString().replace(/\D/g, '');
    },
    amountNum() {
      this.userinfo.amount = this.userinfo.amount.toString().replace(/[^\d|\.]/g, '')

    },
    handleClose() {
      this.dialogVisible = false
      this.userinfo = {}
    },
    async sumbituser() {
      let res = await tbShopUseredit({
        ...this.userinfos,
        levelConsume: '0',
        shopId: localStorage.getItem("shopId"),
      })
      this.$message.success('修改成功')
      this.dialogVisibleedit = false
      this.getTableData();
    },
    async sumbit() {
      if (!this.userinfo.amount) {
        this.$message.error("请填写金额")
        return
      }
      let res = await midfiyAccount(this.userinfo)
      this.dialogVisible = false
      this.$message.success('修改成功')
      this.getTableData();
    },
    async editPop(d) {
      let res = await hasPermission('允许修改会员余额');
      if ( !res) { return; }
      this.dialogVisible = true
      this.userinfo.nickName = d.nickName
      this.userinfo.amounts = d.amount
      this.userinfo.id = d.id
      this.userinfo.amount = ""
    },
    async edituser(d) {
      let res = await hasPermission('允许管理会员信息');
      if ( !res) { return; }
      let obj = { ...d }
      if (d.sex == '男') {
        obj.sex = '1'
      } else {
        obj.sex = '2'
      }
      // obj.birthday = d.birthDay
      obj.name = d.nickName
      console.log(obj, '调试1')
      this.userinfos = obj

      this.dialogVisibleedit = true
    },
    toPage(type) {
      const pages = {
        charge: "charge_list",
        cost: "cost_list"
      };
      this.$router.push({
        name: pages[type]
      });
      console.log(pages[type]);
    },
    // 获取商家用户概述信息
    async getShopInfo() {
      try {
        const res = await queryAllShopInfo(this.query);
        this.shopInfo = res;
      } catch (error) {
        console.log(error);
      }
    },
    sizeChange() {
      this.tableData.page = 0;
      this.getTableData();
    },
    // 切换状态
    async statusChange(e, row) {
      try {
        this.tableData.loading = true;
        const data = { ...row };
        data.status = e;
        await modityActivate(data);
        this.getTableData();
      } catch (error) {
        console.log(error);
        this.tableData.loading = false;
      }
    },
    // 重置查询
    resetHandle() {
      this.query.name = "";
      this.query.isVip = 1;
      this.getTableData();
    },
    // 分页回调
    paginationChange(e) {
      this.tableData.page = e - 1;
      this.getTableData();
    },
    paginationChanges(e) {
      this.pages = e;
      this.moneyevents()
    },
    // 获取商品列表
    async getTableData() {
      this.tableData.loading = true;
      //用于当页码为2以及以上查询条件更改时重置页码
      if (cacheData.isVip !== this.query.isVip) {
        this.tableData.page = 0;
      }
      cacheData.isVip = this.query.isVip;
      try {
        const res = await queryAllShopUser({
          ...this.query,
          size: this.tableData.size,
          page: this.tableData.page + 1
        });
        this.tableData.loading = false;
        this.tableData.data = res.content;
        this.tableData.total = res.totalElements;
      } catch (error) {
        console.log(error);
      }
    }
  }
};
</script>

<style scoped lang="scss">
.user_info {
  display: flex;
  align-items: center;

  .name {
    margin-left: 10px;
  }
}

::v-deep .image-slot {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #efefef;
  font-size: 20px;
  color: #999;
}

.card {
  background-color: #f5f5f5;
  padding: 0 14px;

  .title {
    font-size: 22px;
    padding-top: 14px;
  }

  .row {
    display: flex;
    padding: 20px 0;

    .item {
      flex: 1;

      .t {
        text-align: center;
        color: #555;
      }

      .n {
        color: #000;
        font-size: 20px;
        font-weight: bold;
        padding-top: 6px;
        text-align: center;
      }
    }
  }
}
</style>
