<template>
  <div>
    <a-card size="small" :bordered="false" class="allocationDetailsList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="allocationDetailsList-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="allocationDetailsList-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="allocationDetailsList-productName" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="调拨单号">
                <a-input id="allocationDetailsList-allocateNo" v-model.trim="queryParam.allocateNo" allowClear placeholder="请输入调拨单号"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="所在区域">
                <subarea id="allocationDetailsList-subarea" ref="subarea" @change="subareaChange"></subarea>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="地区">
                <Area id="allocationDetailsList-dealerProvinceSn" v-model="queryParam.dealerProvinceSn" placeholder="请选择省"></Area>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="客户名称">
                <a-input id="allocationDetailsList-dealerName" v-model.trim="queryParam.dealerName" allowClear placeholder="请输入客户名称"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="客户级别">
                <v-select code="DEALER_LEVEL" id="allocationDetailsList-dealerLevel" v-model="queryParam.dealerLevel" allowClear placeholder="请选择客户级别"></v-select>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="品牌分类">
                  <v-select code="BRAND_TYPE" id="allocationDetailsList-productBrandTypeSn" v-model="queryParam.productBrandTypeSn" allowClear placeholder="请选择品牌分类"></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品品牌">
                  <ProductBrand id="allocationDetailsList-productBrandSn" v-model="queryParam.productBrandSn"></ProductBrand>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品编码">
                  <a-input id="allocationDetailsList-productCode" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品分类">
                  <ProductType id="allocationDetailsList-productType" placeholder="请选择产品分类" @change="changeProductType" v-model="productType"></ProductType>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="费用/调拨类型">
                  <AllocateType id="allocationDetailsList-allocateTypeSn" v-model="allocateTypeVal" :changeOnSelect="true" placeholder="请选择费用/调拨类型" @change="changeAllocatype"></AllocateType>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="操作员">
                  <a-select id="allocationDetailsList-creatorId" v-model="queryParam.creatorId" placeholder="请选择操作员" allowClear >
                    <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="出库仓库">
                  <chooseWarehouse ref="warehouse" id="allocationDetailsList-warehouse" isPermission v-model="queryParam.warehouseSn"></chooseWarehouse>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                <a-form-model-item label="客服">
                  <customerService ref="customerName" id="allocationDetailsList-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="allocationDetailsList-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 type="primary" @click="handleSearch" :disabled="disabled" id="allocationDetailsList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="allocationDetailsList-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_allocationDetails_Export')"
                id="allocationDetailsList-export">导出</a-button>
              <a @click="advanced=!advanced">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <!-- 列表 -->
    <a-card size="small" :bordered="false" class="allocationDetailsList-wrap">
      <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"
          :pageSize="30"
          :style="{ height: tableHeight+70+'px' }"
          :scroll="{ x: 2610 ,y: tableHeight-45 }"
          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_allocationDetailsList_costPrice')">总成本价：{{ (totalData && (totalData.totalCost || totalData.totalCost==0)) ? toThousands(totalData.totalCost) : '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_allocationDetailsList_salesPrice')&&$hasPermissions('M_allocationDetailsList_costPrice')">总毛利：{{ (totalData && (totalData.totalGrossProfit || totalData.totalGrossProfit==0)) ? toThousands(totalData.totalGrossProfit) : '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_allocationDetailsList_salesPrice')">总售价：{{ (totalData && (totalData.totalPrice || totalData.totalPrice==0)) ? toThousands(totalData.totalPrice) : '--' }}</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 reportModal from '@/views/common/reportModal.vue'
import subarea from '@/views/common/subarea.js'
import Area from '@/views/common/area.js'
import ProductBrand from '@/views/common/productBrand.js'
import ProductType from '@/views/common/productType.js'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import customerService from '@/views/common/customerService'
import AllocateType from '@/views/common/allocateType.js'
// 接口
import { userQueryList } from '@/api/power-user'
import { allocateTypeAllList } from '@/api/allocateType'
import { allocateReportDetailList, allocateReportDetailCount, allocateReportDetailExport } from '@/api/allocateReport'
export default {
  name: 'AllocationDetailsList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, subarea, Area, ProductBrand, reportModal, AllocateType, ProductType, chooseWarehouse, customerService },
  data () {
    return {
      spinning: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      advanced: false, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出按钮加载状态
      tableHeight: 0, // 表格高度
      showExport: false, // 导出弹窗
      //  查询条件
      queryParam: {
        // 调拨开单日期 默认时间
        time: [
          getDate.getCurrMonthDays().starttime,
          getDate.getCurrMonthDays().endtime
        ],
        beginDate: getDate.getCurrMonthDays().starttime, // 开始日期
        endDate: getDate.getCurrMonthDays().endtime, // 结束日期
        productName: '', // 产品名称
        productBrandTypeSn: undefined, // 产品分类sn
        productBrandSn: undefined, //  产品品牌sn
        productCode: '', // 产品编码
        costTypeSn: undefined, // 费用类型
        allocateSortSn: undefined, //  调拨类型1
        allocateTypeSn: undefined, //  调拨类型2
        creatorId: undefined, // 操作员 id
        allocateNo: '', // 调拨单号
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        dealerName: '', // 客户名称
        dealerLevel: undefined, // 客户等级
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined// 分区
        },
        dealerProvinceSn: undefined, // 地区  省份
        warehouseSn: undefined, // 出库仓库
        bizUserSn: undefined, // 客服
        dealerNewFlag: undefined
      },
      productType: [], // 产品分类
      allocateTypeVal: [], // 已选费用/调拨类型 值
      rules: {
        'time': [{ required: true, message: '请选择调拨开单日期', trigger: 'change' }]
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, this.queryParam)
        delete params.time
        this.spinning = true
        if (params.beginDate) {
          // 获取列表数据  有分页
          return allocateReportDetailList(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
          })
        } else {
          const _this = this
          return new Promise(function (resolve, reject) {
            const data = {
              pageNo: 1,
              pageSize: 10,
              list: [],
              count: 0
            }
            _this.disabled = false
            _this.spinning = false
            _this.$message.info('请选择调拨开单日期')
            resolve(data)
          })
        }
      },
      allocateTypeList: [], //  调拨类型
      operatorList: [], //  操作员下拉数据
      totalData: null //  合计
    }
  },
  computed: {
    columns () {
      const _this = this
      let arr = [
        { title: '区域', dataIndex: 'subareaArea.subareaName', width: 60, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaArea.subareaAreaName', width: 60, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调拨单号', dataIndex: 'allocateNo', width: 160, align: 'center', sorter: true, customRender: function (text) { return text || '--' } },
        { title: '出库仓库', dataIndex: 'warehouseName', width: 150, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '调拨开单日期', dataIndex: 'allocateDate', width: 130, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '省份', dataIndex: 'dealerProvinceName', width: 90, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户名称', dataIndex: 'targetName', width: 120, align: 'center', sorter: true, customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户级别', dataIndex: 'dealerLevelDictValue', width: 120, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '品牌', dataIndex: 'productBrandName', width: 130, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '二级分类', dataIndex: 'productTypeName2', width: 130, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: 260, align: 'left', sorter: true, customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品编码', dataIndex: 'productCode', width: 150, align: 'center', sorter: true, customRender: function (text) { return text || '--' } },
        { title: '调拨数量', dataIndex: 'qty', width: 70, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'productUnit', width: 50, align: 'center', customRender: function (text) { return text || '--' } }
        // { title: '成本价', dataIndex: 'cost', width: 70, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '售价', dataIndex: 'price', 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 : '--') } },
      ]
      if (this.$hasPermissions('M_allocationDetailsList_costPrice')) { //  成本价权限
        arr.push({ title: '成本价', dataIndex: 'cost', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions('M_allocationDetailsList_salesPrice')) { //  售价权限
        arr.push({ title: '售价', dataIndex: 'price', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions('M_allocationDetailsList_costPrice')) { //  成本价权限
        arr.push({ title: '总成本价', dataIndex: 'totalCost', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        if (this.$hasPermissions('M_allocationDetailsList_salesPrice')) {
          arr.push({ title: '毛利', dataIndex: 'grossProfit', width: 70, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        }
      }
      arr = arr.concat([
        { title: '操作员', dataIndex: 'creatorName', width: 100, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '费用类型', dataIndex: 'costTypeName', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调拨类型(一级)', dataIndex: 'allocateSortName', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调拨类型(二级)', dataIndex: 'allocateTypeName', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '费用归属品牌', dataIndex: 'costProductBrandName', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '费用归属品类(二级)', dataIndex: 'costProductTypeName2', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '费用归属品类(三级)', dataIndex: 'costProductTypeName3', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '费用归属部门', dataIndex: 'departmentName', width: 100, align: 'center', customRender: function (text) { return text || '--' } }
      ])
      return arr
    }
  },
  watch: {
    // 展开关闭
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    // 盘点库存日期
    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] || ''
    },
    // 费用/调拨类型 change
    changeAllocatype (val, opts) {
      this.allocateTypeVal = val || []
      this.queryParam.costTypeSn = val && val[0] ? val[0] : ''
      this.queryParam.allocateSortSn = val && val[1] ? val[1] : ''
      this.queryParam.allocateTypeSn = val && val[2] ? val[2] : ''
    },
    // 合计
    getCount (params) {
      allocateReportDetailCount(params).then(res => {
        if (res.status == 200) {
          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
    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.productName = ''
      this.queryParam.productBrandTypeSn = undefined
      this.queryParam.productBrandSn = undefined
      this.queryParam.productCode = ''
      this.queryParam.costTypeSn = undefined
      this.queryParam.allocateSortSn = undefined
      this.queryParam.allocateTypeSn = undefined
      this.queryParam.creatorId = undefined
      this.queryParam.allocateNo = ''
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.dealerName = ''
      this.queryParam.dealerLevel = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.dealerProvinceSn = undefined
      this.queryParam.warehouseSn = undefined
      this.queryParam.bizUserSn = undefined
      this.queryParam.dealerNewFlag = undefined
      this.productType = []
      this.allocateTypeVal = []
      if (this.advanced) {
        this.$refs.subarea.clearData()
      }
      this.$refs.ruleForm.resetFields()
      this.totalData = null
      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_allocationDetails_Export'
          _this.showExport = true
          _this.exportLoading = true
          _this.spinning = true
          hdExportExcel(allocateReportDetailExport, params, '调拨明细报表', function () {
            _this.exportLoading = false
            _this.spinning = false
            _this.$store.state.app.curActionPermission = ''
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productTypeSn3 = val[2] ? val[2] : ''
    },
    //  调拨类型
    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 = []
        }
      })
    },
    // 初始化
    pageInit () {
      this.getAllocateTypeAllList()
      this.getUserList()
      this.resetSearchForm()
      this.setTableH()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 200
    }
  },
  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>
