<template>
  <div>
    <a-card size="small" :bordered="false" class="tireSalesReportList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="tireSalesReportList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam"
          :rules="rules"
          @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-item label="产品名称">
                <a-input id="inventoryQueryList-productName" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品编码">
                <a-input id="inventoryQueryList-productCode" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="唯一码">
                  <a-input id="inventoryQueryList-productOrigCode" v-model.trim="queryParam.productOrigCode" allowClear placeholder="请输入唯一码"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="售出状态">
                  <v-select
                    v-model="queryParam.dealerLevel"
                    ref="dealerLevel"
                    id="salesOrderTotalList-dealerLevel"
                    code="DEALER_LEVEL"
                    placeholder="请选择售出状态"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="地区">
                  <AreaList id="chooseCustomer-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="所在区域">
                  <subarea id="allocateBillList-subarea" ref="subarea" @change="subareaChange"></subarea>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户名称">
                  <a-input
                    id="salesOrderTotalList-dealerName"
                    v-model.trim="queryParam.dealerName"
                    allowClear
                    placeholder="请输入客户名称" />
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="当前所在客户">
                  <a-input id="inventoryQueryList-productOrigCode" v-model.trim="queryParam.productOrigCode" allowClear placeholder="请输入客户名称"/>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <a-button
                style="margin-left: 5px"
                type="primary"
                @click="handleSearch"
                :disabled="disabled"
                id="salesOrderTotalList-refresh">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetSearchForm"
                :disabled="disabled"
                id="salesOrderTotalList-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_salesOrderTotalExport')"
                id="salesOrderTotalList-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-model>
      </div>
    </a-card>
    <a-card size="small" :bordered="false">
      <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>；
          总销售金额：<strong>{{ totalData&&(totalData.totalPushedAmount || totalData.totalPushedAmount==0) ? toThousands(totalData.totalPushedAmount) : '--' }}</strong>；
          已售出数量（从客户系统销售出库）：<strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '--' }}</strong>；
          已售出金额：<strong>{{ totalData&&(totalData.totalPushedAmount || totalData.totalPushedAmount==0) ? toThousands(totalData.totalPushedAmount) : '--' }}</strong>；
          未售出数量：<strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '--' }}</strong>；
          未售出金额：<strong>{{ totalData&&(totalData.totalPushedAmount || totalData.totalPushedAmount==0) ? toThousands(totalData.totalPushedAmount) : '--' }}</strong>；
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          size="small"
          :rowKey="(record) => record.salesBillNo"
          :style="{ height: tableHeight+70+'px' }"
          rowKeyName="salesBillNo"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight-10 }"
          :defaultLoadData="false"
          bordered>
        </s-table>
      </a-spin>
      <!-- 导出提示框 -->
      <reportModal :visible="showExport" @close="showExport=false"></reportModal>
    </a-card>
  </div>
</template>

<script>
import {
  commonMixin
} from '@/utils/mixin'
import getDate from '@/libs/getDate.js'
import {
  STable,
  VSelect
} from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import subarea from '@/views/common/subarea.js'
import custList from '@/views/common/custList.vue'
import reportModal from '@/views/common/reportModal.vue'
import AreaList from '@/views/common/areaList.js'
import {
  hdExportExcel
} from '@/libs/exportExcel'
import {
  userQueryList
} from '@/api/power-user'
import {
  reportSalesBillList,
  reportSalesBillCount,
  reportSalesBillExport
} from '@/api/reportData'
export default {
  name: 'SalesOrderTotalList',
  mixins: [commonMixin],
  components: {
    STable,
    VSelect,
    rangeDate,
    custList,
    subarea,
    reportModal,
    AreaList
  },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0,
      showExport: false,
      queryParam: { //  查询条件
        time: [
          getDate.getCurrMonthDays().starttime,
          getDate.getCurrMonthDays().endtime
        ],
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        salesBillNo: '',
        dealerName: '',
        dealerLevel: undefined,
        operatorSn: undefined,
        subareaArea: {
          subareaSn: undefined,
          subareaAreaSn: undefined
        },
        dealerProvinceSn: undefined
      },
      rules: {
        'time': [{
          required: true,
          message: '请选择销售日期',
          trigger: 'change'
        }]
      },
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        return reportSalesBillList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            this.getCount(params)
            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
        })
      },
      totalData: null,
      operatorList: [], //  操作员下拉数据
      addrProvinceList: [] //  省下拉
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '地区', dataIndex: 'salesBillNo', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '区域', dataIndex: 'createDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'auditDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'dealerName', width: '12%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '商户类型', dataIndex: 'dealerLevelDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '商户级别', dataIndex: 'directDealerName', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'indirectDealerName', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'totalQty', width: '12%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '唯一码', dataIndex: 'giftQty', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        // { title: '售价（开单金额）', dataIndex: 'totalRealSaleAmount', width: '12%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '出库时间', dataIndex: 'giftQty', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户出库日期', dataIndex: 'giftQty', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '当前所在客户', dataIndex: 'giftQty', width: '12%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '销售状态', dataIndex: 'giftQty', width: '10%', align: 'center', customRender: function (text) { return text || '--' } }
      ]
      if (this.$hasPermissions('M_salesOrderTotalList_salesPrice')) {
        arr.splice(10, 0, { title: '售价（开单金额）', dataIndex: 'totalRealSaleAmount', width: '12%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    // 盘点库存日期
    handleStock () {
      this.$message.info('无盘点区间的起始/终止时间，请自行选择日期区间查询！')
    },
    // 总计
    getCount (params) {
      reportSalesBillCount(params).then(res => {
        if (res.status == 200 && res.data) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择销售日期')
          return false
        }
      })
    },
    //  创建时间  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] || ''
    },
    custChange (val) {
      this.queryParam.dealerSn = val.key
    },
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    //  重置
    resetSearchForm () {
      this.queryParam.time = [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ]
      this.$refs.rangeDate.resetDate(this.queryParam.time)
      this.queryParam.beginDate = getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.salesBillNo = ''
      this.queryParam.dealerName = ''
      this.queryParam.dealerLevel = undefined
      this.queryParam.operatorSn = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.dealerProvinceSn = undefined
      this.totalData = null
      if (this.advanced) {
        this.$refs.subarea.clearData()
      }
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
    },
    //  导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = _this.queryParam
          _this.$store.state.app.curActionPermission = 'B_salesOrderTotalExport'
          _this.showExport = true
          _this.exportLoading = true
          _this.spinning = true
          hdExportExcel(reportSalesBillExport, params, '销售(开单统计)报表', function () {
            _this.exportLoading = false
            _this.spinning = false
            _this.$store.state.app.curActionPermission = ''
          })
        } else {
          return false
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 操作员
    getUserList () {
      userQueryList({}).then(res => {
        if (res.status == 200) {
          this.operatorList = res.data
        } else {
          this.operatorList = []
        }
      })
    },
    pageInit () {
      const _this = this
      _this.getUserList()
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 226
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
