<template>
  <a-card size="small" :bordered="false" class="storeAccount-wrap jg-page-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="货架名称">
                <shelfSList v-model="queryParam.shelfSn" id="storeAccount-shelfName"></shelfSList>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="关联客户">
                <custList ref="custList" id="storeAccount-custList" @change="custChange" :isEnabled="true"></custList>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="storeAccount-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="storeAccount-reset">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 统计 -->
      <div class="table-operator" style="margin-bottom:10px;">
        <div class="alert-message">
          总充值：<strong>{{ totalData&&(totalData.totalRecharge || totalData.totalRecharge==0) ? toThousands(totalData.totalRecharge) : '--' }}</strong>；
          已用充值：<strong>{{ totalData&&(totalData.usedRecharge || totalData.usedRecharge==0) ? toThousands(totalData.usedRecharge) : '--' }}</strong>；
          充值余额：<strong>{{ totalData&&(totalData.rechargeBalance || totalData.rechargeBalance==0) ? toThousands(totalData.rechargeBalance) : '--' }}</strong>；
          总抵扣：<strong>{{ totalData&&(totalData.totalGive || totalData.totalGive==0) ? toThousands(totalData.totalGive) : '--' }}</strong>；
          已用抵扣：<strong>{{ totalData&&(totalData.usedDeduction || totalData.usedDeduction==0) ? toThousands(totalData.usedDeduction) : '--' }}</strong>；
          抵扣余额：<strong>{{ totalData&&(totalData.giveBalance || totalData.giveBalance==0) ? toThousands(totalData.giveBalance) : '--' }}</strong>；
        </div>
      </div>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ y: tableHeight }"
        :defaultLoadData="false"
        bordered>
        <!-- 充值余额 -->
        <template slot="rechargeBalance" slot-scope="text, record">
          <span class="table-td-link" :id="'storeAccount-recharge'+record.id" v-if="$hasPermissions('B_clearRecord')" @click="handleFlow(record,'1')">{{ (record.rechargeBalance||record.rechargeBalance==0)?toThousands(record.rechargeBalance):'--' }}</span>
          <span v-else>{{ (record.rechargeBalance||record.rechargeBalance==0)?toThousands(record.rechargeBalance):'--' }}</span>
        </template>
        <!-- 抵扣余额 -->
        <template slot="giveBalance" slot-scope="text, record">
          <span class="table-td-link" :id="'storeAccount-give'+record.id" v-if="$hasPermissions('B_clearRecord')" @click="handleFlow(record,'2')">{{ (record.giveBalance||record.giveBalance==0)?toThousands(record.giveBalance):'--' }}</span>
          <span v-else>{{ (record.giveBalance||record.giveBalance==0)?toThousands(record.giveBalance):'--' }}</span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            :id="'storeAccount-clearRecord'+record.id"
            v-if="$hasPermissions('B_clearRecord')"
            size="small"
            type="link"
            class="button-primary"
            @click="handleClearRecord(record)">清零记录</a-button>
          <a-button
            :id="'storeAccount-ZeroClear-'+record.id"
            size="small"
            type="link"
            v-if="$hasPermissions('B_zeroClear')"
            class="button-error"
            @click="handleZeroClear(record)">清零</a-button>
          <span v-if="!$hasPermissions('B_clearRecord')&&!$hasPermissions('B_zeroClear')">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 交易流水 -->
    <transaction-flow-modal :modalType="modalType" :itemInfo="itemInfo" :openModal="openFlowModal" @close="openFlowModal=false"></transaction-flow-modal>
    <!-- 清零 -->
    <zero-clearing-modal ref="zeroClearModal" :openModal="openZeroClearModal" @ok="$refs.table.refresh(true)" @close="openZeroClearModal=false"></zero-clearing-modal>
    <!-- 清零记录 -->
    <clear-record-modal ref="clearRecordModal" :openModal="openClearRecordModal" @close="openClearRecordModal=false"></clear-record-modal>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable } from '@/components'
import custList from '@/views/common/custList.vue' // 客户列表组件
import shelfSList from '@/views/common/shelfList' // 货架列表组件
import transactionFlowModal from './transactionFlowModal.vue' // 交易流水弹框
import zeroClearingModal from './zeroClearingModal.vue' // 清零弹框
import clearRecordModal from './clearRecordModal.vue' // 清零记录弹框
// 接口
import { storeAccountList, storeAccountCount } from '@/api/storeAccount' // 接口api

export default {
  components: { STable, custList, shelfSList, transactionFlowModal, zeroClearingModal, clearRecordModal },
  mixins: [commonMixin],
  data () {
    const _this = this
    return {
      spinning: false, // loading
      tableHeight: 0, // 表格高度
      disabled: false, //  查询、重置按钮是否可操作
      queryParam: {
        shelfSn: undefined, // 货架sn
        customerSn: undefined, // 关联客户sn
        customerName: undefined// 关联客户名称
      },
      time: [],
      modalType: '1',
      openFlowModal: false, // 打开 交易流水弹窗
      openZeroClearModal: false, // 打开 清零弹窗
      openClearRecordModal: false, // 打开 清零记录弹窗
      totalData: null, // 统计数据
      itemInfo: null, // 当前行数据
      // 列定义
      columns: [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '货架名称', dataIndex: 'shelfName', width: '23%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '关联客户', dataIndex: 'customerName', width: '23%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '总充值', dataIndex: 'totalRecharge', width: '12%', align: 'right', customRender: function (text) { return (text || text == 0) ? _this.toThousands(text, 2) : '--' } },
        { title: '总抵扣', dataIndex: 'totalGive', width: '12%', align: 'right', customRender: function (text) { return (text || text == 0) ? _this.toThousands(text, 2) : '--' } },
        { title: '充值余额', dataIndex: 'rechargeBalance', width: '12%', align: 'right', scopedSlots: { customRender: 'rechargeBalance' } },
        { title: '抵扣余额', dataIndex: 'giveBalance', width: '12%', align: 'right', scopedSlots: { customRender: 'giveBalance' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '16%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        return storeAccountList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
            }
            this.getCount(params)
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  methods: {
    // 统计
    getCount (val) {
      storeAccountCount(val).then(res => {
        if (res.status == 200) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    // 交易流水  1 充值余额  2抵扣余额
    handleFlow (row, type) {
      this.modalType = type
      this.itemInfo = row
      this.openFlowModal = true
    },
    // 打开清零记录弹窗
    handleClearRecord (row) {
      this.$refs.clearRecordModal.pageInit(row)
      this.openClearRecordModal = true
    },
    // 打开清零弹窗
    handleZeroClear (record) {
      this.$refs.zeroClearModal.pageInit(record)
      this.$nextTick(() => {
        this.openZeroClearModal = true
      })
    },
    // 选择关联客户
    custChange (obj, row) {
      if (row) {
        this.queryParam.customerSn = row && row.customerSn || undefined
        this.queryParam.customerName = undefined
      } else {
        this.queryParam.customerName = obj || undefined
        this.queryParam.customerSn = undefined
      }
    },
    // 是否设置完成更改
    changeStatus (record) {
      const params = {
        shelfSn: record.shelfSn,
        finishFlag: record.finishFlag == 1 ? '0' : '1'
      }
      this.spinning = true
      modifFinishFlag(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$refs.table.refresh()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    // 启用禁用
    enableShelf (record) {
      const params = {
        shelfSn: record.shelfSn,
        state: record.state == 'ENABLE' ? 'DISABLED' : 'ENABLE'
      }
      const _this = this
      _this.$confirm({
        title: '提示',
        content: <div style="text-align:center;">是否{(record.state == 'ENABLE' ? '停用' : '启用') + record.shelfName}</div>,
        centered: true,
        closable: true,
        class: 'confirm-center',
        onOk () {
          _this.updateState(params)
        }
      })
    },

    // 更改货架状态
    updateState (params) {
      this.spinning = true
      shelfModifState(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$refs.table.refresh()
          this.spinning = false
        } else {
          this.spinning = false
        }
        this.showTip = false
      })
    },
    // 重置列表查询
    resetSearchForm () {
      this.queryParam.shelfSn = undefined
      this.queryParam.customerSn = undefined
      this.queryParam.customerName = undefined
      this.$refs.custList.resetForm()
      this.$refs.table.refresh(true)
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 240
    },
    // 初始化页面
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  }
}
</script>
