<template>
  <div>
    <!-- 搜索条件 -->
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="下推时间">
                <rangeDate ref="rangeDate" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户名称" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
                <dealerSubareaScopeList ref="dealerSubareaScopeList" id="pushOrder-buyerName" @change="custChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="销售单号">
                <a-input id="pushOrder-salesBillNo" v-model.trim="queryParam.salesBillNo" allowClear placeholder="请输入销售单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="备货单号">
                <a-input id="pushOrder-dispatchBillNo" v-model.trim="queryParam.dispatchBillNo" allowClear placeholder="请输入备货单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="收货客户名称" :label-col="{ span:7 }" :wrapper-col="{ span:17}">
                <dealerSubareaScopeList ref="shbuyerName" id="pushOrder-shbuyerName" @change="shcustChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="业务状态">
                <v-select
                  v-model="queryParam.billStatus"
                  ref="billStatus"
                  id="pushOrder-billStatus"
                  code="DISPATCH_BILL_STATUS"
                  placeholder="请选择业务状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="单据状态">
                <v-select
                  v-model="queryParam.voidFlag"
                  ref="voidFlag"
                  id="pushOrder-voidFlag"
                  code="VOID_FLAG"
                  placeholder="请选择单据状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="备货打印状态">
                  <v-select
                    v-model="queryParam.printStatus"
                    ref="printStatus"
                    id="pushOrder-printStatus"
                    code="PRINT_STATUS"
                    placeholder="请选择备货打印状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="对单状态">
                  <v-select
                    v-model="queryParam.checkStatus"
                    ref="checkStatus"
                    id="pushOrder-checkStatus"
                    code="CHECK_STATUS"
                    placeholder="请选择对单状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="所在区域">
                  <subarea id="pushOrder-subarea" ref="subarea" @change="subareaChange"></subarea>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="地区" prop="shippingAddrProvinceSn">
                  <Area id="pushOrder-shippingAddrProvinceSn" v-model="queryParam.shippingAddrProvinceSn" placeholder="请选择省"></Area>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowWarehouse">
                <a-form-item label="出库仓库">
                  <chooseWarehouse ref="warehouse" v-model="queryParam.warehouseSn" :isPermission="true"></chooseWarehouse>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                <a-form-item label="客服">
                  <customerService ref="customerName" v-model="queryParam.bizUserSn"></customerService>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="新客户首笔订单">
                  <v-select
                    v-model="queryParam.newCustFlag"
                    ref="newCustFlag"
                    id="pushOrder-newCustFlag"
                    code="FLAG"
                    placeholder="请选择是否新客户首笔订单"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <div class="table-page-search-submitButtons">
                <a-button type="primary" :disabled="disabled" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" :disabled="disabled" @click="resetSearchForm()">重置</a-button>
                <a @click="advanced=!advanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </div>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card size="small" :bordered="false" class="pushOrder-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 统计 -->
        <div class="tongji-bar" style="margin-bottom:10px">
          下推总单数：<strong>{{ totalData&&(totalData.totalRecord || totalData.totalRecord==0) ? totalData.totalRecord : '--' }}</strong>；
          下推总数量：<strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '--' }}</strong>；
          <span v-if="$hasPermissions('M_pushOrderManagementList_salesPrice')">下推总金额：<strong>{{ totalData&&(totalData.totalAmount || totalData.totalAmount==0) ? toThousands(totalData.totalAmount) : '--' }}</strong>；</span>
        </div>
        <!-- 列表 -->
        <v-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+35+'px' }"
          :columns="columns"
          :data="loadData"
          :pagination="{pageSize:20}"
          :scroll="{ y:tableHeight, x:1920 }"
          :defaultLoadData="false"
          bordered>
          <!-- 销售单号 -->
          <template slot="salesBillNo" slot-scope="text, record">
            <span class="link-bule" v-if="$hasPermissions('B_salesDetail')" @click="handleDetail(record,0)">{{ record.salesBillNo }}</span>
            <span v-else>{{ record.salesBillNo }}</span>
          </template>
          <!-- 备货单号 -->
          <template slot="dispatchBillNo" slot-scope="text, record">
            <div style="display: flex;align-items: center;justify-content: center;">
              <span class="link-bule" v-if="$hasPermissions('B_dispatchDetail')" @click="handleDetail(record,1)">{{ record.dispatchBillNo }}</span>
              <span v-else>{{ record.dispatchBillNo }}</span>
              <a-badge count="新" v-if="record.newCustFlag==1" :number-style="{ backgroundColor: '#52c41a', zoom:0.8 }"></a-badge>
            </div>
          </template>
          <!-- 发货说明  -->
          <template slot="explainInfo" slot-scope="text, record">
            <span class="link-bule" @click="handleExplainInfo(record)" :title="record.explainInfo">{{ record.explainInfo||'--' }}</span>
          </template>
          <!-- 单据状态 -->
          <template slot="voidFlag" slot-scope="text, record">
            <span :style="{color:record.voidFlag==1?'red':''}">{{ record.voidFlagDictValue||'--' }}</span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <div>
              <a-button
                size="small"
                type="link"
                class="button-warning"
                :loading="!!tipData"
                v-if="(record.printStatus=='UNABLE_PRINT'||record.printStatus=='CANCEL_PRINT')&&record.voidFlag=='0'&&$hasPermissions('B_UNABLE_PRINT')"
                @click="handlePrint(record,1)"
              >允许打印</a-button>
              <a-button
                size="small"
                type="link"
                class="button-error"
                :loading="!!tipData"
                v-if="record.printStatus=='UNABLE_PRINT'&&record.voidFlag=='0'&&$hasPermissions('B_CANSEL_PRINT')"
                @click="handlePrint(record,0)"
              >取消打印</a-button>
            </div>
          </template>
        </v-table>

        <!-- 允许此单进行备货打印操作提示 -->
        <commonModal modalTit="操作提示" :openModal="showTipModal" @cancel="canselModal" @ok="updatePrintStatus">
          <div style="display:flex;flex-direction: column;align-items: center;">
            <div style="margin-bottom: 15px;font-size: 14px;"><strong>{{ tipData&&tipData.printType==1?'确认允许此单进行备货打印吗？':'确认此单取消备货打印吗？' }}</strong></div>
            <div style="line-height: 24px;">
              <div>备货单号：{{ tipData&&tipData.dispatchBillNo }}</div>
              <div>客户名称：{{ tipData&&tipData.buyerName }}</div>
            </div>
          </div>
        </commonModal>

        <!-- 查看销售单或备货单详情 -->
        <commonModal
          modalTit="销售单详情"
          HEAD
          bodyPadding="0"
          width="70%"
          :showFooter="false"
          :openModal="showDetailModal"
          @cancel="closeDetailModal">
          <salesDetail v-if="showDetailModal" ref="salesDetail" :bizSn="bizSn" @close="closeDetailModal"></salesDetail>
        </commonModal>

        <!-- 发货说明 -->
        <explainInfoModal v-drag :rowData="tipData" :openModal="showInfoModal" @close="canselModal"></explainInfoModal>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import getDate from '@/libs/getDate.js'
import rangeDate from '@/views/common/rangeDate.vue'
import { VTable, VSelect } from '@/components'
import subarea from '@/views/common/subarea.js'
import Area from '@/views/common/area.js'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import commonModal from '@/views/common/commonModal.vue'
import salesDetail from '@/views/salesManagement/salesQueryNew/detail.vue'
import explainInfoModal from './explainInfoModal.vue'
import { dispatchlList, dispatchQueryCount, dispatchPrintStatus } from '@/api/dispatch'
import customerService from '@/views/common/customerService'
export default {
  name: 'PushOrderManagementList',
  mixins: [commonMixin],
  components: { VTable, VSelect, dealerSubareaScopeList, rangeDate, subarea, commonModal, Area, salesDetail, explainInfoModal, chooseWarehouse, customerService },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      showDetailModal: false, // 销售单详情弹框
      showInfoModal: false, // 发货说明弹框
      bizSn: null, // 当前操作的销售单sn
      tableHeight: 0, // 表格高度
      time: [
        moment(getDate.getThreeMonthDays().starttime, 'YYYY-MM-DD'),
        moment(getDate.getCurrMonthDays().endtime, 'YYYY-MM-DD')
      ],
      // 查询参数
      queryParam: {
        beginDate: getDate.getThreeMonthDays().starttime, // 开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 结束时间
        buyerSn: undefined, //  客户名称
        receiverSn: undefined, // 收货客户
        salesBillNo: '', //  销售单号
        dispatchBillNo: '', //  备货单号
        billStatus: undefined, //  业务状态
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined // 分区
        },
        voidFlag: undefined, // 单据状态
        shippingAddrProvinceSn: undefined, // 地区 省
        printStatus: undefined, // 备货打印状态
        checkStatus: undefined, // 对单状态
        warehouseSn: undefined, // 仓库
        bizUserSn: undefined, // 客服
        newCustFlag: undefined
      },
      totalData: { // 统计数据
        totalAmount: 0, // 总金额
        totalQty: 0, // 总数量
        totalRecord: 0 // 总条数
      },
      showTipModal: false, // 确认弹框操作提示
      tipData: null, // 发货说明 数据
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        // 查询总计
        dispatchQueryCount(Object.assign(parameter, this.queryParam)).then(res => {
          this.totalData = Object.assign(this.totalData, res.data || {})
        })
        return dispatchlList(Object.assign(parameter, this.queryParam)).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.spinning = false
          return data
        })
      }
    }
  },
  computed: {
    columns () {
      const formatDate = function (text) {
        if (text) {
          const ret = text.split(' ')
          return (<div>{ret[0]}<br/>{ret[1]}</div>)
        }
        return '--'
      }
      const arr = [
        { title: '序号', dataIndex: 'no', width: '40px', align: 'center' },
        { title: '下推时间', dataIndex: 'pushedDate', width: '100px', align: 'center', customRender: function (text) { return formatDate(text) } },
        { title: '销售单号', scopedSlots: { customRender: 'salesBillNo' }, width: '120px', align: 'center' },
        { title: '备货单号', scopedSlots: { customRender: 'dispatchBillNo' }, width: '150px', align: 'center' },
        { title: '发货编号', dataIndex: 'sendNo', width: '80px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '发货说明', scopedSlots: { customRender: 'explainInfo' }, width: '150px', align: 'center', ellipsis: true },
        { title: '客户名称', dataIndex: 'buyerName', width: '150px', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '收货客户名称', dataIndex: 'receiverName', width: '150px', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '出库仓库', dataIndex: 'warehouseName', width: '150px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品款数', dataIndex: 'totalCategory', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '产品数量', dataIndex: 'totalQty', width: '80px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '备货打印状态', dataIndex: 'printStatusDictValue', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '财务状态', dataIndex: 'financialStatusDictValue', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '收款打印状态', dataIndex: 'settlePrintStateDictValue', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '对单状态', dataIndex: 'checkStatusDictValue', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据状态', dataIndex: 'voidFlagDictValue', scopedSlots: { customRender: 'voidFlag' }, width: '100px', align: 'center' },
        { title: '备货时间', dataIndex: 'stockUpDate', width: '100px', align: 'center', customRender: function (text) { return formatDate(text) } },
        { title: '出库时间', dataIndex: 'stockOutDate', width: '100px', align: 'center', customRender: function (text) { return formatDate(text) } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '100px', align: 'center', fixed: 'right' }
      ]
      //  售价权限
      if (this.$hasPermissions('M_pushOrderManagementList_salesPrice')) {
        arr.splice(10, 0, { title: '总售价', dataIndex: 'totalAmount', width: '80px', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      return arr
    }
  },
  methods: {
    //  选择时间
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 客户名称
    custChange (val) {
      this.queryParam.buyerSn = val.key
    },
    // 选择区域
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    // 收货客户名称
    shcustChange (val) {
      this.queryParam.receiverSn = val.key
    },
    // 详情，type 0 销售订单 1 销售退单
    handleDetail (row, type) {
      if (type == 0) {
        this.$store.state.app.curActionPermission = 'B_salesDetail'
        this.bizSn = row.salesBillSn
        this.showDetailModal = true
      } else {
        this.$router.push({ name: 'pushOrderDetail', params: { sn: row.dispatchBillSn, type: 'pushOrder' } })
      }
    },
    // 详情弹框关闭
    closeDetailModal () {
      this.showDetailModal = false
      this.$store.state.app.curActionPermission = ''
    },
    // 查看发货说明
    handleExplainInfo (row) {
      this.tipData = row
      this.showInfoModal = true
    },
    // 允许备货打印
    handlePrint (row, type) {
      this.tipData = row
      this.tipData.printType = type
      this.showTipModal = true
    },
    // 发货说明弹框关闭
    canselModal () {
      this.tipData = null
      this.showTipModal = false
      this.showInfoModal = false
    },
    // 确认允许此单进行备货打印
    updatePrintStatus () {
      dispatchPrintStatus({
        dispatchBillSn: this.tipData.dispatchBillSn,
        printStatus: this.tipData && this.tipData.printType == 1 ? 'NO_PRINT' : 'CANCEL_PRINT'
      }).then(res => {
        if (res.status == 200) {
          this.canselModal()
          this.$message.info(res.message)
          this.$refs.table.refresh()
        }
      })
    },
    // 重置查询
    resetSearchForm () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getThreeMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.buyerSn = undefined
      this.queryParam.receiverSn = undefined
      this.$refs.dealerSubareaScopeList.resetForm()
      this.$refs.shbuyerName.resetForm()
      this.queryParam.salesBillNo = ''
      this.queryParam.dispatchBillNo = ''
      this.queryParam.billStatus = undefined
      this.queryParam.voidFlag = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.shippingAddrProvinceSn = undefined
      this.queryParam.printStatus = undefined
      this.queryParam.checkStatus = undefined
      this.queryParam.warehouseSn = undefined
      this.queryParam.bizUserSn = undefined
      this.queryParam.newCustFlag = undefined

      if (this.advanced) {
        this.$refs.subarea.clearData()
      }
      this.$refs.table.refresh(true)
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 195
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
