<template>
  <div>
    <a-card size="small" :bordered="false" class="allocationOrderTotalList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="allocationOrderTotalList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam"
          :rules="rules"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          @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="allocationOrderTotalList-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="allocationOrderTotalList-allocateNo" v-model.trim="queryParam.allocateNo" allowClear placeholder="请输入调拨单号"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户名称">
                <a-input id="allocationOrderTotalList-targetName" v-model.trim="queryParam.targetName" allowClear placeholder="请输入客户名称搜索"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户类型">
                  <v-select
                    v-model="queryParam.targetType"
                    id="allocationOrderTotalList-targetType"
                    code="TARGET_TYPE"
                    placeholder="请选择客户类型"
                    allowClear></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="费用/调拨类型">
                  <AllocateType id="allocationOrderTotalList-allocateTypeSn" v-model="allocateTypeVal" :changeOnSelect="true" placeholder="请选择费用/调拨类型" @change="changeAllocatype"></AllocateType>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                <a-form-model-item label="客服">
                  <customerService ref="customerName" id="allocationOrderTotalList-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="allocationOrderTotalList-creatorId"
                    allowClear
                    v-model="queryParam.creatorId"
                    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="新/老客户">
                  <a-select id="allocationOrderTotalList-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&&advanced?24:6" :sm="24" style="margin-bottom: 10px;" :style="{textAlign: isShowCustomerSearch&&advanced?'center':''}">
              <a-button style="margin-left: 5px" type="primary" @click="handleSearch" :disabled="disabled" id="allocationOrderTotalList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="allocationOrderTotalList-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                v-if="$hasPermissions('B_allocationOrderTotalList_export')"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                id="allocationOrderTotalList-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.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          bordered
          :style="{ height: tableHeight+84.5+'px' }"
          :scroll="{ y: tableHeight - 20 }">
          <!-- 调拨类型 -->
          <template slot="allocateType" slot-scope="text, record">
            <div>
              <span>{{ record.allocateSortName||'--' }}</span>
              <span v-if="record.allocateSortName&&record.allocateTypeName">/{{ record.allocateTypeName }}</span>
            </div>
          </template>
          <!-- 费用归属品类 -->
          <template slot="productType" slot-scope="text, record">
            <span v-if="record.productTypeName1">{{ record.productTypeName1 }}{{ record.productTypeName2?'>'+record.productTypeName2:'' }}{{ record.productTypeName3?'>'+record.productTypeName3:'' }}</span>
            <span v-else>--</span>
          </template>
          <template slot="footer">
            <table>
              <tr>
                <td style="width:15%"></td>
                <td style="width:15%"></td>
                <td style="width:20%"></td>
                <td style="width:12%;text-align: center;">总数量：{{ (totalData && (totalData.totalQty || totalData.totalQty==0)) ? totalData.totalQty : '--' }}</td>
                <td style="width:12%;text-align: right;"><span v-if="$hasPermissions('M_allocationOrderTotalList_salesPrice')">总售价：{{ (totalData && (totalData.totalPrice || totalData.totalPrice==0)) ? toThousands(totalData.totalPrice) : '--' }}</span></td>
                <td style="width:12%;text-align: right;"><span v-if="$hasPermissions('M_allocationOrderTotalList_costPrice')">总成本价：{{ (totalData && (totalData.totalCost || totalData.totalCost==0)) ? toThousands(totalData.totalCost) : '--' }}</span></td>
                <td style="width:12%;text-align: right;"><span v-if="$hasPermissions('M_allocationOrderTotalList_costPrice')">总毛利：{{ (totalData && (totalData.totalGrossProfit || totalData.totalGrossProfit==0)) ? toThousands(totalData.totalGrossProfit) : '--' }}</span></td>
                <td style="width:14%"></td>
              </tr>
            </table>
          </template>
        </s-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import getDate from '@/libs/getDate.js'
// 组件
import { STable, VSelect } from '@/components'
import { exportExcel } from '@/libs/JGPrint.js'
import rangeDate from '@/views/common/rangeDate.vue'
import AllocateType from '@/views/common/allocateType.js'
import customerService from '@/views/common/customerService'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
// 接口
import { allocateTypeAllList } from '@/api/allocateType'
import { userQueryList } from '@/api/power-user'
import { allocateReportList, allocateReportCount, allocateReportExportExcel } from '@/api/allocateReport'
export default {
  name: 'AllocationOrderTotalList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, AllocateType, customerService, dealerSubareaScopeList },
  data () {
    return {
      spinning: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      tableHeight: 0, // 表格高度
      advanced: true, // 高级搜索 展开/关闭
      //  查询条件
      queryParam: {
        // 调拨开单日期 默认值
        time: [
          getDate.getCurrMonthDays().starttime,
          getDate.getCurrMonthDays().endtime
        ],
        beginDate: getDate.getCurrMonthDays().starttime, // 开始日期
        endDate: getDate.getCurrMonthDays().endtime, // 结束日期
        allocateNo: '', // 调拨单号
        creatorId: undefined, // 操作员id
        costTypeSn: undefined, // 费用类型
        allocateCategory: undefined, //  调拨类型1
        allocateTypeSn: undefined, //  调拨类型2
        bizUserSn: undefined, // 客服
        targetName: undefined, // 客户名称
        targetType: undefined, // 客户类型
        dealerNewFlag: undefined
      },
      allocateTypeList: [], //  调拨类型
      allocateTypeVal: [], // 已选费用/调拨类型
      operatorList: [], //  操作员下拉数据
      totalData: null, //  合计
      rules: {
        'time': [{ required: true, message: '请选择调拨开单日期', trigger: 'change' }]
      },
      disabled: false, //  查询、重置按钮是否可操作
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, this.queryParam)
        delete params.time
        this.spinning = true
        // 获取列表数据 有分页
        return allocateReportList(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
        })
      }
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '6%', align: 'center' },
        { title: '调拨单号', dataIndex: 'allocateNo', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调拨开单日期', dataIndex: 'allocateDate', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'targetName', width: '20%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户类型', dataIndex: 'targetTypeDictValue', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '费用类型', dataIndex: 'costTypeName', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调拨类型', dataIndex: 'allocateSortName', width: '15%', align: 'center', scopedSlots: { customRender: 'allocateType' } },
        { title: '费用归属品牌', dataIndex: 'productBrandName', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '费用归属品类', dataIndex: 'productTypeName1', width: '15%', align: 'center', scopedSlots: { customRender: 'productType' } },
        { title: '调拨数量', dataIndex: 'totalQty', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
        // { title: '成本价', dataIndex: 'totalCost', width: '12%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '毛利', dataIndex: 'totalGrossProfit', width: '12%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
      ]
      if (this.$hasPermissions('M_allocationOrderTotalList_salesPrice')) { //  成本价权限
        arr.push({ title: '售价', dataIndex: 'totalPrice', width: '10%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions('M_allocationOrderTotalList_costPrice')) { //  成本价权限
        arr.push({ title: '成本价', dataIndex: 'totalCost', width: '10%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.push({ title: '毛利', dataIndex: 'totalGrossProfit', width: '10%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      arr.push({ title: '操作员', dataIndex: 'creatorName', width: '11%', 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: {
    // 费用/调拨类型 change
    changeAllocatype (val, opts) {
      this.allocateTypeVal = val || []
      this.queryParam.costTypeSn = val && val[0] ? val[0] : ''
      this.queryParam.allocateCategory = val && val[1] ? val[1] : ''
      this.queryParam.allocateTypeSn = val && val[2] ? val[2] : ''
    },
    // 盘点库存日期
    handleStock () {
      this.$message.info('无盘点区间的起始/终止时间，请自行选择日期区间查询！')
    },
    //  调拨开单日期  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] || ''
    },
    // 统计
    getCount (params) {
      allocateReportCount(params).then(res => {
        if (res.status == 200) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    //  导出
    handleExport () {
      const _this = this
      const params = this.queryParam
      _this.spinning = true
      _this.exportLoading = true
      _this.$store.state.app.curActionPermission = 'B_allocationOrderTotalList_export'
      exportExcel(allocateReportExportExcel, params, '调拨开单报表', function () {
        _this.spinning = false
        _this.exportLoading = false
        _this.$store.state.app.curActionPermission = ''
      })
    },
    //  查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择调拨开单日期')
          return false
        }
      })
    },
    //  重置
    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.allocateNo = ''
      this.queryParam.creatorId = undefined
      this.queryParam.costTypeSn = undefined
      this.queryParam.allocateCategory = undefined
      this.queryParam.allocateTypeSn = undefined
      this.queryParam.bizUserSn = undefined
      this.queryParam.targetName = undefined
      this.queryParam.targetType = undefined
      this.queryParam.dealerNewFlag = undefined
      this.allocateTypeVal = []
      this.$refs.ruleForm.resetFields()
      this.totalData = null
      this.$refs.table.clearTable()
    },
    //  调拨类型
    getAllocateTypeAllList () {
      allocateTypeAllList().then(res => {
        if (res.status == 200) {
          this.allocateTypeList = res.data
        } else {
          this.allocateTypeList = []
        }
      })
    },
    // 操作员
    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.getAllocateTypeAllList()
      _this.getUserList()
      this.$nextTick(() => {
        _this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 215
    }
  },
  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>
