<template>
  <div>
    <a-card size="small" :bordered="false" class="salesSlipReportList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper newTableSearchName" ref="tableSearch">
        <a-form-model
          id="salesSlipReportList-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" id="salesSlipReportList-time" :value="queryParam.time" @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="客户名称">
                <dealerSubareaScopeList ref="custList" id="salesAmountReportList-dealerSn" @change="custChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="客户级别">
                <v-select
                  v-model="queryParam.dealerLevel"
                  ref="dealerLevel"
                  id="salesSlipReportList-dealerLevel"
                  code="DEALER_LEVEL"
                  placeholder="请选择客户级别"
                  allowClear></v-select>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="销售单号">
                  <a-input id="salesSlipReportList-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="所在区域">
                  <subarea id="salesSlipReportList-subareaSn" ref="subarea" @change="subareaChange"></subarea>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="区域负责人">
                  <BizUser id="salesSlipReportList-bizUserSn" v-model="queryParam.subareaArea.bizUserSn"></BizUser>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="地区">
                  <AreaList id="salesSlipReportList-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                <a-form-model-item label="客服">
                  <customerService id="salesSlipReportList-customerName" ref="customerName" v-model="queryParam.bizUserSn"></customerService>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="新/老客户">
                  <a-select id="salesSlipReportList-dealerNewFlag" v-model="queryParam.dealerNewFlag" placeholder="请选择" allowClear>
                    <a-select-option value="1">新客户</a-select-option>
                    <a-select-option value="0">老客户</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="!isShowCustomerSearch?24:6" :sm="24" style="margin-bottom: 10px;" :style="{textAlign: !isShowCustomerSearch?'center':''}">
              <a-button type="primary" @click="handleSearch" :disabled="disabled" id="salesSlipReportList-refresh">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="salesSlipReportList-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_salesSlip_report')"
                id="salesSlipReportList-export">导出</a-button>
              <a @click="advanced=!advanced" style="margin-left: 8px">
                {{ 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"
          :defaultLoadData="false"
          :rowKey="(record) => record.no"
          rowKeyName="no"
          :columns="columns"
          :data="loadData"
          :pageSize="30"
          :style="{ height: tableHeight+84.5+'px' }"
          :scroll="{ x: 2410,y: tableHeight-136 }"
          bordered>
          <template slot="footer" v-if="countLabel.length||countBrandLabel.length">
            <a-row>
              <a-col span="2">合计：</a-col>
              <a-col span="22">
                <a-row>
                  <a-col span="4" v-for="item in countLabel" :key="item.key">
                    {{ item.title }}：{{ totalData?(totalData[item.dataIndex]||totalData[item.dataIndex]==0)?toThousands(totalData[item.dataIndex]):'--':'--' }}
                  </a-col>
                </a-row>
                <a-row>
                  <a-col span="24" style="padding:8px;"></a-col>
                </a-row>
                <a-row>
                  <a-col span="4" v-for="item in countBrandLabel" :key="item.key">
                    {{ item.title }}：{{ totalData?(totalData[item.dataIndex] ||totalData[item.dataIndex]==0)?toThousands(totalData[item.dataIndex]):'--':'--' }}
                  </a-col>
                </a-row>
              </a-col>
            </a-row>
          </template>
        </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 { hdExportExcel } from '@/libs/exportExcel'
// 组件
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import subarea from '@/views/common/subarea.js'
import reportModal from '@/views/common/reportModal.vue'
import AreaList from '@/views/common/areaList.js'
import BizUser from '@/views/common/bizUser.js'
import customerService from '@/views/common/customerService'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
// 接口
import { salesSlipExport } from '@/api/reportData'
import { salesKdxxdReportTitle, salesBillReportList, salesBillReportCount } from '@/api/salesBillReport'
export default {
  name: 'SalesSlipReportList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, subarea, dealerSubareaScopeList, reportModal, AreaList, BizUser, customerService },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0, // 表格高度
      showExport: false, // 导出弹窗
      exportLoading: false, // 导出按钮加载状态
      //  查询条件
      queryParam: {
        // 默认下推时间
        time: [
          getDate.getCurrMonthDays().starttime,
          getDate.getCurrMonthDays().endtime
        ],
        beginDate: getDate.getCurrMonthDays().starttime, // 开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 结束时间
        salesBillNo: '', //  销售单号
        dealerSn: undefined, // 客户sn
        dealerLevel: undefined, // 客户等级
        provinceSn: undefined, // 省
        citySn: undefined, // 市
        districtSn: undefined, // 区
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined, // 分区
          bizUserSn: undefined// 区域负责人
        },
        bizUserSn: undefined, // 客服
        dealerNewFlag: undefined
      },
      columns: [], // 表格列
      countLabel: [], // 统计品牌数据
      countBrandLabel: [], // 统计分类数据
      totalData: null, // 统计
      rules: {
        'time': [{ required: true, message: '请选择下推时间', trigger: 'change' }]
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const paramsPage = Object.assign(this.queryParam, { pageNo: parameter.pageNo, pageSize: parameter.pageSize })
        // 获取列表数据  有分页
        return salesBillReportList(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
        })
      }
    }
  },
  watch: {
    // 展开关闭
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    //  导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = _this.queryParam
          _this.$store.state.app.curActionPermission = 'B_salesSlip_report'
          _this.showExport = true
          _this.exportLoading = true
          _this.spinning = true
          hdExportExcel(salesSlipExport, params, '开单销售单报表', function () {
            _this.exportLoading = false
            _this.spinning = false
            _this.$store.state.app.curActionPermission = ''
          })
        } else {
          return false
        }
      })
    },
    // 总计
    getCount (params) {
      salesBillReportCount(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] || ''
    },
    // 客户名称  change
    custChange (val) {
      this.queryParam.dealerSn = val.key
    },
    // 区域分区  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 = [
        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.dealerSn = undefined
      this.queryParam.provinceSn = undefined
      this.queryParam.citySn = undefined
      this.queryParam.districtSn = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.subareaArea.bizUserSn = undefined
      this.queryParam.dealerLevel = undefined
      this.queryParam.bizUserSn = undefined
      this.queryParam.dealerNewFlag = undefined
      this.totalData = null
      if (this.advanced) {
        this.$refs.subarea.clearData()
        this.$refs.areaList.clearData()
      }
      this.$refs.custList.resetForm()
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
    },
    // 地区
    areaChange (val) {
      this.queryParam.provinceSn = val[0] ? val[0] : ''
      this.queryParam.citySn = val[1] ? val[1] : ''
      this.queryParam.districtSn = val[2] ? val[2] : ''
    },
    // 获取表头
    async getTableTitle () {
      const _this = this
      const tableTitle = await salesKdxxdReportTitle().then(res => res.data)
      this.columns = tableTitle.list
      this.countLabel = tableTitle.count.filter(item => item.title.indexOf('品牌') < 0)
      this.countBrandLabel = tableTitle.count.filter(item => item.title.indexOf('品牌') >= 0)
      this.columns.map(item => {
        let mw = 20
        if (item.customRender == 'amount') {
          mw = 15
          item.customRender = function (text) { return (text || text == 0) ? _this.toThousands(text) : '--' }
        } else {
          item.customRender = function (text) { return text || '--' }
        }
        const w = item.title.length * mw
        const tw = w <= 80 ? mw * 5 : w
        item.width = tw + 'px'
        this.tableWidth = this.tableWidth + tw
      })
      this.resetSearchForm()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 215
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.getTableTitle()
      this.setTableH()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.getTableTitle()
      this.setTableH()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
