<template>
  <div>
    <!-- 搜索条件 -->
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form-model
          id="salesOrderWarehouseList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :rules="rules"
          :model="queryParam"
          @keyup.enter.native="handleSearch">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="创建时间" prop="time">
                <rangeDate ref="rangeDate" :value="queryParam.time" @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="客户名称">
                <dealerSubareaScopeList ref="dealerSubareaScopeList" id="salesManagementList-buyerName" @change="custChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="销售单号">
                <a-input id="salesOrderWarehouseList-salesBillNo" v-model.trim="queryParam.salesBillNo" allowClear placeholder="请输入销售单号"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="业务状态">
                <v-select
                  v-model="queryParam.billStatus"
                  ref="billStatus"
                  id="salesManagementList-billStatus"
                  code="SALES_BILL_STATUS"
                  placeholder="请选择业务状态"
                  allowClear></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="地区" prop="shippingAddrProvinceSn">
                <Area id="salesOrderWarehouseList-shippingAddrProvinceSn" v-model="queryParam.shippingAddrProvinceSn" placeholder="请选择省"></Area>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24" v-show="isShowWarehouse">
              <a-form-model-item label="出库仓库">
                <chooseWarehouse ref="warehouse" v-model="queryParam.warehouseSn" :isPermission="true"></chooseWarehouse>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="handleSearch" :disabled="disabled" id="salesOrderWarehouseList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="salesOrderWarehouseList-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_salesOrderWarehouseExport')"
              >导出</a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>

    <a-card size="small" :bordered="false" class="salesOrderWarehouseList-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <div class="tongji-bar" style="margin-bottom:10px">
          <!-- 总款数：<strong>{{ totalData&&(totalData.totalCategory || totalData.totalCategory==0) ? totalData.totalCategory : '0' }}</strong>； -->
          总数量：<strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '--' }}</strong>；
        </div>
        <!-- 列表 -->
        <v-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+35+'px' }"
          size="small"
          rowKeyName="no"
          :columns="columns"
          :pagination="{pageSize:30}"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 单号 -->
          <template slot="stockOutNo" slot-scope="text, record" v-if="$hasPermissions('B_salesOrderWarehouseDetail')">
            <span class="link-bule" @click="handleDetail(record)">{{ record.salesBillNo }}</span>
            <a-badge count="促" v-if="record.promoFlag==1" :number-style="{ backgroundColor: '#52c41a', zoom:'80%' }"></a-badge>
          </template>
        </v-table>
      </a-spin>
      <!-- 导出提示框 -->
      <reportModal :visible="showExport" @close="showExport=false"></reportModal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import rangeDate from '@/views/common/rangeDate.vue'
import getDate from '@/libs/getDate.js'
import Area from '@/views/common/area.js'
import reportModal from '@/views/common/reportModal.vue'
import { VTable, VSelect } from '@/components'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import { queryPageForWarehouse, queryCountForWarehouse, exportForWarehouse } from '@/api/salesNew'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import { hdExportExcel } from '@/libs/exportExcel'
export default {
  name: 'SalesOrderWarehouseList',
  mixins: [commonMixin],
  components: { VTable, VSelect, rangeDate, Area, chooseWarehouse, reportModal, dealerSubareaScopeList },
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      queryParam: { //  查询条件
        time: [
          moment(getDate.getCurrMonthDays().starttime, 'YYYY-MM-DD'),
          moment(getDate.getCurrMonthDays().endtime, 'YYYY-MM-DD')
        ],
        beginDate: getDate.getThreeMonthDays().starttime, // 开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 结束时间
        buyerSn: '', //  客户名称
        billStatus: 'WAIT_AUDIT', //  业务状态
        salesBillNo: '', // 销售单号
        shippingAddrProvinceSn: undefined, // 地址sn
        warehouseSn: undefined // 仓库sn
      },
      exportLoading: false, // 导出loading
      disabled: false, //  查询、重置按钮是否可操作
      loading: false,
      totalData: null, // 统计信息
      showExport: false, // 导出提示框
      // 校验规则
      rules: {
        'time': [{ required: true, message: '请选择创建时间', trigger: 'change' }]
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        return queryPageForWarehouse(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
        })
      }
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '3.5%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售单号', scopedSlots: { customRender: 'stockOutNo' }, width: '15%', align: 'center' },
        { title: '提交时间', dataIndex: 'submitDate', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'dealerEntity.dealerName', width: '32%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '总数量', dataIndex: 'totalQty', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: '15%', align: 'center', customRender: function (text) { return text || '--' } }
      ]
      // 如果显示仓库
      if (this.isShowWarehouse) {
        arr.splice(5, 0, { title: '出库仓库', dataIndex: 'warehouseName', width: '20%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true })
      }
      return arr
    }
  },
  methods: {
    // 查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择创建时间')
          return false
        }
      })
    },
    // 选择客户
    custChange (val) {
      this.queryParam.buyerSn = val.key
    },
    // 获取总数量
    getCount (params) {
      queryCountForWarehouse(params).then(res => {
        if (res.status == 200) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    //  导出
    handleExport () {
      const _this = this
      _this.exportLoading = true
      _this.spinning = true
      hdExportExcel(exportForWarehouse, _this.queryParam, '仓库销售单明细', function () {
        _this.exportLoading = false
        _this.spinning = false
        _this.showExport = true
      })
    },
    //  选择时间  change
    dateChange (date) {
      if (date[0] && date[1]) {
        this.queryParam.time = date
      } else {
        this.queryParam.time = []
      }
      this.queryParam.beginDate = date[0] || ''
      this.queryParam.endDate = date[1] || ''
    },
    //  重置
    resetSearchForm () {
      this.queryParam.time = [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ]
      this.$refs.rangeDate.resetDate(this.queryParam.time)
      this.$refs.dealerSubareaScopeList.resetForm()
      this.queryParam.beginDate = getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.buyerSn = ''
      this.queryParam.billStatus = 'WAIT_AUDIT'
      this.queryParam.salesBillNo = ''
      this.queryParam.shippingAddrProvinceSn = undefined
      this.queryParam.warehouseSn = undefined
      this.$refs.table.refresh(true)
    },
    //  打开详情页面
    handleDetail (row) {
      this.$router.push({ path: `/salesManagement/salesOrderWarehouse/detail/${row.salesBillSn}/${row.warehouseSn}` })
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.rowSelectionInfo = null
      this.$refs.table.clearSelected()
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 190
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  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">
  .salesOrderWarehouseList-wrap{
    margin-bottom: 6px;
    &:first-child{
      .ant-card-body{
        padding-bottom: 2px;
      }
    }
  }
</style>
