<template>
  <a-card size="small" :bordered="false" class="pushOrder-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <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>
            <template v-if="advanced">
              <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>
              <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="printStatus"
                    id="pushOrder-printStatus"
                    code="CHECK_STATUS"
                    placeholder="请选择对单状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="所在区域">
                  <subarea id="pushOrder-subarea" v-model="queryParam.subareaSn"></subarea>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="地区">
                  <a-form-model-item prop="shippingAddrProvinceSn">
                    <Area id="pushOrder-shippingAddrProvinceSn" v-model="queryParam.shippingAddrProvinceSn" placeholder="请选择省"></Area>
                  </a-form-model-item>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <span 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>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- alert -->
      <a-alert type="info" style="margin-bottom:10px">
        <div slot="message">
          下推总单数：<strong>{{ totalData&&(totalData.totalRecord || totalData.totalRecord==0) ? totalData.totalRecord : '--' }}</strong>；
          下推总数量：<strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '--' }}</strong>；
          <span v-if="$hasPermissions('B_isShowPrice')">下推总金额：<strong>{{ totalData&&(totalData.totalAmount || totalData.totalAmount==0) ? toThousands(totalData.totalAmount) : '--' }}</strong>；</span>
        </div>
      </a-alert>
      <!-- 列表 -->
      <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, x:1890 }"
        :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 class="link-bule" @click="handleExplainInfo(record)" :title="record.explainInfo">{{ record.explainInfo||'--' }}</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>
      </s-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="销售单详情"
        bodyPadding="10px"
        width="70%"
        :showFooter="false"
        :openModal="showDetailModal"
        @cancel="showDetailModal = false">
        <salesDetail v-if="showDetailModal" ref="salesDetail" :bizSn="bizSn"></salesDetail>
      </commonModal>
      <!-- 发货说明 -->
      <explainInfoModal v-drag :rowData="tipData" :openModal="showInfoModal" @close="canselModal"></explainInfoModal>
    </a-spin>
  </a-card>
</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 { 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 commonModal from '@/views/common/commonModal.vue'
import salesDetail from '@/views/salesManagement/salesQuery/detail.vue'
import explainInfoModal from './explainInfoModal.vue'
import { dispatchlList, dispatchQueryCount, dispatchPrintStatus } from '@/api/dispatch'
export default {
  name: 'PushOrderManagementList',
  mixins: [commonMixin],
  components: { STable, VSelect, dealerSubareaScopeList, rangeDate, subarea, commonModal, Area, salesDetail, explainInfoModal },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      showDetailModal: false,
      showInfoModal: false,
      bizSn: null,
      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, //  业务状态
        subareaSn: undefined,
        voidFlag: undefined,
        shippingAddrProvinceSn: undefined,
        printStatus: undefined,
        checkStatus: 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 arr = [
        { title: '序号', dataIndex: 'no', width: '60px', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售单号', scopedSlots: { customRender: 'salesBillNo' }, width: '120px', align: 'center' },
        { title: '备货单号', scopedSlots: { customRender: 'dispatchBillNo' }, width: '120px', 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: '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: 'totalAmount', width: '100px', 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', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '备货时间', dataIndex: 'stockUpDate', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '出库时间', dataIndex: 'stockOutDate', width: '100px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '100px', align: 'center', fixed: 'right' }
      ]
      if (this.$hasPermissions('B_isShowPrice')) { //  售价权限
        arr.splice(10, 0, { title: '总售价', dataIndex: 'totalAmount', width: '80px', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      return arr
    }
  },
  methods: {
    //  时间  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) {
      if (type == 0) {
        this.bizSn = row.salesBillSn
        this.showDetailModal = true
      } else {
        this.$router.push({ name: 'pushOrderDetail', params: { sn: row.dispatchBillSn, type: 'pushOrder' } })
      }
    },
    // 查看发货说明
    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.subareaSn = undefined
      this.queryParam.shippingAddrProvinceSn = undefined
      this.queryParam.printStatus = undefined
      this.queryParam.checkStatus = undefined
      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 - 230
    }
  },
  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">
  .pushOrder-wrap{
    .sTable{
      margin-top: 10px;
    }
  }
</style>
