<template>
  <div class="jg-page-wrap">
    <a-card size="small" :bordered="false" class="table-page-search-wrapper">
      <!-- 搜索条件 -->
      <a-form-model
        id="salesProfit-form"
        ref="ruleForm"
        class="form-model-con"
        layout="inline"
        :model="queryParam"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        @keyup.enter.native="handleSearch" >
        <a-row :gutter="15">
          <a-col :md="6" :sm="24">
            <a-form-model-item label="创建时间">
              <rangeDate id="salesProfit-creatDate" ref="creatDate" v-model="creatTime" @change="creatDateChange" />
            </a-form-model-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-model-item label="客户名称">
              <custList id="salesProfit-buyerName" ref="custSatelliteList" @change="custSatelliteChange"></custList>
            </a-form-model-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="客户类型">
              <custType id="salesProfit-salesTargetType" v-model="queryParam.salesTargetType" allowClear placeholder="请选择客户类型"></custType>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="收款方式">
                <v-select
                  code="SETTLE_STYLE"
                  id="salesProfit-settleStyleSn"
                  v-model="queryParam.settleStyleSn"
                  allowClear
                  placeholder="请选择收款方式"
                ></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="审核时间">
                <rangeDate id="salesProfit-rangeDate" ref="rangeDate" v-model="time" @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="业务员">
                <a-input id="salesProfit-manName" v-model.trim="queryParam.manName" allowClear placeholder="请输入业务员"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="单号">
                <a-input id="salesProfit-billNo" v-model.trim="queryParam.billNo" allowClear placeholder="请输入单号"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户所在区">
                <AreaList id="salesProfit-areaList" changeOnSelect ref="areaList" @change="areaChange"></AreaList>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="单据类型">
                <a-select id="salesProfit-billType" v-model="queryParam.billType" allowClear placeholder="请选择单据类型">
                  <a-select-option value="SALES_BILL">销售</a-select-option>
                  <a-select-option value="SALES_RETURN">销售退货</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="客户关系">
                <v-select code="CUSTOMER_RELATION_TYPE" id="salesProfit-customerRelationType" v-model="queryParam.customerRelationType" allowClear placeholder="请选择客户关系"></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="急件">
                <v-select
                  v-model="queryParam.urgentBillStatus"
                  ref="status"
                  id="salesProfit-status"
                  code="URGENT_STATUS"
                  placeholder="请选择急件状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="24">
            <a-button type="primary" @click="handleSearch" :disabled="disabled" id="salesProfit-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="salesProfit-reset">重置</a-button>
            <a-button
              type="primary"
              style="margin-left: 5px"
              @click="handleExport"
              :disabled="disabled"
              :loading="exportLoading"
              v-if="$hasPermissions('M_salesProfitExport')"
              class="button-warning"
              id="salesProfit-export-btn">导出</a-button>
            <a @click="advanced=!advanced" style="margin-left: 5px" id="salesProfit-advanced">
              {{ advanced ? '收起' : '展开' }}
              <a-icon :type="advanced ? 'up' : 'down'"/>
            </a>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card size="small" :bordered="false">
      <!-- 合计 -->
      <a-alert type="info" style="margin-bottom:10px">
        <div class="ftext" slot="message">
          总单数：<strong>{{ (totalData && (totalData.totalRecord || totalData.totalRecord==0)) ? totalData.totalRecord : '--' }}</strong>；
          产品总数量：<strong>{{ (totalData && (totalData.totalQty || totalData.totalQty==0)) ? totalData.totalQty : '--' }}</strong>；
          <div style="display: inline-block;" v-if="$hasPermissions('M_ShowAllCost')">
            总成本：<strong>{{ (totalData && (totalData.totalCost || totalData.totalCost==0)) ? toThousands(totalData.totalCost) : '--' }}</strong>；
          </div>
          总售价：<strong>{{ (totalData && (totalData.totalAmount || totalData.totalAmount==0)) ? toThousands(totalData.totalAmount) : '--' }}</strong>；
          折后总售价：<strong>{{ (totalData && (totalData.discountedAmount || totalData.discountedAmount==0)) ? toThousands(totalData.discountedAmount) : '--' }}</strong>；
          <div style="display: inline-block;" v-if="$hasPermissions('M_ShowAllCost')">
            总毛利：<strong>{{ (totalData && (totalData.totalProfit || totalData.totalProfit==0)) ? toThousands(totalData.totalProfit) : '--' }}</strong>。
          </div>
        </div>
      </a-alert>
      <!-- 列表 -->
      <a-spin :spinning="spinning" tip="Loading...">
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.no"
          rowKeyName="no"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          bordered>
        </s-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import { downloadExcel } from '@/libs/JGPrint.js'
import custType from '@/views/common/custType.js'
import AreaList from '@/views/common/areaList.js'
import custList from '@/views/common/custList.vue'
import { reportSalesProfitList, reportSalesProfitCount, reportSalesProfitExport } from '@/api/reportData'
export default {
  components: { STable, VSelect, rangeDate, custList, AreaList, custType },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        createBeginDate: '', // 创建开始时间
        createEndDate: '', // 创建结束时间
        beginDate: '', // 审核开始时间
        endDate: '', // 审核结束时间
        buyerName: undefined, // 客户名称
        buyerSn: undefined, // 客户sn
        salesTargetType: undefined, // 客户类型
        provinceSn: undefined, //  省
        citySn: undefined, //  市
        countySn: undefined, //  区
        settleStyleSn: undefined, // 收款方式
        billNo: '', // 单号
        manName: '', // 销售人员
        billType: undefined, // 单据类型
        customerRelationType: undefined, // 客户关系
        urgentBillStatus: undefined // 急件状态
      },
      creatTime: [], // 创建时间
      time: [], // 审核时间
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, this.queryParam)
        this.spinning = true
        delete params.time
        return reportSalesProfitList(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, //  合计
      addrProvinceList: [], //  省下拉
      addrCityList: [], //  市下拉
      addrDistrictList: [], //  区下拉
      allocateTypeList: [], //  调拨类型
      custTypeList: [] //  客户类型 下拉数据
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '单号', dataIndex: 'billNo', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '急件', dataIndex: 'urgentBillStatusDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'buyerName', width: '20%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '收款方式', dataIndex: 'settleStyleSnDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '款数', dataIndex: 'totalCategory', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '数量', dataIndex: 'totalQty', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '成本', dataIndex: 'totalCost', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总售价', dataIndex: 'totalAmount', width: '7%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '折扣金额', dataIndex: 'discountAmount', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '折后总售价', dataIndex: 'discountedAmount', width: '9%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        // { title: '毛利', dataIndex: 'totalProfit', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '业务员', dataIndex: 'manName', width: '8%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '审核时间', dataIndex: 'auditDate', width: '10%', align: 'center', customRender: function (text) { return text || '--' } }
      ]
      if (this.$hasPermissions('M_ShowAllCost')) {
        arr.splice(7, 0, { title: '总成本', dataIndex: 'totalCost', width: '7%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(11, 0, { title: '毛利', dataIndex: 'totalProfit', width: '7%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr
    }
  },
  methods: {
    // 所在区域
    areaChange (val) {
      this.queryParam.provinceSn = val[0] ? val[0] : undefined
      this.queryParam.citySn = val[1] ? val[1] : undefined
      this.queryParam.countySn = val[2] ? val[2] : undefined
    },
    // 合计
    getCount (params) {
      reportSalesProfitCount(params).then(res => {
        if (res.status == 200) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    // 创建时间
    creatDateChange (date) {
      this.creatTime = date
      this.queryParam.createBeginDate = date[0] || ''
      this.queryParam.createEndDate = date[1] || ''
    },
    //  创建时间  change
    dateChange (date) {
      this.time = date
      this.queryParam.beginDate = date[0] || ''
      this.queryParam.endDate = date[1] || ''
    },
    //  查询
    handleSearch () {
      let hasVal = false
      for (const key in this.queryParam) {
        if (this.queryParam[key]) {
          hasVal = true
          break
        }
      }
      if (hasVal) {
        this.$refs.table.refresh(true)
      } else {
        this.$message.info('请至少输入一个查询条件')
      }
    },
    // 客户名称
    custSatelliteChange (v, row) {
      if (row && row.customerSn) {
        this.queryParam.buyerSn = row.customerSn
        this.queryParam.buyerName = undefined
      } else {
        this.queryParam.buyerName = v
        this.queryParam.buyerSn = undefined
      }
    },
    //  重置
    resetSearchForm () {
      this.$refs.creatDate.resetDate()
      this.creatTime = []
      this.queryParam.createBeginDate = ''
      this.queryParam.createEndDate = ''
      this.queryParam.buyerName = undefined
      this.queryParam.buyerSn = undefined
      this.queryParam.salesTargetType = undefined
      this.queryParam.provinceSn = undefined
      this.queryParam.citySn = undefined
      this.queryParam.countySn = undefined

      this.queryParam.settleStyleSn = undefined
      this.queryParam.showCost = undefined
      this.queryParam.billNo = ''
      this.queryParam.manName = ''
      this.queryParam.billType = undefined
      this.queryParam.customerRelationType = undefined// 客户关系
      this.queryParam.urgentBillStatus = undefined // 急件状态
      this.$refs.ruleForm.resetFields()
      this.totalData = null
      if (this.advanced) {
        this.$refs.rangeDate.resetDate()
        this.time = []
        this.queryParam.beginDate = ''
        this.queryParam.endDate = ''
        this.$refs.custSatelliteList.resetForm()
        this.$refs.areaList.clearData()
      }
      this.$refs.table.clearTable()
    },
    // 导出
    handleExport () {
      const _this = this
      let hasVal = false
      for (const key in this.queryParam) {
        if (this.queryParam[key]) {
          hasVal = true
          break
        }
      }
      if (hasVal) {
        const params = _this.queryParam
        params.showCost = this.$hasPermissions('M_ShowAllCost') ? '1' : '0'
        _this.exportLoading = true
        _this.spinning = true
        reportSalesProfitExport(params).then(res => {
          downloadExcel(res, '销售报表')
          _this.exportLoading = false
          _this.spinning = false
          _this.queryParam.showCost = undefined
        })
      } else {
        this.$message.info('请至少输入一个查询条件')
      }
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.resetSearchForm()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
