<template>
  <div>
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 选项卡切换 -->
      <a-tabs v-model="activeKey" @change="callback" :tabBarStyle="{'background':'#fff'}">
        <a-tab-pane :key="item.id" :tab="item.name" v-for="item in tabsList">
        </a-tab-pane>
      </a-tabs>
      <a-card size="small">
        <!-- 搜索条件 -->
        <div class="table-page-search-wrapper newTableSearchName" ref="tableSearch">
          <a-form-model
            id="regionTypeSalesList-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 id="regionTypeSalesList-time" ref="rangeDate" :value="queryParam.time" @change="dateChange"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="销售状态" prop="salesStatusType">
                  <v-select
                    id="regionTypeSalesList-salesStatusType"
                    v-model="queryParam.salesStatusType"
                    code="SALES_STATUS"
                    placeholder="请选择销售状态"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24" v-if="activeKey==0">
                <a-form-model-item label="所在区域">
                  <subarea id="regionTypeSalesList-subarea" ref="subarea" @change="subareaChange"></subarea>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="区域负责人">
                  <BizUser id="regionTypeSalesList-bizUserSn" v-model="queryParam.subareaArea.bizUserSn"></BizUser>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                <a-form-model-item label="客服">
                  <customerService id="regionTypeSalesList-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="regionTypeSalesList-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>
              <a-col :md="(activeKey==1&&!isShowCustomerSearch)?24:6" :sm="24" style="margin-bottom: 10px;" :style="{textAlign:(activeKey==1&&!isShowCustomerSearch)?'center':'left'}">
                <a-button type="primary" @click="handleSearch" :disabled="disabled" id="regionTypeSalesList-refresh">查询</a-button>
                <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="regionTypeSalesList-reset">重置</a-button>
                <a-button
                  style="margin-left: 5px"
                  type="primary"
                  class="button-warning"
                  @click="handleExport"
                  :disabled="disabled"
                  :loading="exportLoading"
                  v-if="$hasPermissions('B_regionTypeSalesReportExport')"
                  id="regionTypeSalesList-export">导出</a-button>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
      </a-card>
      <!-- 列表 -->
      <a-card size="small" style="margin-top:4px!important">
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :defaultLoadData="false"
          :rowKey="(record) => record.no"
          rowKeyName="no"
          :columns="columns"
          :data="loadData"
          :showPagination="false"
          :style="{ height: tableHeight+84.5+'px' }"
          :scroll="{ x:1550,y: tableHeight +30}"
          bordered>
        </s-table>
      </a-card>
    </a-spin>
    <!-- 导出提示框 -->
    <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 BizUser from '@/views/common/bizUser.js'
import reportModal from '@/views/common/reportModal.vue'
import customerService from '@/views/common/customerService.vue'
// 接口
import { realReportSalesByProvince, realReportSalesByProvinceExport, subareaAreaReportTitle, subareaReportTitle, realReportSalesBySubArea, realReportSalesBySubAreaExport } from '@/api/reportData.js'
export default {
  name: 'RegionTypeSalesReportList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, subarea, reportModal, BizUser, customerService },
  data () {
    return {
      spinning: false,
      activeKey: 0, // 切换显示页面值 0 各分区品类实售明细 1各区域品类实售明细
      advanced: true, // 高级搜索 展开/关闭
      showExport: false, // 导出弹窗
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出按钮加载状态
      tableHeight: 0, // 表格高度
      tabsList: [{ id: 0, name: '各分区品类实售明细' }, { id: 1, name: '各区域品类实售明细' }], // tab切换data
      salesStatusTypeList: [{ code: 'SALES', name: '实售销售' }, { code: 'SALES_RETURN', name: '实售退货' }, { code: 'REAL_SALES', name: '实际销售' }],
      columns: [], // 表头数据
      totalData: null, // 统计
      // 查询参数
      queryParam: {
        time: [], // 默认时间
        beginDate: '', // 开始时间
        endDate: '', // 结束时间
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined, // 分区
          bizUserSn: undefined// 区域负责人
        },
        salesStatusType: 'REAL_SALES', // 销售状态
        bizUserSn: undefined, // 客服
        dealerNewFlag: undefined
      },
      rules: {
        'time': [{ required: true, message: '请选择时间', trigger: 'change' }],
        'salesStatusType': [{ required: true, message: '请选择销售状态', trigger: 'change' }]
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const paramsPage = Object.assign(this.queryParam)
        const jkUrl = this.activeKey == 0 ? realReportSalesByProvince : realReportSalesBySubArea
        // 获取列表数据 无分页 0各分区品类实售明细列表 1各区域品类实售明细列表
        return jkUrl(paramsPage).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            data.map((item, index) => {
              item.no = index + 1
            })
          }
          this.disabled = false
          this.spinning = false
          return data
        })
      }
    }
  },
  methods: {
    // tabs切换  change时间
    callback (key) {
      this.activeKey = key
      const _this = this
      _this.$nextTick(() => {
        this.getTableTitle()
        this.setTableH()
      })
    },
    //  创建时间  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] || ''
    },
    // 查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择时间和销售状态')
          return false
        }
      })
    },
    // 区域分区
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    //  重置
    resetSearchForm () {
      this.$refs.ruleForm.resetFields()
      this.queryParam.time = []
      this.$refs.rangeDate.resetDate(this.queryParam.time)
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.subareaArea.bizUserSn = undefined
      this.queryParam.bizUserSn = undefined
      this.queryParam.dealerNewFlag = undefined
      this.queryParam.salesStatusType = 'REAL_SALES'
      if (this.activeKey == 0) {
        this.$refs.subarea.clearData()
      }
      this.$refs.table.clearTable()
    },
    //  导出
    handleExport () {
      const _this = this
      const jkUrl = _this.activeKey == 0 ? realReportSalesByProvinceExport : realReportSalesBySubAreaExport
      const excelTitle = _this.activeKey == 0 ? '各省品类实售明细报表' : '各区品类实售明细报表'
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = _this.queryParam
          _this.$store.state.app.curActionPermission = 'B_regionTypeSalesReportExport'
          _this.showExport = true
          _this.exportLoading = true
          _this.spinning = true
          hdExportExcel(jkUrl, params, excelTitle, function () {
            _this.exportLoading = false
            _this.spinning = false
            _this.$store.state.app.curActionPermission = ''
          })
        } else {
          return false
        }
      })
    },
    // 获取表头
    async getTableTitle () {
      const _this = this
      const titUrl = _this.activeKey == 0 ? subareaAreaReportTitle : subareaReportTitle
      const tableTitle = await titUrl().then(res => res.data)
      this.columns = tableTitle.list
      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()
    },
    // 初始化
    pageInit () {
      this.activeKey = 0
      this.getTableTitle()
      this.setTableH()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 250
    }
  },
  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>
<style lang="less" scoped>
  /deep/.ant-card.ant-card-bordered.ant-card-small{
    margin-top:-12px !important;
    .ant-card-body{
      padding-bottom: 0;
    }
  }
</style>
