<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <!-- 搜索条件 -->
      <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="创建时间">
                <rangeDate ref="rangeDate" :allowClear="false" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品编码">
                <a-input id="shortageStatisticsCList-productCode" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户名称">
                <dealerSubareaScopeList ref="custList" id="shortageStatisticsCList-buyerSn" :itemSn="queryParam.buyerSn" @change="custChange"></dealerSubareaScopeList>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="销售单号">
                  <a-input id="shortageStatisticsCList-salesBillNo" v-model.trim="queryParam.salesBillNo" allowClear placeholder="请输入销售单号"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品状态">
                  <v-select code="PRODUCT_STATUS" id="shortageStatisticsCList-state" v-model="queryParam.state" allowClear placeholder="请选择产品状态"></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品名称">
                  <a-input id="shortageStatisticsCList-productName" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="客户类型">
                  <dealerType
                    id="shortageStatisticsCList-dealerType"
                    changeOnSelect
                    v-model="dealerType"
                    @change="getDealerType"
                    allowClear
                    placeholder="请选择商户类型"></dealertype>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品分类">
                  <ProductType v-model="productType" id="shortageStatisticsCList-productType" @change="changeProductType" placeholder="请选择产品分类"></ProductType>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="品牌">
                  <ProductBrand id="shortageStatisticsCList-productBrandSn" v-model="queryParam.productBrandSn"></ProductBrand>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="品牌分类">
                  <v-select code="BRAND_TYPE" id="shortageStatisticsCList-brandType" v-model="queryParam.brandType" allowClear placeholder="请选择品牌分类"></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="区域">
                  <subarea id="shortageStatisticsCList-subarea" ref="subarea" @change="subareaChange"></subarea>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="省份" prop="provinceSn">
                  <Area id="shortageStatisticsCList-provinceSn" v-model="queryParam.provinceSn" placeholder="请选择省"></Area>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="仓库">
                  <chooseWarehouse ref="warehouse" v-model="queryParam.warehouseSn"></chooseWarehouse>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                <a-form-item label="客服">
                  <customerService ref="customerName" v-model="queryParam.bizUserSn"></customerService>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24" style="margin-bottom: 8px;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="shortageStatisticsCList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="shortageStatisticsCList-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_oosDetailExportByBuyer')"
                id="shortageStatisticsCList-export">导出</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-card>
    <a-card size="small" :bordered="false" class="shortageStatisticsCList-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- alert -->
        <div class="tongji-bar">
          <div>
            <div>
              总客户数：<strong>{{ productTotal && (productTotal.totalBuyerQty || productTotal.totalBuyerQty==0) ? productTotal.totalBuyerQty : '--' }}</strong>，
              总单数：<strong>{{ productTotal && (productTotal.totalRecord || productTotal.totalRecord==0) ? productTotal.totalRecord : '--' }}</strong>，
              缺货总款数：<strong>{{ productTotal && (productTotal.totalCategory || productTotal.totalCategory==0) ? productTotal.totalCategory : '--' }}</strong>，
              缺货总数量：<strong>{{ productTotal && (productTotal.totalQty || productTotal.totalQty==0) ? productTotal.totalQty : '--' }}</strong>，
              <span v-if="$hasPermissions('M_shortageStatisticsCList_salesPrice')">缺货总金额：<strong>{{ productTotal && (productTotal.totalAmount || productTotal.totalAmount==0) ? toThousands(productTotal.totalAmount) : '--' }}</strong></span>
            </div>
            <div>
              本页客户数：<strong>{{ currentTotal && (currentTotal.totalBuyerQty || currentTotal.totalBuyerQty==0) ? currentTotal.totalBuyerQty : '--' }}</strong>，
              本页总单数：<strong>{{ currentTotal && (currentTotal.totalRecord || currentTotal.totalRecord==0) ? currentTotal.totalRecord : '--' }}</strong>，
              本页缺货总款数：<strong>{{ currentTotal && (currentTotal.totalCategory || currentTotal.totalCategory==0) ? currentTotal.totalCategory : '--' }}</strong>，
              本页缺货总数量：<strong>{{ currentTotal && (currentTotal.totalQty || currentTotal.totalQty==0) ? currentTotal.totalQty : '--' }}</strong>，
              <span v-if="$hasPermissions('M_shortageStatisticsCList_salesPrice')">本页缺货总金额：<strong>{{ currentTotal && (currentTotal.totalAmount || currentTotal.totalAmount==0) ? toThousands(currentTotal.totalAmount) : '--' }}</strong></span>
            </div>
          </div>
          <div>
            <hideCellMenus :defHiddenKes="defHiddenKes" v-model="hidekey"></hideCellMenus>
          </div>
        </div>
        <!-- 列表 -->
        <v-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+32+'px' }"
          size="small"
          rowKeyName="no"
          :pagination="{pageSize:30}"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          :scroll="{y: tableHeight }"
          bordered>
          <template slot="productCode" slot-scope="text, record">
            <span style="padding-right: 10px;">{{ text }}</span>
            <a-badge count="促" v-if="record.promotionFlag&&record.promotionFlag.indexOf('GIFT')>=0" :number-style="{ backgroundColor: '#52c41a', zoom:'0.8' }"></a-badge>
            <a-badge count="特" v-if="record.promotionFlag&&record.promotionFlag.indexOf('DISCOUNT')>=0" :number-style="{ backgroundColor: '#faad14', zoom:'0.8' }"></a-badge>
          </template>
        </v-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import getDate from '@/libs/getDate.js'
import { VTable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import subarea from '@/views/common/subarea.js'
import Area from '@/views/common/area.js'
import ProductType from '@/views/common/productType.js'
import ProductBrand from '@/views/common/productBrand.js'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import customerService from '@/views/common/customerService'
import dealerType from '@/views/common/dealerType.js'
import hideCellMenus from '@/views/common/hideCellMenus'
import { oosBuyerList, oosBuyerDetailCount, oosBuyerDetailPageCount, oosDetailExport } from '@/api/oos'
export default {
  name: 'ShortageStatisticsCList',
  mixins: [commonMixin],
  components: { VTable, VSelect, hideCellMenus, dealerSubareaScopeList, subarea, Area, rangeDate, ProductBrand, ProductType, chooseWarehouse, customerService, dealerType },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      dealerType: [],
      queryParam: { //  查询条件
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        buyerSn: undefined,
        subareaArea: {
          subareaSn: undefined,
          subareaAreaSn: undefined
        },
        productName: '',
        productCode: '',
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        salesBillNo: '',
        provinceSn: undefined,
        dealerType1: undefined, //  商户类型
        dealerType2: undefined, //  商户类型
        brandType: undefined,
        productBrandSn: undefined,
        state: undefined,
        warehouseSn: undefined,
        bizUserSn: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出loading
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ], //  创建时间
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const paramsPage = Object.assign(this.queryParam, { pageNo: parameter.pageNo, pageSize: parameter.pageSize }) //  有分页
        const params = Object.assign(parameter, this.queryParam) //  无分页
        return oosBuyerList(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
              if (data.list[i].dealerEntity.dealerTypeName1) {
                data.list[i].dealerTypeName = data.list[i].dealerEntity.dealerTypeName1 + '>' + data.list[i].dealerEntity.dealerTypeName2
                data.list[i].offlineReasonType = data.list[i].productEntity.offlineReasonType
                data.list[i].commonCode = data.list[i].productEntity.commonCode
              }
            }
            this.disabled = false
            this.getCount(params)
            this.getCurrentCount(paramsPage)
          }
          this.spinning = false
          return data
        })
      },
      productType: [],
      productTotal: null,
      currentTotal: null,
      defHiddenKes: [
        { title: '操作员', key: 'operatorName', checked: false },
        { title: '缺货说明', key: 'offlineReasonType', checked: false },
        { title: '通用编码', key: 'commonCode', checked: false }
      ],
      hidekey: []
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '区域', dataIndex: 'subareaArea.subareaName', width: 50, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', width: 50, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售单号', dataIndex: 'salesBillNo', width: 100, align: 'center' },
        { title: '省份', dataIndex: 'dealerEntity.provinceName', width: 50, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'dealerEntity.dealerName', width: 120, align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '仓库', dataIndex: 'warehouseName', width: 80, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '创建时间', dataIndex: 'createDate', width: 60, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'productEntity.productBrandName', width: 80, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '二级分类', dataIndex: 'productEntity.productTypeName2', width: 80, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: 180, align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品编码', dataIndex: 'productCode', width: 120, align: 'left', scopedSlots: { customRender: 'productCode' } },
        { title: '单位', dataIndex: 'productEntity.unit', width: 40, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品状态', dataIndex: 'productEntity.stateDictValue', width: 60, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '缺货数量', dataIndex: 'qty', width: 60, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作员', dataIndex: 'operatorName', key: 'operatorName', width: 50, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '缺货说明', dataIndex: 'offlineReasonType', key: 'offlineReasonType', width: 80, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '通用编码', dataIndex: 'commonCode', key: 'commonCode', width: 80, align: 'center', customRender: function (text) { return text || '--' } }
      ]
      if (this.$hasPermissions('M_shortageStatisticsCList_costPrice')) { //  成本价权限
        arr.splice(15, 0, { title: '缺货成本金额', dataIndex: 'totalShowCostAmount', width: 80, align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      if (this.$hasPermissions('M_shortageStatisticsCList_salesPrice')) { //  售价权限
        const ind = this.$hasPermissions('M_shortageStatisticsCList_costPrice') ? 16 : 15
        arr.splice(ind, 0, { title: '缺货实售金额', dataIndex: 'totalRealSaleAmount', width: 80, align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
        arr.splice(ind + 1, 0, { title: '缺货开单金额', dataIndex: 'totalAmount', width: 80, align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      return arr.filter(item => !this.hidekey.includes(item.key))
    }
  },
  methods: {
    //  创建时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    custChange (obj) {
      this.queryParam.buyerSn = obj.key
    },
    // 合计
    getCount (params) {
      oosBuyerDetailCount(params).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    // 本页合计
    getCurrentCount (params) {
      oosBuyerDetailPageCount(params).then(res => {
        if (res.status == 200) {
          this.currentTotal = res.data
        } else {
          this.currentTotal = null
        }
      })
    },
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    getDealerType (v, o) {
      this.queryParam.dealerType1 = v[0]
      this.queryParam.dealerType2 = v[1]
    },
    //  重置
    resetSearchForm () {
      this.dealerType = []
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.buyerSn = undefined
      if (this.advanced) {
        this.$refs.custList.resetForm()
        this.$refs.subarea.clearData()
      }
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.productName = ''
      this.queryParam.productCode = ''
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.salesBillNo = ''
      this.queryParam.provinceSn = undefined
      this.queryParam.dealerType1 = undefined
      this.queryParam.dealerType2 = undefined
      this.queryParam.brandType = undefined
      this.queryParam.productBrandSn = undefined
      this.queryParam.state = undefined
      this.queryParam.warehouseSn = undefined
      this.queryParam.bizUserSn = undefined
      this.productType = []
      this.$refs.table.refresh(true)
    },
    // 详情
    handleDetail (row) {
      this.$router.push({ name: 'salesDetail', params: { sn: row.salesBillSn, type: 'shortageStatisticsC' } })
    },
    //  导出
    handleExport () {
      const _this = this
      _this.$store.state.app.curActionPermission = 'B_oosDetailExportByBuyer'
      const params = this.queryParam
      this.exportLoading = true
      _this.spinning = true
      oosDetailExport(params).then(res => {
        this.exportLoading = false
        _this.spinning = false
        if (res.type == 'application/json') {
          var reader = new FileReader()
          reader.addEventListener('loadend', function () {
            const obj = JSON.parse(reader.result)
            _this.$notification.error({
              message: '提示',
              description: obj.message
            })
          })
          reader.readAsText(res)
        } else {
          this.download(res)
        }
      })
    },
    download (data) {
      this.$store.state.app.curActionPermission = ''
      if (!data) { return }
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      const a = moment().format('YYYYMMDDHHmmss')
      const fname = '缺货统计(按客户)' + a
      link.setAttribute('download', fname + '.xlsx')
      document.body.appendChild(link)
      link.click()
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productTypeSn3 = val[2] ? val[2] : ''
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 210
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$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">
  .shortageStatisticsCList-wrap{
     .sTable{
       margin-top: 10px;
     }
     .tongji-bar{
       display: flex;
       align-items: center;
       justify-content:space-between;
     }
  }
</style>
