<template>
  <a-card size="small" :bordered="false" class="accountManagementList-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="货架名称">
                <shelfList ref="shelfList" @change="shelfChange" :itemSn="queryParam.shelfSn"></shelfList>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="关联客户">
                <custList ref="custList" @change="custChange" :itemSn="queryParam.customerSn" :isEnabled="true"></custList>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="结算方式">
                <v-select code="SHELF_SETTLE_TYPE" v-model="queryParam.settleType" allowClear placeholder="请选择状态"></v-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="待结金额">
                  <a-input-group>
                    <a-row>
                      <a-col :span="11">
                        <a-input-number
                          v-model="queryParam.beginAmount"
                          placeholder="起始金额"
                          :precision="2"
                          :min="0"
                          :max="999999"
                          style="width: 100%;display: inline-block;"/>
                      </a-col>
                      <a-col :span="2"><span style="display: block;text-align: center;line-height: 32px;">至</span></a-col>
                      <a-col :span="11">
                        <a-input-number
                          placeholder="截止金额"
                          :precision="2"
                          :min="0"
                          :max="999999"
                          v-model="queryParam.endAmount"
                          style="width: 100%;display: inline-block;"/>
                      </a-col>
                    </a-row>
                  </a-input-group>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="outboundOrderList-refresh" >查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="outboundOrderList-reset">重置</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-alert type="info" style="margin:10px 0">
        <div slot="message" style="display: flex;align-items: center;padding: 2px 0;">
          共：<strong>{{ count }}</strong>条记录；
          待结算金额合计￥<strong>{{ toThousands(total,2) }}</strong>
        </div>
      </a-alert>
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+77+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ y:tableHeight }"
        :defaultLoadData="true"
        bordered>
        <template slot="action" slot-scope="text,record">
          <a-button
            size="small"
            type="link"
            class="button-primary"
            @click="handleUndetail(record)"
            id="shelfMonitoringList-warehousing-btn">待结明细</a-button>
          <a-button
            size="small"
            type="link"
            class="button-primary"
            @click="handleDetail(record)"
            id="shelfMonitoringList-warehousing-btn">结算历史</a-button>
        </template>
      </s-table>
    </a-spin>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { toThousands } from '@/libs/tools.js'
import moment from 'moment'
import { STable, VSelect } from '@/components'
import shelfList from '@/views/common/shelfList.vue'
import custList from '@/views/common/custList.vue'
import { queryShelfSettleRulePage, queryShelfSettleRuleCount } from '@/api/merchant'
export default {
  components: { STable, shelfList, custList, VSelect },
  mixins: [commonMixin],
  data () {
    return {
      toThousands,
      advanced: true, // 高级搜索 展开/关闭
      spinning: false,
      disabled: false,
      tableHeight: 0,
      showModal: false,
      currentData: null,
      total: 0,
      count: 0,
      time: [],
      queryParam: {
        shelfSn: undefined,
        settleType: undefined,
        beginAmount: '',
        endAmount: ''
      },
      columns: [
        { title: '序号', dataIndex: 'no', width: '10%', align: 'center' },
        { title: '货架名称', dataIndex: 'shelfName', width: '25%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '关联客户', dataIndex: 'dealerName', width: '25%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '结算方式', dataIndex: 'settleTypeDictValue', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '待结金额', dataIndex: 'waitSettleAmount', width: '15%', align: 'right', customRender: function (text) { return toThousands(text, 2) || '--' } },
        { title: '操作', width: '15%', align: 'left', scopedSlots: { customRender: 'action' } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const _this = this
        _this.disabled = true
        _this.spinning = true
        const paramsPage = Object.assign(parameter, this.queryParam) //  有分页
        if (this.checkValueRange()) {
          return queryShelfSettleRulePage(paramsPage).then(res => {
            let data
            if (res.status == 200) {
              data = res.data
              this.getCount(paramsPage)
              const no = (data.pageNo - 1) * data.pageSize
              for (var i = 0; i < data.list.length; i++) {
                data.list[i].no = no + i + 1
              }
              this.disabled = false
            }
            this.spinning = false
            return data
          })
        } else {
          const _this = this
          this.disabled = true
          this.spinning = true
          return new Promise(function (resolve, reject) {
            const data = []
            _this.disabled = false
            _this.spinning = false
            resolve(data)
          })
        }
      }
    }
  },
  methods: {
    // 客户 change
    custChange (obj) {
      this.queryParam.customerSn = obj.key || undefined
    },
    // 货架  change
    shelfChange (obj) {
      this.queryParam.shelfSn = obj.key || undefined
    },
    // 禁止选择今天之后的日期
    disabledDate (current) {
      return current && current > moment().endOf('day')
    },
    // 校验待结金额数值范围
    checkValueRange () {
      const isONull = this.queryParam.beginAmount === null || this.queryParam.beginAmount === undefined
      const isOEmpty = this.queryParam.beginAmount === ''
      const isOZero = this.queryParam.beginAmount === 0
      const isTNull = this.queryParam.endAmount === null || this.queryParam.endAmount === undefined
      const isTEmpty = this.queryParam.endAmount === ''
      const isTZero = this.queryParam.endAmount === 0
      //  第一个为空（可为null可为空字符）第二个不为空
      //  第一个不为空第二个为空（可为null可为空字符）
      //  第一个大于第二个
      if ((isONull || isOEmpty) && (this.queryParam.endAmount || isTZero)) {
        this.$message.info('请输入正确的待结金额查询范围！')
        return false
      }
      if ((this.queryParam.beginAmount || isOZero) && (isTNull || isTEmpty)) {
        this.$message.info('请输入正确的待结金额查询范围！')
        return false
      }
      if (this.queryParam.beginAmount > this.queryParam.endAmount) {
        this.$message.info('请输入正确的待结金额查询范围！')
        return false
      }
      this.queryParam.beginAmount = this.queryParam.beginAmount > 999999999 ? 999999999 : this.queryParam.beginAmount
      this.queryParam.endAmount = this.queryParam.endAmount > 999999999 ? 999999999 : this.queryParam.endAmount
      return true
    },
    // 重置
    resetSearchForm () {
      this.time = []
      this.queryParam = {
        shelfSn: undefined,
        settleType: undefined,
        beginAmount: '',
        endAmount: ''
      }
      this.$refs.table.refresh(true)
    },
    // 合计
    getCount (val) {
      queryShelfSettleRuleCount(val).then(res => {
        if (res.status == 200) {
          this.count = res.data.size || 0
          this.total = res.data.waitSettleAmount || 0
        }
      })
    },
    // 待结明细
    handleUndetail (row) {
      this.$router.push({ name: 'unSettlementDetail', params: { shelfSn: row.shelfSn, settleType: row.settleType, shelfName: row.shelfName } })
      // this.$router.push({ path: `/numsGoodsShelves/settlementManagement/warehouseDetail/${row.shelfPlaceSn}/${row.productSn}` })
    },
    // 结算历史
    handleDetail (row) {
      this.$router.push({ name: 'settlementDetail', params: { shelfSn: row.shelfSn, shelfName: row.shelfName } })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 265
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      setTimeout(() => {
        _this.setTableH()
      }, 400)
    },
    '$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()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .accountManagementList-wrap{

  }
</style>
