<template>
  <div class="page-box" v-loading="loading > 0">
    <Header :title="title"></Header>
    <div class="container">
      <!-- tab -->
      <div class="content">
        <!-- 表格 -->
        <div class="filter-box">
          <div class="filter">
            <!-- <div class="filter-item">
              <p class="label">系统：</p>
              <el-select
                v-model="filter.sys"
                placeholder="全部"
                size="small"
                class="input"
                style="margin: 0 10px"
              >
                <el-option
                  v-for="item in system"
                  :key="item.value"
                  :label="item.labelName"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div> -->

            <div class="filter-item">
              <p class="label">变动类型：</p>
              <el-select
                v-model="filter.fundType"
                placeholder="全部"
                size="small"
                class="input"
                style="margin: 0 10px"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>

            <div class="filter-item">
              <p class="label">变动时间段：</p>
              <el-date-picker
                style="margin: 0 10px"
                size="small"
                class="date-input"
                v-model="date"
                type="datetimerange"
                align="right"
                unlink-panels
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </div>

            <div class="filter-item">
              <!-- <div class="label">用户ID：</div> -->
              <el-input
                class="input"
                type="number"
                v-model="filter.uid"
                placeholder="用户id"
                size="small"
              >
                <template slot="prepend"
                  >QY</template
                >
              </el-input>
            </div>

            <!-- <div class="filter-item">
              <div class="label">查询时间：</div>
              <el-date-picker
                v-model="date"
                type="datetimerange"
                align="right"
                unlink-panels
                class="date-input"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                size="small"
              >
              </el-date-picker>
            </div> -->
          </div>
          <div class="btn-box">
            <button class="search" @click="search">筛选</button>
            <button class="reset" @click="reset">重置</button>
            <button
              class="search"
              style="margin-left: 60px"
              @click="order2excel"
            >
              导出
            </button>
          </div>
        </div>
        <el-table
          :data="list"
          class="order-table table no-border-table"
          ref="orderTable"
          :header-cell-style="{
            border: 'none',
            color: '#333',
            background: '#f6f6f6',
            borderBottom: '1px solid #E8E8E8',
            height: '54px',
          }"
          :row-style="{
            height: '54px',
          }"
        >
          <el-table-column
            prop="nickname"
            align="center"
            label="用户昵称"
          ></el-table-column>
          <el-table-column prop="uid" align="center" label="用户ID">
            <div slot-scope="scope">
              {{ uidFormat(scope.row.uid) }}
            </div>
          </el-table-column>
          <el-table-column
            prop="describe"
            align="center"
            label="变动类型"
          ></el-table-column>
          <el-table-column
            prop="amount"
            align="center"
            label="操作金额/元"
          ></el-table-column>
          <el-table-column
            prop="afterAmount"
            align="center"
            label="操作后金额"
          ></el-table-column>
          <!-- <el-table-column prop="status" align="center" label="状态">
            <div slot-scope="scope">
              {{ statusMap[scope.row.status] }}
            </div>
          </el-table-column> -->
          <el-table-column
            prop="created"
            align="center"
            label="变更时间"
          ></el-table-column>
          <el-table-column prop="adminUid" align="center" label="操作人ID">
            <div slot-scope="scope">
              {{ uidFormat(scope.row.adminUid) }}
            </div>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页按钮 -->
      <div class="footer">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          background
          layout="total, prev, pager, next, jumper"
          :page-size="size"
          :total="total"
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      :show-close="false"
      :close-on-click-modal="false"
      title="生成中..."
      :visible.sync="showProgressDialog"
      width="30%"
      center
    >
      <el-progress
        :percentage="progress"
        :text-inside="true"
        :stroke-width="18"
      ></el-progress>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
import Header from '../../components/common/header';
import myUtils from '../../components/common/whatever2excel';
import { role, roleMap } from '@/config.js';
export default {
  components: {
    Header
  },
  name: 'balanceRecord',
  data() {
    return {
      currentPage: 1, // 当前页码
      size: 20, // 每页条数
      total: 0, // 总页数
      loading: 0, // 加载中
      title: {
        // 页面标题
        firstTitile: '资金管理',
        secondTitle: '余额变动记录'
      },
      filter: {
        uid: null,
        fundType: null,
        begin: '',
        end: ''
      },
      role: [
        {
          name: '全部',
          id: -1
        },
        ...role
      ],
      roleMap: roleMap,
      tabActive: 1,
      statusType: [],
      list: [], // 列表
      date: [],
      showProgressDialog: false,
      progress: 0,
      system: [],
      systemMap: {},
      typeList: [],
      typeMap: {},
      statusMap: {
        0: '冻结中',
        5: '已解冻'
      }
    };
  },

  mounted() {
    // this.statusType = this.hzType;
    // 获取列表
    this.getList();
    // this.getDictionary();
    this.getFundTypeMap();
  },
  computed: {},
  methods: {
    // 切换页码
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getList();
    },

    // 获取列表
    getList() {
      this.filter.begin = this.date[0] || '';
      this.filter.end = this.date[1] || '';
      this.loading++;
      this.httpGet(this.$root.getBalance, {
        page: this.currentPage,
        size: this.size,
        ...this.filter
      }).then(
        (res) => {
          this.loading--;
          this.list = res.list;
          this.total = res.total;
        },
        (res) => {
          this.loading--;
          this.$message.error(res);
        }
      );
    },
    getFundTypeMap() {
      this.loading++;
      this.httpGet(this.$root.getFundTypeMap, {}).then(
        (res) => {
          this.loading--;
          this.typeMap = res.balanceLog.balance;
          let list = [];
          for(let key in this.typeMap){
            list.push({
              name: this.typeMap[key],
              value: key
            });
          };
          this.typeList = list;
        },
        (res) => {
          this.loading--;
          this.$message.error(res);
        }
      );
    },
    getDictionary(){
      this.getDictionaryByName('system');
    },
    getDictionaryByName(dataName){
      this.loading++;
      this.httpGet(this.$root.getDictionaryByName, {
        dataName
      }).then(
        (res) => {
          this.loading--;
          this[dataName] = res.list;
          let obj = {};
          res.list.forEach(item => {
            obj[item.value] = item.labelName;
          });
          this[dataName + 'Map'] = obj;
        },
        (res) => {
          this.loading--;
          this.$message.error(res);
        }
      );
    },
    // 过滤
    search() {
      this.currentPage = 1;
      this.getList();
    },
    // 重置过滤
    reset() {
      this.filter = {
        uid: null,
        fundType: null,
        begin: '',
        end: ''
      };
      this.date = [];
      this.getList();
    },
    uidFormat(val) {
      if (!val) return '-';
      let str = val + '';
      let length = 6 - str.length;
      for (let i = 0; i < length; i++) {
        str = '0' + str;
      }
      return 'QY' + str;
    },
    async order2excel() {
      if(!(await this.exportLog())) return;
      this.loading++;
      let list = [];
      let totalPage = null;
      let data = {
        page: this.currentPage,
        size: this.size,
        ...this.filter
      };
      await this.httpGet(this.$root.getBalance, data).then(
        (res) => {
          this.loading--;
          totalPage = Math.ceil(parseInt(res.total) / this.size);
        },
        () => {
          this.loading--;
        }
      );
      this.showProgressDialog = true;
      this.progress = 0;
      await this.getAllPages(totalPage, list).then(
        () => {
          this.showProgressDialog = false;
          this.jsonFormatAndToExcel(list);
        },
        (err) => {
          console.error(err);
          this.showProgressDialog = false;
        }
      );
    },
    async getAllPages(totalPage, list) {
      for (let i = 1; i <= totalPage; i++) {
        let data = {
          page: i,
          size: this.size,
          ...this.filter
        };
        await this.httpGet(this.$root.getBalance, data).then((res) => {
          list.push(...res.list);
          this.progress = Math.floor((i / totalPage) * 100);
          console.log('page' + i, list.length);
        });
        // console.log(5555, list);
      }
    },
    jsonFormatAndToExcel(list) {
      let formatList = [];
      list.forEach((item) => {
        let obj = {
          用户昵称: item.nickname,
          用户ID: this.uidFormat(item.uid),
          变动类型: item.describe,
          '操作金额/元': +item.amount,
          操作后金额: +item.afterAmount,
          变更时间: item.created,
          操作人ID: this.uidFormat(item.adminUid),
        };
        formatList.push(obj);
      });
      myUtils.json2excel(formatList);
    },
    exportLog(){
      this.loading++;
      return this.httpGet(this.$root.getBalance + '/export', {}).then(
        (res) => {
          this.loading--;
          return true;
        },
        (res) => {
          this.loading--;
          this.$message.error(res);
          return false;
        }
      );
    },
  }
};
</script>
<style lang="stylus" rel="stylesheet/stylus">
@import '~assets/public.styl';
</style>
<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '~assets/main.styl';

.page-box {
  height: 100%;
  width: 100%;
  flex-y(flex-start, flex-start);
  overflow-y: hidden;
  background: bg-color;

  .container {
    box-sizing: border-box;
    height: 100%;
    width: 100%;
    overflow-y: auto;
    flex-y(flex-start, flex-start);
    padding: 0 20px 20px;

    // content 表格
    .content {
      flex: 1;
      width: 100%;
      font-size: 14px;
      background: white;
      box-sizing: border-box;
      padding: 24px 32px;
      border-radius: 2px;

      // 按钮
      .btn {
        width: 100px;
        height: 32px;
        line-height: 32px;
        confirm-btn();
        font-size: 14px;
        margin: 16px 0;
      }

      // 表格按钮
      .table-btn {
        // width: 65px;
        height: 24px;
        line-height: 24px;
        color: gray3;
        font-size: 12px;
        margin-right: 8px;
        cancel-btn();
        padding: 0 8px;
      }

      .filter-item {
        margin-right: 12px;
      }

      .select, .input {
        width: 160px;
      }

      .date-input {
        width: 360px;
      }

      .btn-box {
        margin: 0;
      }

      .table {
        margin-top: 24px !important;
      }
    }
  }

  .footer {
    width: 100%;
    padding: 24px;
    box-sizing: border-box;
    flex-x(flex-end);
    background: white;
  }

  .dialog-content {
    flex-y();
  }

  .form {
    width: 100%;
    flex-center();
    margin: 8px 0;
  }
}

.tabs {
  width: 100%;
  background: #fff;
  height: 60px;
  flex-x(flex-start);
  padding: 0 30px;
  box-sizing: border-box;
  margin-top: 8px;
  flex-shrink: 0;

  .tab {
    background: #fff;
    cursor: pointer;
    padding: 0 15px;
    position: relative;
    width: auto;
    margin-right: 100px;
    height: 100%;
    flex-x(center);
    word(16px, #999);

    &.active {
      word(16px, #333);

      .tab-line {
        width: 100%;
        position: absolute;
        background: #4678E6;
        height: 4px;
        border-radius: 2px;
        left: 0;
        bottom: 3px;
      }
    }
  }
}
</style>
