<template>
  <div>
    <a-card size="small" :bordered="false" class="tireSalesDealerList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="tireSalesDealerList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :rules="rules"
          :model="queryParam">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="日期" prop="time">
                <rangeDate
                  ref="rangeDate"
                  :showTime="false"
                  :today="false"
                  :value="queryParam.time"
                  id="tireSalesDealerList-time"
                  @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="地区">
                <AreaList id="tireSalesDealerList-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="区域/分区">
                <subarea id="tireSalesDealerList-subarea" ref="subarea" @change="subareaChange"></subarea>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="区域负责人">
                  <BizUser id="tireSalesDealerList-bizUserSn" v-model="queryParam.subareaArea.bizUserSn"></BizUser>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户名称">
                  <dealerSubareaScopeList ref="dealerSubareaScopeList" id="tireSalesDealerList-dealerName" @change="custChange" />
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户级别">
                  <v-select
                    v-model="queryParam.dealer.dealerLevel"
                    ref="dealerLevel"
                    id="tireSalesDealerList-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="是否轮胎省仓">
                  <v-select
                    v-model="queryParam.provinceFlag"
                    id="tireSalesDealerList-provinceFlag"
                    code="Flag"
                    placeholder="请选择是否轮胎省仓"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="轮胎省仓名称">
                  <dealerSubareaScopeList ref="provinceDealerList" placeholder="请输入轮胎省仓名称" id="tireSalesDealerList-parentDealerName" @change="custProvinceChange" />
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                <a-form-model-item label="客服">
                  <customerService ref="customerName" v-model="queryParam.bizUserSn"></customerService>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="isShowCustomerSearch?6:24" :sm="24" :style="{textAlign:isShowCustomerSearch?'left':'center'}">
              <a-button
                style="margin-left: 5px"
                type="primary"
                @click="handleSearch"
                :disabled="disabled"
                id="tireSalesDealerList-refresh">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetSearchForm"
                :disabled="disabled"
                id="tireSalesDealerList-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_tireReportExport')"
                id="tireSalesDealerList-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...">
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          size="small"
          :rowKey="(record) => record.no"
          :style="{ height: tableHeight+70+'px' }"
          rowKeyName="no"
          :columns="columns"
          :data="loadData"
          :scroll="{x:2200, y: tableHeight-110 }"
          :defaultLoadData="false"
          bordered>
          <template slot="addressInfo" slot-scope="text, record">
            {{ record.dealerEntity.provinceName }}{{ '/'+record.dealerEntity.cityName }}{{ '/'+record.dealerEntity.districtName }}
          </template>
          <template slot="footer">
            <a-row :gutter="15">
              <a-col :md="4" :sm="24">总部订货数量：{{ (totalData && (totalData.sysOrderQty || totalData.sysOrderQty==0)) ? totalData.sysOrderQty : '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_tireSalesReportList_salesPrice')">总部订货金额：{{ (totalData && (totalData.sysOrderAmount || totalData.sysOrderAmount==0)) ? toThousands(totalData.sysOrderAmount): '--' }}</a-col>
              <a-col :md="4" :sm="24">上级订货数量：{{ (totalData && (totalData.upOrderQty || totalData.upOrderQty==0)) ?totalData.upOrderQty: '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_tireSalesReportList_salesPrice')">上级订货金额：{{ (totalData && (totalData.upOrderAmount || totalData.upOrderAmount==0)) ? toThousands(totalData.upOrderAmount): '--' }}</a-col>
              <a-col :md="4" :sm="24">跨地区订货数量：{{ (totalData && (totalData.crossRegionQty || totalData.crossRegionQty==0)) ?totalData.crossRegionQty: '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_tireSalesReportList_salesPrice')">跨地区订货金额：{{ (totalData && (totalData.crossRegionAmount || totalData.crossRegionAmount==0)) ? toThousands(totalData.crossRegionAmount): '--' }}</a-col>
              <a-col :md="4" :sm="24">累计入库数量：{{ (totalData && (totalData.putQty || totalData.putQty==0)) ?totalData.putQty: '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_tireSalesReportList_salesPrice')">累计入库金额：{{ (totalData && (totalData.putAmount || totalData.putAmount==0)) ? toThousands(totalData.putAmount): '--' }}</a-col>
              <a-col :md="4" :sm="24">退货数量：{{ (totalData && (totalData.returnQty || totalData.returnQty==0)) ?totalData.returnQty: '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_tireSalesReportList_salesPrice')">退货金额：{{ (totalData && (totalData.returnAmount || totalData.returnAmount==0)) ? toThousands(totalData.returnAmount): '--' }}</a-col>
              <a-col :md="4" :sm="24">客户现有库存数量：{{ (totalData &&totalData.rptDealerStockVO && (totalData.rptDealerStockVO.totalStockQty || totalData.rptDealerStockVO.totalStockQty==0)) ?totalData.rptDealerStockVO.totalStockQty: '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_tireSalesReportList_salesPrice')">客户现有库存金额：{{ (totalData&&totalData.rptDealerStockVO && (totalData.rptDealerStockVO.totalStockAmount || totalData.rptDealerStockVO.totalStockAmount==0)) ? toThousands(totalData.rptDealerStockVO.totalStockAmount): '--' }}</a-col>
              <a-col :md="4" :sm="24">出库加盟商数量：{{ (totalData && (totalData.outQtyDealer || totalData.outQtyDealer==0)) ?totalData.outQtyDealer: '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_tireSalesReportList_salesPrice')">出库加盟商金额：{{ (totalData && (totalData.outAmountDealer || totalData.outAmountDealer==0)) ? toThousands(totalData.outAmountDealer): '--' }}</a-col>
              <a-col :md="4" :sm="24">出库跨区域数量：{{ (totalData && (totalData.crossRegionOutQty || totalData.crossRegionOutQty==0)) ?totalData.crossRegionOutQty: '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_tireSalesReportList_salesPrice')">出库跨区域金额：{{ (totalData && (totalData.crossRegionOutAmount || totalData.crossRegionOutAmount==0)) ? toThousands(totalData.crossRegionOutAmount): '--' }}</a-col>
              <a-col :md="4" :sm="24">出库终端数量：{{ (totalData && (totalData.outQtyTerminal || totalData.outQtyTerminal==0)) ?totalData.outQtyTerminal: '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_tireSalesReportList_salesPrice')">出库终端金额：{{ (totalData && (totalData.outAmountTerminal || totalData.outAmountTerminal==0)) ? toThousands(totalData.outAmountTerminal): '--' }}</a-col>
              <a-col :md="4" :sm="24">累计出库数量：{{ (totalData && (totalData.outQty || totalData.outQty==0)) ?totalData.outQty: '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_tireSalesReportList_salesPrice')">累计出库金额：{{ (totalData && (totalData.outAmount || totalData.outAmount==0)) ? toThousands(totalData.outAmount): '--' }}</a-col>
              <a-col :md="4" :sm="24">已绑质保单数量：{{ (totalData&&totalData.rptDealerStockVO && (totalData.rptDealerStockVO.totalWarrantyQty || totalData.rptDealerStockVO.totalWarrantyQty==0)) ?totalData.rptDealerStockVO.totalWarrantyQty: '--' }}</a-col>
            </a-row>
          </template>
        </s-table>
      </a-spin>
    </a-card>
    <!-- 导出提示框 -->
    <reportModal :visible="showExport" @close="showExport=false"></reportModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { hdExportExcel } from '@/libs/exportExcel'
// 组件
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import subarea from '@/views/common/subarea.js'
import AreaList from '@/views/common/areaList.js'
import BizUser from '@/views/common/bizUser.js'
import reportModal from '@/views/common/reportModal.vue'
import customerService from '@/views/common/customerService'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
// 接口
import { tireReportList, queryTireCount, tireListExport } from '@/api/reportData'
export default {
  name: 'TireSalesDealerList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, subarea, AreaList, BizUser, dealerSubareaScopeList, reportModal, customerService },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出按钮加载状态
      showExport: false, // 导出弹窗
      tableHeight: 0, // 表格高度
      //  查询条件
      queryParam: {
        time: [], // 日期
        bizBeginDate: '', // 开始时间
        bizEndDate: '', // 结束时间
        dealer: {
          provinceSn: undefined, // 省份编码
          citySn: undefined, // 市编码
          districtSn: undefined, // 区编码
          dealerLevel: undefined // 客户等级
        },
        dealerName: undefined, // 客户名称
        dealerSn: undefined, // 客户sn
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined, // 分区
          bizUserSn: undefined // 区域负责人
        },
        parentDealerSn: undefined, // 轮胎省仓sn
        parentDealerName: undefined, // 轮胎省仓名称
        provinceFlag: undefined, // 是否是轮胎省仓 1是 0否
        bizUserSn: undefined// 客服
      },
      rules: {
        'time': [{ required: true, message: '请选择日期', trigger: 'change' }]
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const oldParams = Object.assign(parameter, this.queryParam)
        const params = JSON.parse(JSON.stringify(oldParams))
        delete params.time
        // 获取列表数据  有分页
        return tireReportList(params).then(res => {
          let data
          if (res.status == 200 && res.data) {
            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.disabled = false
            // 获取统计数据
            this.getCount(params)
          }
          this.spinning = false
          return data
        })
      },
      totalData: null
    }
  },
  watch: {
    // 展开关闭
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '40px', align: 'center' },
        { title: '地区', scopedSlots: { customRender: 'addressInfo' }, width: '100px', align: 'center' },
        { title: '区域', dataIndex: 'subareaArea.subareaName', width: '80px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', width: '80px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '区域负责人', dataIndex: 'bizUserName', width: '90px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户名称', dataIndex: 'dealerEntity.dealerName', width: '150px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户级别', dataIndex: 'dealerEntity.dealerLevelDictValue', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '轮胎省仓', dataIndex: 'provinceFlag', width: '80px', align: 'center', customRender: function (text) { return text == '1' ? '是' : '否' } },
        { title: '轮胎省仓名称', dataIndex: 'parentDealerName', width: '150px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '任务数量', dataIndex: 'dealerEntity.taskNum', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总部订货数量', dataIndex: 'sysOrderQty', width: '90px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '上级订货数量', dataIndex: 'upOrderQty', width: '70px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '跨地区订货数量', dataIndex: 'crossRegionQty', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '累计入库数量', dataIndex: 'putQty', width: '90px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '退货数量', dataIndex: 'returnQty', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '客户现有库存数量', dataIndex: 'rptDealerStockVO.totalStockQty', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '出库加盟商数量', dataIndex: 'outQtyDealer', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '出库跨区域数量', dataIndex: 'crossRegionOutQty', width: '70px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '出库终端数量', dataIndex: 'outQtyTerminal', width: '70px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '累计出库数量', dataIndex: 'outQty', width: '70px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: <div>已绑质保单<div>数量</div></div>, dataIndex: 'rptDealerStockVO.totalWarrantyQty', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ]
      if (this.$hasPermissions('M_tireSalesReportList_salesPrice')) {
        arr.splice(10, 0, { title: '授信金额', dataIndex: 'dealerEntity.taskAmount', width: '90px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(12, 0, { title: '总部订货金额', dataIndex: 'sysOrderAmount', width: '90px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(14, 0, { title: '上级订货金额', dataIndex: 'upOrderAmount', width: '90px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(16, 0, { title: '跨地区订货金额', dataIndex: 'crossRegionAmount', width: '80px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(18, 0, { title: '累计入库金额', dataIndex: 'putAmount', width: '90px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(20, 0, { title: '退货金额', dataIndex: 'returnAmount', width: '90px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(22, 0, { title: '客户现有库存金额', dataIndex: 'rptDealerStockVO.totalStockAmount', width: '90px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(24, 0, { title: '出库加盟商金额', dataIndex: 'outAmountDealer', width: '80px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(26, 0, { title: '出库跨区域金额', dataIndex: 'crossRegionOutAmount', width: '80px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(28, 0, { title: '出库终端金额', dataIndex: 'outAmountTerminal', width: '90px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(30, 0, { title: '累计出库金额', dataIndex: 'outAmount', width: '90px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      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
        }
      })
    },
    // 客户名称 change
    custChange (val) {
      this.queryParam.dealerName = val.name
      this.queryParam.dealerSn = val.key
    },
    // 轮胎省仓客户名称 change
    custProvinceChange (val) {
      this.queryParam.parentDealerName = val.name
      this.queryParam.parentDealerSn = val.key
    },
    // 统计
    getCount (params) {
      queryTireCount(params).then(res => {
        if (res.status == 200 && res.data) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    // 地区
    areaChange (val) {
      this.queryParam.dealer.provinceSn = val[0] ? val[0] : undefined
      this.queryParam.dealer.citySn = val[1] ? val[1] : undefined
      this.queryParam.dealer.districtSn = val[2] ? val[2] : undefined
    },
    //  日期选择  change
    dateChange (date) {
      if (date[0] && date[1]) {
        this.queryParam.time = date
      } else {
        this.queryParam.time = []
      }
      this.queryParam.bizBeginDate = date[0] ? date[0].replace(/-/g, '') : ''
      this.queryParam.bizEndDate = date[1] ? date[1].replace(/-/g, '') : ''
    },
    // 区域分区  change
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    //  重置
    resetSearchForm () {
      this.queryParam.time = []
      this.$refs.rangeDate.resetDate()
      this.queryParam.bizBeginDate = ''
      this.queryParam.bizEndDate = ''
      this.queryParam.dealer.provinceSn = undefined
      this.queryParam.dealer.citySn = undefined
      this.queryParam.dealer.districtSn = undefined
      this.queryParam.dealerName = undefined
      this.queryParam.dealerSn = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.subareaArea.bizUserSn = undefined
      this.queryParam.dealer.dealerLevel = undefined
      this.queryParam.parentDealerSn = undefined
      this.queryParam.parentDealerName = undefined
      this.queryParam.provinceFlag = undefined
      this.queryParam.bizUserSn = undefined
      this.totalData = null
      this.$refs.areaList.clearData()
      if (this.advanced) {
        this.$refs.provinceDealerList.resetForm()
        this.$refs.dealerSubareaScopeList.resetForm()
      }

      this.$refs.subarea.clearData()
      this.$refs.table.clearTable()
    },
    //  导出 查询数据必填判断
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.exportList()
        } else {
          _this.$message.error('请选择日期')
          return false
        }
      })
    },
    //  导出
    exportList () {
      const _this = this
      const params = JSON.parse(JSON.stringify(_this.queryParam))
      _this.exportLoading = true
      _this.spinning = true
      _this.showExport = true
      _this.$store.state.app.curActionPermission = 'B_tireReportExport'
      params.exportFlag = 0
      delete params.time
      hdExportExcel(tireListExport, params, '轮胎统计报表', function () {
        _this.exportLoading = false
        _this.spinning = false
        _this.$store.state.app.curActionPermission = ''
      })
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 276
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
