<template>
  <section class="recharge dm-wrap" v-loading="loading">
    <div class="pb22">
      <el-date-picker v-model="dateTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="onSearch"></el-date-picker>
      <el-select style="width:180px" clearable v-model="listParams.feeType" placeholder="全部记录类型" @change="onChangeFeeType">
        <el-option label="充值" :value="1"></el-option>
        <el-option label="扣款" :value="2"></el-option>
        <el-option label="退费" :value="3"></el-option>
      </el-select>
      <el-select v-if="listParams.feeType == 2" style="width:180px" clearable v-model="listParams.deductType" placeholder="全部扣款类型" @change="onSearch">
        <el-option v-for="(value, key) in deductTypeList" :key="key" :label="value" :value="key"></el-option>
      </el-select>
      <select-depart v-if="isMoreAccount && config.showAllDepartment" :data="deparment" @load="load" @getDepartId="getDepartId" @remote-search="remoteSearch" :loading="deparment.loading" />
    </div>
    <el-table tooltipEffect="dark" :data="tableList" style="width: 100%">
      <el-table-column align="left" prop="timeEnd" label="操作时间">
        <template slot-scope="scope">
          <p style="color:#606266;">{{ formatDateTimeByType(scope.row.timeEnd, 'yyyy-MM-dd-HH-mm-ss', true).y }}</p>
          <p style="color:#606266;">{{ formatDateTimeByType(scope.row.timeEnd, 'yyyy-MM-dd-HH-mm-ss', true).h }}</p>
        </template>
      </el-table-column>
      <el-table-column align="left" prop="transactionId" label="流水号"></el-table-column>
      <el-table-column label="记录类型">
        <template slot-scope="scope">
          {{ textMap[scope.row.feeType] || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="扣款类型">
        <template slot-scope="scope">
          {{ deductTypeList[scope.row.deductType] || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="余额(元)" align="left" prop="totalFee">
        <template slot-scope="scope"> {{ scope.row.totalFee ? (scope.row.totalFee / 100).toFixed(2) : '0.00' }}元 </template>
      </el-table-column>
      <el-table-column v-if="isMoreAccount" label="计费部门" align="left" prop="accountDepartName">
        <template slot-scope="{ row }">{{ row.accountDepartName || '--' }}</template>
      </el-table-column>
      <el-table-column align="left" prop="reason" label="原因" show-overflow-tooltip>
        <template slot-scope="{ row }">{{ row.reason || '--' }}</template>
      </el-table-column>
      <el-table-column label="图片凭证">
        <template slot-scope="scope">
          <viewer :options="options" :images="getUrls(scope)" class="viewer" ref="viewer">
            <template #default="scope2">
              <img style="width: 36px; height: 36px;margin-left:5px;cursor:pointer" v-for="src in scope2.images" :src="src" :key="src" />
            </template>
          </viewer>
        </template>
      </el-table-column>
    </el-table>
    <dm-pagination v-show="tableList.length" background class="dm-pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listParams.currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="listParams.pageSize" layout="total, sizes, prev, pager, next" :total="total"></dm-pagination>
  </section>
</template>
<script>
import { rechargeRecord, getDepartList } from '@/service/api/rechargeApi.js';
import { formatDateTimeByType } from '@/utils/index.js';
import 'viewerjs/dist/viewer.css';
import { component as Viewer } from 'v-viewer';
import SelectDepart from './components/select-depart.vue';
import intel from './recharge_mixin';

export default {
  name: 'recharge-record',
  components: { Viewer, SelectDepart },
  mixins: [intel],
  data() {
    return {
      textMap: {
        1: '充值',
        2: '扣款',
        3: '退费'
      },
      formatDateTimeByType,
      dateTime: [Date.now() - 30 * 24 * 60 * 60 * 1000, Date.now()],
      loading: false,
      tableList: [],
      listParams: {
        currentPage: 1,
        pageSize: 20,
        beginTime: '',
        endTime: '',
        deductType: '',
        feeType: '',
        accountDepartId: ''
      },
      deparment: {
        list: [],
        searchParams: '',
        status: -1,
        pageSize: 20,
        currentPage: 1,
        loading: false,
        isLimit: false, // 是否最后一页
        departId: '', // 选中时得id
        zbFlag: 1
      },
      total: 0,
      deductTypeList: {}
    };
  },
  async created() {
    this.getDepartmentList();
    this.$store.commit('mutations_breadcrumb', [{ name: '企业管理', path: '' }, { name: '计费中心', path: '/recharge' }, { name: '记录', path: '' }]); // eslint-disable-line
    const config = await this.getAuth(); // rechartge_mixin
    this.deparment.departId = this.$route.query.id || config.accountDepartId;
    await this.getRule(); // 该接口调取完后select-depart组件挂载所以在之前一步初始化departId
    this.rechargeRecord();
  },
  methods: {
    getUrls(scope) {
      let urls = scope.row.imageUrls ? scope.row.imageUrls.split(',') : [];
      urls = urls.filter(el => el);
      return urls;
    },
    onChangeFeeType() {
      this.listParams.deductType = '';
      this.onSearch();
    },
    onSearch() {
      this.listParams.currentPage = 1;
      this.rechargeRecord();
    },
    handleSizeChange(val) {
      this.listParams.currentPage = 1;
      this.listParams.pageSize = val;
      this.rechargeRecord();
    },
    handleCurrentChange(val) {
      this.listParams.currentPage = val;
      this.rechargeRecord();
    },
    async rechargeRecord() {
      const para = this.listParams;
      this.loading = true;
      if (this.dateTime) {
        para.beginTime = formatDateTimeByType(this.dateTime[0], 'yyyy-MM-dd');
        para.endTime = formatDateTimeByType(this.dateTime[1], 'yyyy-MM-dd');
      } else {
        para.beginTime = '';
        para.endTime = '';
      }
      const id = this.setAccountDepartId(this.deparment.departId, this.config);
      if (id) para.accountDepartId = id;
      else {
        delete para.accountDepartId;
      }
      try {
        let res = await rechargeRecord(para);
        if (res.errorCode === 0 && res.result.result) {
          this.tableList = res.result.result;
          this.total = res.result.totalCount;
          this.deductTypeList = JSON.parse(res.result.params.deductTypeList || '{}');
        } else {
          this.tableList = [];
        }
      } catch (err) {
        console.log(err);
      }
      this.loading = false;
    },
    // 计费部门下拉
    // 获取计费部门
    async getDepartmentList() {
      const depart = this.deparment;
      depart['loading'] = true;
      const para = Object.assign({}, depart);
      const typeArr = ['list', 'loading', 'isLimit', 'departId'];
      this.deleteAttribute(para, typeArr);
      let { result } = await getDepartList(para);
      this.setDepartData(depart, result);
    },
    // 清除接口无用属性
    deleteAttribute(obj, typeArr) {
      for (const key in obj) {
        if (typeArr.includes(key)) delete obj[key];
      }
    },
    // 设置departmentData
    setDepartData(obj, result) {
      const data = result.result || [];
      const total = result.totalCount;
      obj['list'].push(...data);
      obj['isLimit'] = obj['list'].length >= total; // list得数据量>=数据总数时做出限制
      obj['loading'] = false;
    },
    // 下拉滚动加载
    load() {
      const depart = this.deparment;
      if (depart['isLimit'] || depart['loading']) return;
      depart['currentPage']++;
      this.getDepartmentList();
    },
    getDepartId(id) {
      // 选中不同下拉得id时，调用对应得表格方法
      const depart = this.deparment;
      depart['departId'] = id;
      this.listParams['currentPage'] = 1;
      this.rechargeRecord();
    },
    // 下拉远程搜索
    remoteSearch(val) {
      const depart = this.deparment;
      depart['searchParams'] = val.trim();
      depart['currentPage'] = 1;
      depart['isLimit'] = false;
      depart['list'] = [];
      this.getDepartmentList();
    }
  },
  filters: {
    filterPayType(val) {
      let result = '';
      switch (val) {
        case 1:
          result = '微信';
          break;
        case 2:
          result = '支付宝';
          break;
        case 3:
          result = '线下充值';
          break;
        default:
          result = '未知';
          break;
      }
      return result;
    }
  }
};
</script>
