<template>
  <div>
    <a-card size="small" :bordered="false" class="sfdetail-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="sfdetail-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 prop="time">
                <div style="display: inline;" slot="label">
                  <a-popover placement="top">
                    <template slot="content">
                      <p>1、销售单（非转单）下推时间</p>
                      <p>2、销售单（转单）转单完结时间</p>
                      <p>3、销售退货单客服确认时间</p>
                    </template>
                    查询日期 <a-icon type="question-circle" />
                  </a-popover>
                </div>
                <rangeDate
                  ref="rangeDate"
                  :value="queryParam.time"
                  id="sfdetail-time"
                  @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="记账主体">
                <custList id="sfdetail-belongDealer" dataAuthFlag="0" placeholder="请输入记账主体" ref="belongDealer" @change="belongDealerChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="业务单号">
                <a-input id="sfdetail-bizNo" v-model.trim="queryParam.bizNo" allowClear placeholder="请输入业务单号"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户名称">
                  <custList id="sfdetail-custName" dataAuthFlag="0" placeholder="请输入客户名称" ref="custList" @change="custChange" />
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="业务类型">
                  <v-select
                    v-model="queryParam.bizType"
                    ref="bizType"
                    id="sfdetail-bizType"
                    code="SUBSIDY_BIZ_TYPE"
                    placeholder="请选择业务类型"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="发货经销商">
                  <custList id="sfdetail-transferDealerSn" dataAuthFlag="0" placeholder="请输入发货经销商" ref="dealerTireScopeList" @change="custTireChange" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="轮胎省仓">
                  <v-select
                    v-model="queryParam.belongProvinceFlag"
                    id="sfdetail-belongProvinceFlag"
                    code="Flag"
                    placeholder="请选择轮胎省仓"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="所在区域">
                  <subarea id="sfdetail-subarea" ref="subarea" @change="subareaChange"></subarea>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="地区">
                  <AreaList id="sfdetail-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <a-button
                type="primary"
                @click="handleSearch"
                :disabled="disabled"
                id="sfdetail-refresh">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetSearchForm"
                :disabled="disabled"
                id="sfdetail-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('M_tireSubsidyExport')"
                id="sfdetail-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"
          rowKeyName="no"
          :style="{ height: tableHeight+70+'px' }"
          :columns="columns"
          :data="loadData"
          :pageSize="30"
          :scroll="{ y: tableHeight-50}"
          :defaultLoadData="false"
          bordered>
          <template slot="footer">
            <a-row :gutter="15">
              <a-col :md="6" :sm="24" v-if="$hasPermissions('M_tireSubsidyList_salesPrice')">服务费金额：{{ (totalData && (totalData.subsidyServiceAmount || totalData.subsidyServiceAmount==0)) ? toThousands(totalData.subsidyServiceAmount): '--' }}</a-col>
              <a-col :md="6" :sm="24">运费补贴金额：{{ (totalData && (totalData.subsidyShippingAmount || totalData.subsidyShippingAmount==0)) ? toThousands(totalData.subsidyShippingAmount): '--' }}</a-col>
            </a-row>
          </template>
        </s-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { hdExportExcel } from '@/libs/exportExcel'
import moment from 'moment'
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 AreaList from '@/views/common/areaList.js'
import custList from '@/views/common/custList.vue'
// 接口
import { subsidyDetailList, subsidyDetailCount, subsidyDetailExport } from '@/api/reportData'
export default {
  name: 'ServiceFreightDetailList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, subarea, AreaList, custList },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      exportLoading: false, // 导出按钮加载状态
      //  查询条件
      queryParam: {
        time: [
          moment(getDate.getCurrMonthDays().starttime, 'YYYY-MM-DD'),
          moment(getDate.getCurrMonthDays().endtime, 'YYYY-MM-DD')
        ], // 日期
        beginDate: getDate.getCurrMonthDays().starttime, // 开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 结束时间
        bizNo: undefined, // 业务单号
        bizType: undefined, // 业务类型
        belongProvinceFlag: undefined, // 是否轮胎省仓
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined // 分区
        },
        dealer: {
          provinceSn: undefined,
          citySn: undefined,
          districtSn: undefined
        },
        belongDealerSn: undefined,
        transferDealerSn: undefined,
        bizDealerSn: undefined
      },
      totalData: null, // 合计
      showOutDetail: false, // 出库明细弹窗
      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 subsidyDetailList(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
            }
            this.disabled = false
            // 获取统计数据
            this.getCount(params)
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  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: '业务单号', dataIndex: 'bizNo', width: '120px', align: 'center', customRender: function (text) { return text || '--' } },
        { 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: 'provinceName', width: '80px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '记账主体', dataIndex: 'belongDealerName', width: '150px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '轮胎省仓', dataIndex: 'belongProvinceFlagDictValue', width: '80px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售数量', dataIndex: 'bizQty', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '服务费比例', dataIndex: 'subsidyServiceDiff', width: '80px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text * 100) + '%' : '--') } },
        { title: '运费补贴', dataIndex: 'subsidyShippingDiff', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '运费补贴金额', dataIndex: 'subsidyShippingAmount', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '客户名称', dataIndex: 'bizDealerName', width: '150px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        // { title: '发货经销商', dataIndex: 'transferDealerName', width: '150px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '业务类型', dataIndex: 'bizTypeDictValue', width: '100px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true }
      ]
      if (_this.$hasPermissions('M_tireSubsidyList_salesPrice')) {
        arr.splice(8, 0, { title: '销售金额', dataIndex: 'bizAmount', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(10, 0, { title: '服务费金额', dataIndex: 'subsidyServiceAmount', width: '100px', 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
    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]
    },
    // 选择发货经销商
    custTireChange (val) {
      this.queryParam.transferDealerSn = val.key
    },
    // 记账主体
    belongDealerChange (val) {
      this.queryParam.belongDealerSn = val.key
    },
    // 客户名称 change
    custChange (val) {
      this.queryParam.bizDealerSn = val.key
    },
    // 统计
    getCount (params) {
      subsidyDetailCount(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
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    //  重置
    resetSearchForm () {
      this.queryParam.time = [
        moment(getDate.getCurrMonthDays().starttime, 'YYYY-MM-DD'),
        moment(getDate.getCurrMonthDays().endtime, 'YYYY-MM-DD')
      ]
      this.$refs.rangeDate.resetDate(this.queryParam.time)
      this.queryParam.beginDate = getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.bizNo = undefined
      this.queryParam.bizType = undefined
      this.queryParam.belongDealerSn = undefined
      this.queryParam.transferDealerSn = undefined
      this.queryParam.bizDealerSn = undefined
      this.queryParam.belongProvinceFlag = undefined
      this.queryParam.dealer.provinceSn = undefined
      this.queryParam.dealer.citySn = undefined
      this.queryParam.dealer.districtSn = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.$refs.belongDealer.resetForm()
      if (this.advanced) {
        this.$refs.dealerTireScopeList.resetForm()
        this.$refs.custList.resetForm()
        this.$refs.subarea.clearData()
        this.$refs.areaList.clearData()
      }
      this.totalData = null
      this.$refs.table.clearTable()
      this.$refs.ruleForm.resetFields()
    },
    //  导出  必填判断
    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.$store.state.app.curActionPermission = 'M_tireSubsidyExport'
      _this.exportLoading = true
      _this.spinning = true
      hdExportExcel(subsidyDetailExport, params, '轮胎服务费运费明细报表-', function () {
        _this.exportLoading = false
        _this.spinning = false
        _this.$store.state.app.curActionPermission = ''
      })
    },
    // 初始化
    pageInit () {
      this.$nextTick(() => { // 页面渲染完成后的回调
        this.setTableH()
      })
      this.resetSearchForm()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 280
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
    }
  }
}
</script>
