<template>
  <div>
    <a-card size="small" :bordered="false" class="salesOrderTotalList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="salesOrderTotalList-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="salesOrderTotalList-time" :value="queryParam.time" @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="销售单号">
                <a-input
                  id="salesOrderTotalList-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="客户名称">
                <a-input
                  id="salesOrderTotalList-dealerName"
                  v-model.trim="queryParam.dealerName"
                  allowClear
                  placeholder="请输入客户名称" />
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <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="操作员">
                  <a-select
                    id="salesOrderTotalList-operatorSn"
                    allowClear
                    v-model="queryParam.operatorSn"
                    placeholder="请选择操作员"
                    :showSearch="true"
                    option-filter-prop="children"
                    :filter-option="filterOption">
                    <a-select-option
                      v-for="item in operatorList"
                      :key="item.sn"
                      :value="item.sn">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="所在区域">
                  <subarea id="salesOrderTotalList-subareaSn" ref="subarea" @change="subareaChange"></subarea>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="地区" prop="dealerProvinceSn">
                  <Area
                    id="salesOrderTotalList-dealerProvinceSn"
                    defValKey="id"
                    v-model="queryParam.dealerProvinceSn"
                    placeholder="请选择省"></Area>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                <a-form-model-item label="客服">
                  <customerService id="salesOrderTotalList-bizUserSn" 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="salesOrderTotalList-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
                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 style="margin-bottom:12px;text-align: right;">
          <span>显示：</span>
          <a-tree-select
            size="small"
            v-model="showCols"
            style="min-width: 200px"
            dropdownMatchSelectWidth
            :maxTagCount="3"
            id="salesOrderTotalList-isShowColumn"
            :tree-data="colsArr"
            tree-checkable
            placeholder="请选择要显示的列（多选）"
          />
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          size="small"
          :rowKey="(record) => record.salesBillNo"
          :style="{ height: tableHeight+84.5+'px' }"
          rowKeyName="salesBillNo"
          :columns="columns"
          :data="loadData"
          :pageSize="30"
          :scroll="{ x: 1990, y: tableHeight-32 }"
          :defaultLoadData="false"
          bordered>
          <template slot="footer">
            <a-row :gutter="15">
              <a-col :md="4" :sm="24">下推数量：{{ (totalData && (totalData.totalQty || totalData.totalQty==0)) ? totalData.totalQty : '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_salesOrderTotalList_salesPrice')">实售金额：{{ (totalData && (totalData.totalRealAmount || totalData.totalRealAmount==0)) ? toThousands(totalData.totalRealAmount) : '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_salesOrderTotalList_salesPrice')">开单金额：{{ (totalData && (totalData.totalAmount || totalData.totalAmount==0)) ? toThousands(totalData.totalAmount) : '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_salesOrderTotalList_costPrice')">成本金额：{{ (totalData && (totalData.totalCost || totalData.totalCost==0)) ? toThousands(totalData.totalCost) : '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_salesOrderTotalList_costPrice')&&$hasPermissions('M_salesOrderTotalList_salesPrice')">毛利：{{ (totalData && (totalData.grossProfit || totalData.grossProfit==0)) ? toThousands(totalData.grossProfit) : '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_salesOrderTotalList_salesPrice')">返利：{{ (totalData &&totalData.reportRebateAmountInfo&&(totalData.reportRebateAmountInfo.rebateAmount || totalData.reportRebateAmountInfo.rebateAmount==0)) ? toThousands(totalData.reportRebateAmountInfo.rebateAmount) : '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_salesOrderTotalList_salesPrice')">优惠金额：{{ (totalData && (totalData.discountAmount || totalData.discountAmount==0)) ? toThousands(totalData.discountAmount) : '--' }}</a-col>
            <!-- <a-col :md="4" :sm="24" v-if="$hasPermissions('M_salesOrderTotalList_salesPrice')">折扣金额：{{ (totalData && (totalData.totalDiscountAmount || totalData.totalDiscountAmount==0)) ? toThousands(totalData.totalDiscountAmount) : '--' }}</a-col>
            <a-col :md="4" :sm="24" v-if="$hasPermissions('M_salesOrderTotalList_salesPrice')">折后金额：{{ (totalData && (totalData.totalDiscountedAmount || totalData.totalDiscountedAmount==0)) ? toThousands(totalData.totalDiscountedAmount) : '--' }}</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 custList from '@/views/common/custList.vue'
import reportModal from '@/views/common/reportModal.vue'
import customerService from '@/views/common/customerService.vue'
import Area from '@/views/common/area.js'
// 接口
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, Area, customerService },
  data () {
    return {
      spinning: false,
      advanced: false, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0, // 表格高度
      exportLoading: false, //  导出按钮加载状态
      showExport: false, // 导出到下载中心弹窗
      //  查询参数
      queryParam: {
        // 默认时间
        time: [
          getDate.getCurrMonthDays().starttime,
          getDate.getCurrMonthDays().endtime
        ],
        beginDate: getDate.getCurrMonthDays().starttime, // 开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 结束时间
        salesBillNo: '', // 销售单号
        dealerName: '', // 客户名称
        dealerLevel: undefined, // 客户级别
        operatorSn: undefined, // 操作员sn
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined// 分区
        },
        dealerProvinceSn: undefined, // 省份
        bizUserSn: undefined, // 客服
        dealerNewFlag: undefined // 客户类型
      },
      rules: { 'time': [{ required: true, message: '请选择下推时间', trigger: 'change' }] }, // 查询时间必选项

      // 加载数据方法 必须为 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: [], //  操作员下拉数据
      // 列表列显示
      colsArr: [
        {
          title: '直接差价金额（明细）',
          value: 'directRebateAmountInfo',
          key: 'directRebateAmountInfo',
          disabled: !this.$hasPermissions('M_salesOrderTotalList_salesPrice')
        },
        {
          title: '间接差价金额（明细）',
          value: 'indirectRebateAmountInfo',
          key: 'indirectRebateAmountInfo',
          disabled: !this.$hasPermissions('M_salesOrderTotalList_salesPrice')
        }
      ],
      showCols: []// 已勾选显示的列
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '销售单号', dataIndex: 'salesBillNo', width: 160, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '创建时间', dataIndex: 'createDate', width: 130, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售审核时间', dataIndex: 'auditDate', width: 130, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'dealerName', width: 120, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户级别', dataIndex: 'dealerLevelDictValue', width: 120, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        // { title: '直接绑定客户名称', dataIndex: 'directDealerName', width: 120, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        // { title: '间接绑定客户名称', dataIndex: 'indirectDealerName', width: 120, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '总下推数量', dataIndex: 'totalQty', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '下推数量(促)', dataIndex: 'giftQty', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
        // { title: '实售价', dataIndex: 'totalRealAmount', width: 70, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '开单价', dataIndex: 'totalAmount', width: 70, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '成本价', dataIndex: 'totalCost', width: 70, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '毛利', dataIndex: 'grossProfit', width: 70, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '省级价', dataIndex: 'totalProvinceAmount', width: 70, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '市级价', dataIndex: 'totalCityAmount', width: 70, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '特约加盟店价', dataIndex: 'totalSpecialAmount', width: 90, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '直接差价', dataIndex: 'directRebateAmount', width: 70, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '间接差价', dataIndex: 'indirectRebateAmount', width: 70, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '返利', dataIndex: 'rebateAmount', width: 70, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '折扣金额', dataIndex: 'totalDiscountAmount', width: 70, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '折后金额', dataIndex: 'totalDiscountedAmount', width: 70, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
      ]
      // 根据权限及勾选按原型图固定顺序动态显示列
      if (this.$hasPermissions('M_salesOrderTotalList_salesPrice')) {
        arr.push({ title: '实售金额', dataIndex: 'totalRealAmount', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.push({ title: '开单金额', dataIndex: 'totalAmount', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions('M_salesOrderTotalList_costPrice')) { //  成本价权限
        arr.push({ title: '成本金额', dataIndex: 'totalCost', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.push({ title: '成本金额(促)', dataIndex: 'totalGiftCost', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        if (this.$hasPermissions('M_salesOrderTotalList_salesPrice')) {
          arr.push({ title: '毛利', dataIndex: 'grossProfit', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        }
      }
      if (this.$hasPermissions('M_salesOrderTotalList_provincePrice')) {
        arr.push({ title: '省级金额', dataIndex: 'totalProvinceAmount', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions('M_salesOrderTotalList_cityPrice')) {
        arr.push({ title: '市级金额', dataIndex: 'totalCityAmount', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions('M_salesOrderTotalList_specialPrice')) {
        arr.push({ title: '特约金额', dataIndex: 'totalSpecialAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions('M_salesOrderTotalList_salesPrice')) {
        if (this.showCols.includes('directRebateAmountInfo')) {
          arr.push({ title: '直接上级差价', dataIndex: 'reportRebateAmountInfo.directRebateUpAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
          arr.push({ title: '直接指定差价', dataIndex: 'reportRebateAmountInfo.directRebateAssignAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
          arr.push({ title: '直接总部差价', dataIndex: 'reportRebateAmountInfo.directRebateHeadAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        }
        arr.push({ title: '直接差价金额', dataIndex: 'reportRebateAmountInfo.directRebateAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        if (this.showCols.includes('indirectRebateAmountInfo')) {
          arr.push({ title: '间接上级差价', dataIndex: 'reportRebateAmountInfo.indirectRebateUpAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
          arr.push({ title: '间接指定差价', dataIndex: 'reportRebateAmountInfo.indirectRebateAssignAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
          arr.push({ title: '间接总部差价', dataIndex: 'reportRebateAmountInfo.indirectRebateHeadAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        }
        arr.push({ title: '间接差价金额', dataIndex: 'reportRebateAmountInfo.indirectRebateAmount', width: 90, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.push({ title: '返利', dataIndex: 'reportRebateAmountInfo.rebateAmount', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.push({ title: '优惠金额', dataIndex: 'discountAmount', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      arr.push({ title: '操作员', dataIndex: 'operatorName', width: 100, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true })
      return arr
    }
  },
  watch: {
    // 展开收起
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    // 总计
    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] || ''
    },
    // 所在区域查询
    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.queryParam.bizUserSn = undefined
      this.queryParam.dealerNewFlag = 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
        }
      })
    },
    // 操作员列表获取 无分页
    getUserList () {
      userQueryList({}).then(res => {
        if (res.status == 200) {
          this.operatorList = res.data
        } else {
          this.operatorList = []
        }
      })
    },
    // 操作员列名称筛选
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 初始化
    pageInit () {
      const _this = this
      _this.getUserList()
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算页面高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 252
    }
  },
  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>
