<template>
  <div class="stockPrint-wrap">
    <!-- 搜索条件 -->
    <a-card class="searchBoxNormal" size="small" :bordered="false">
      <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="stockPrint-buyerName" @change="custChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="销售单号">
                <a-input id="stockPrint-salesBillNo" v-model.trim="queryParam.salesBillNo" allowClear placeholder="请输入销售单号"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="所在区域">
                  <subarea id="stockPrint-subarea" ref="subarea" @change="subareaChange"></subarea>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="业务状态">
                  <v-select
                    v-model="queryParam.billStatus"
                    ref="billStatus"
                    id="stockPrint-billStatus"
                    code="DISPATCH_BILL_STATUS"
                    placeholder="请选择业务状态"
                    allowClear></v-select>
                </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="stockPrint-shbuyerName" @change="shcustChange" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-if="currentTab == 1">
                <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>
              <a-col :md="6" :sm="24" v-if="currentTab == 1">
                <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="备货单号">
                  <a-input id="stockPrint-dispatchBillNo" v-model.trim="queryParam.dispatchBillNo" allowClear placeholder="请输入备货单号"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="地区" prop="shippingAddrProvinceSn">
                  <Area id="stockPrint-shippingAddrProvinceSn" v-model="queryParam.shippingAddrProvinceSn" placeholder="请选择省"></Area>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowWarehouse">
                <a-form-model-item label="仓库">
                  <chooseWarehouse ref="warehouse" v-model="queryParam.warehouseSn" :isPermission="true"></chooseWarehouse>
                </a-form-model-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>
            </template>
            <a-col :md="(currentTab==1&&isShowCustomerSearch)?24:6" :sm="24" :style="{textAlign:(currentTab==1&&isShowCustomerSearch)?'center':''}">
              <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 class="stockPrint-body" size="small" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <div class="flex-center" style="justify-content: space-between;">
          <div style="flex-grow:1;">
            <a-tabs v-model="currentTab" @change="changeTab">
              <a-tab-pane :key="1" tab="全部">
              </a-tab-pane>
              <a-tab-pane :key="2" tab="待打印">
              </a-tab-pane>
            </a-tabs>
          </div>
          <div>
            <hideCellMenus :defHiddenKes="colsArr" v-model="showCols"></hideCellMenus>
          </div>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+84.5+'px'}"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ y:tableHeight }"
          :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">
            <span class="link-bule" v-if="$hasPermissions('B_dispatchDetail')" @click="handleDetail(record,1)">{{ record.dispatchBillNo }}</span>
            <span v-else>{{ record.dispatchBillNo }}</span>
          </template>
          <!-- 发货说明  -->
          <template slot="explainInfo" slot-scope="text, record">
            <span v-if="record.explainInfo" class="link-bule" @click="handleExplainInfo(record)" :title="record.explainInfo">{{ record.explainInfo||'--' }}</span>
            <span v-else>--</span>
          </template>
          <!-- 备货打印状态 -->
          <template slot="printStatus" slot-scope="text, record">
            <span v-if="record.printStatus=='NO_PRINT'&&$hasPermissions('B_noPrintStatus')" class="link-bule" @click="handlePrintStatus(record)">{{ record.printStatusDictValue }}</span>
            <span v-else>{{ record.printStatusDictValue }}</span>
          </template>
          <div slot="costTitle">
            <a-tooltip placement="top">
              <template slot="title">
                如果收货客户名称不为空，则按照收货客户级别的价格计算得到(保价总金额包含所有产品的原售价)。
              </template>
              <span style="margin-right: 5px;">保价总金额</span> <a-icon type="question-circle" />
            </a-tooltip>
          </div>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              v-if="record.printStatus == 'NO_PRINT'&&record.voidFlag==0&&$hasPermissions('B_sendTypePrint')"
              class="button-warning"
              @click="handlePrint(record)"
            >发货分类打印</a-button>
            <a-button
              size="small"
              type="link"
              class="button-warning"
              v-else-if="record.printStatus == 'PRINT'&&$hasPermissions('B_stockPrintRecord')"
              @click="viewPrint(record)"
            >打印记录</a-button>
            <span v-else>--</span>
          </template>
        </s-table>
        <!-- 分类打印 -->
        <sendTypeModal v-drag ref="typePrint" :openModal="showTipModal" @ok="handlePrintOk" @close="showTipModal=false" />
        <!-- 打印记录 -->
        <recordModal v-drag ref="recordModal" modalTit="打印记录" :openModal="showRecordModal" @cancel="showRecordModal=false"></recordModal>
        <!-- 查看销售单或备货单详情 -->
        <commonModal
          :modalTit="detailType?'备货单详情':'销售单详情'"
          bodyPadding="0"
          width="70%"
          :showFooter="false"
          :openModal="showDetailModal"
          @cancel="cancelDetail">
          <salesDetail v-if="detailType==0" ref="salesDetail" :bizSn="bizSn" @close="cancelDetail"></salesDetail>
          <dispatchDetail v-if="detailType==1" ref="dispatchDetail" :bizSn="bizSn" @close="cancelDetail"></dispatchDetail>
        </commonModal>
        <!-- 操作提示 -->
        <commonModal modalTit="操作提示" okText="暂不打印" :openModal="showPrintModal" @cancel="canselModal" @ok="updatePrintStatus">
          <div style="display:flex;flex-direction: column;align-items: center;">
            <div style="margin-bottom: 15px;font-size: 14px;">如需将打印状态回退至<strong>【暂不打印】</strong>,请点击下方按钮</div>
            <div style="line-height: 24px;">
              <div>备货单号：{{ tipData&&tipData.dispatchBillNo }}</div>
              <div>客户名称：{{ tipData&&tipData.buyerName }}</div>
            </div>
          </div>
        </commonModal>
        <!-- 发货说明 -->
        <explainInfoModal v-drag mode="view" :rowData="tipData" :openModal="showInfoModal" @close="canselModal"></explainInfoModal>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import rangeDate from '@/views/common/rangeDate.vue'
import { STable, VSelect } from '@/components'
import subarea from '@/views/common/subarea.js'
import Area from '@/views/common/area.js'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import sendTypeModal from './sendTypeModal.vue'
import recordModal from './recordModal.vue'
import commonModal from '@/views/common/commonModal.vue'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import customerService from '@/views/common/customerService'
import salesDetail from '@/views/salesManagement/salesQueryNew/detail.vue'
import dispatchDetail from '@/views/salesManagement/pushOrderManagement/detail.vue'
import explainInfoModal from '@/views/salesManagement/pushOrderManagement/explainInfoModal.vue'
import hideCellMenus from '@/views/common/hideCellMenus'
import { dispatchlList, dispatchDetailPrint, dispatchPrintStatus } from '@/api/dispatch'
import { printBase64Fun } from '@/libs/JGPrint.js'
export default {
  name: 'StockPrintList',
  mixins: [commonMixin],
  components: { STable, VSelect, hideCellMenus, dealerSubareaScopeList, rangeDate, subarea, sendTypeModal, recordModal, Area, commonModal, salesDetail, dispatchDetail, explainInfoModal, chooseWarehouse, customerService },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      showDetailModal: false,
      detailType: 2,
      bizSn: null,
      tableHeight: 0,
      time: [],
      currentTab: 2,
      // 查询参数
      queryParam: {
        beginDate: '',
        endDate: '',
        buyerSn: undefined, //  客户名称
        receiverSn: undefined, // 收货客户名称
        salesBillNo: '', //  销售单号
        dispatchBillNo: '', //  备货单号
        billStatus: undefined, //  业务状态
        warehouseSn: undefined,
        subareaArea: {
          subareaSn: undefined,
          subareaAreaSn: undefined
        },
        shippingAddrProvinceSn: undefined,
        voidFlag: 0,
        printStatus: 'NO_PRINT',
        bizUserSn: undefined
      },
      showTipModal: false,
      showRecordModal: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        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
        })
      },
      tipData: null,
      showPrintModal: false,
      showInfoModal: false,
      showCols: [],
      colsArr: [
        {
          title: '销售单号',
          key: 'salesBillNo',
          disabled: false,
          checked: false
        },
        {
          title: '仓库',
          key: 'warehouseName',
          disabled: false,
          checked: false
        },
        {
          title: '业务状态',
          key: 'billStatusDictValue',
          disabled: false,
          checked: false
        },
        {
          title: '单据状态',
          key: 'voidFlagDictValue',
          disabled: false,
          checked: false
        },
        {
          title: '允许打印时间',
          key: 'allowPrintTime',
          disabled: false,
          checked: false
        },
        {
          title: '打印次数',
          key: 'stockUpPrintTimes',
          disabled: false,
          checked: false
        }
      ]
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '30px', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '60px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '备货单号', scopedSlots: { customRender: 'dispatchBillNo' }, width: '80px', align: 'center' },
        { title: '发货编号', dataIndex: 'sendNo', width: '30px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '发货说明', scopedSlots: { customRender: 'explainInfo' }, width: '100px', align: 'center', ellipsis: true },
        { title: '客户名称', dataIndex: 'buyerName', width: '120px', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '收货客户名称', dataIndex: 'receiverName', width: '110px', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '产品款数', dataIndex: 'totalCategory', width: '30px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '产品数量', dataIndex: 'totalQty', width: '30px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ]
      arr.splice(2, 0, { title: '销售单号', dataIndex: 'salesBillNo', scopedSlots: { customRender: 'salesBillNo' }, width: '80px', align: 'center' })

      if (this.$hasPermissions('M_stockPrintList_salesPrice')) { //  售价权限
        const ind = this.isShowWarehouse ? 10 : 9
        arr.splice(ind, 0, { title: '开单总金额', dataIndex: 'totalAmount', width: '50px', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
        // arr.splice(ind + 1, 0, { title: '正价总金额', dataIndex: 'normalTotalAmount', width: '50px', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
		    arr.splice(ind + 1, 0, { slots: { title: 'costTitle' }, dataIndex: 'receiveTotalAmount', width: '50px', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
        arr.splice(ind + 2, 0, { title: '易损件售价', dataIndex: 'receiveYsjTotalAmount', width: '50px', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
        arr.splice(ind + 3, 0, { title: '电池售价', dataIndex: 'receiveDcTotalAmount', width: '50px', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
        arr.splice(ind + 4, 0, { title: '机油售价', dataIndex: 'receiveJyTotalAmount', width: '50px', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
        arr.splice(ind + 5, 0, { title: '轮胎售价', dataIndex: 'receiveLtTotalAmount', width: '50px', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      arr.push({ title: '仓库', dataIndex: 'warehouseName', width: '50px', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true })
      arr.push({ title: '业务状态', dataIndex: 'billStatusDictValue', width: '40px', align: 'center', customRender: function (text) { return text || '--' } })
      arr.push({ title: '单据状态', dataIndex: 'voidFlagDictValue', width: '40px', align: 'center', customRender: function (text) { return text || '--' } })
      arr.push({ title: '备货打印状态', width: '40px', align: 'center', scopedSlots: { customRender: 'printStatus' } })
      arr.push({ title: '允许打印时间', dataIndex: 'allowPrintTime', width: '50px', align: 'center', customRender: function (text) { return text || '--' } })
      arr.push({ title: '打印次数', dataIndex: 'stockUpPrintTimes', width: '40px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      arr.push({ title: '操作', scopedSlots: { customRender: 'action' }, width: '60px', align: 'center' })
      return arr.filter(item => !this.showCols.includes(item.dataIndex))
    }
  },
  methods: {
    changeTab (v) {
      this.currentTab = v
      this.resetSearchForm()
    },
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    custChange (val) {
      this.queryParam.buyerSn = val.key
    },
    shcustChange (val) {
      this.queryParam.receiverSn = val.key
    },
    handleDetail (row, type) {
      this.detailType = type
      this.bizSn = type == 0 ? row.salesBillSn : row.dispatchBillSn
      this.$store.state.app.curActionPermission = type == 0 ? 'B_salesDetail' : 'B_dispatchDetail'
      this.showDetailModal = true
    },
    cancelDetail () {
      this.showDetailModal = false
      this.detailType = 2
      this.bizSn = null
      this.$store.state.app.curActionPermission = ''
    },
    // 发货分类打印
    handlePrint (row) {
      this.$refs.typePrint.setData(row, row.dispatchBillSn)
      this.showTipModal = true
    },
    // 发货分类打印
    handlePrintOk (obj, taskName, type) {
      const _this = this
      const params = {
        type: 'DISPATCH_BILL_TYPE',
        dispatchBillSn: obj.dispatchBillSn
      }
      // 货位编号
      if (obj.orderBy) {
        params.type = params.type + '_STACK_PLACE'
      }
      // 原厂编码
      if (obj.origCode == 1) {
        params.type = params.type + '_ORIG_CODE'
      }
      // 装箱号
      if (obj.packNo == 1) {
        params.type = params.type + '_PACK_NUM'
      }
      _this.spinning = true
      printBase64Fun(
        dispatchDetailPrint,
        Object.assign(params, obj || {}),
        type,
        taskName,
        () => {
          _this.$store.state.app.curActionPermission = ''
          _this.$refs.table.refresh(true)
          _this.spinning = false
        },
        {
          billType: 'DISPATCH',
          billSn: params.dispatchBillSn,
          billNo: obj.dispatchBillNo,
          printType: taskName + '打印'
        })
    },
    // 打印记录
    viewPrint (row) {
      this.showRecordModal = true
      this.$refs.recordModal.setData(row, {
        billType: 'DISPATCH',
        billSn: row.dispatchBillSn
      })
    },
    // 允许备货打印
    handlePrintStatus (row) {
      this.tipData = row
      this.showPrintModal = true
    },
    canselModal () {
      this.tipData = null
      this.showPrintModal = false
      this.showInfoModal = false
    },
    updatePrintStatus () {
      dispatchPrintStatus({ dispatchBillSn: this.tipData.dispatchBillSn, printStatus: 'UNABLE_PRINT' }).then(res => {
        if (res.status == 200) {
          this.canselModal()
          this.$message.info(res.message)
          this.$refs.table.refresh()
        }
      })
    },
    // 查看发货说明
    handleExplainInfo (row) {
      this.tipData = row
      this.showInfoModal = true
    },
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    // 重置
    resetSearchForm () {
      this.time = []
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      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.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.shippingAddrProvinceSn = undefined
      this.queryParam.bizUserSn = undefined
      this.queryParam.voidFlag = this.currentTab == 1 ? '' : '0'
      this.queryParam.warehouseSn = undefined
      this.queryParam.printStatus = this.currentTab == 1 ? '' : 'NO_PRINT'
      if (this.advanced) {
        this.$refs.subarea.clearData()
      }
      this.$refs.table.refresh(true)
      this.pageInit()
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 260
    }
  },
  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>
<style lang="less">
  .stockPrint-wrap{
    .sTable{
      margin-top: 10px;
    }
    .stockPrint-body{
      .ant-card-body{
        padding-top:5px;
      }
    }
    .ant-tabs-bar{
      margin:0;
    }
  }
</style>
