<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <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="客户名称">
                <dealerSubareaScopeList ref="dealerSubareaScopeList" id="examineVerifyList-buyerName" @change="custChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="销售单号">
                <a-input id="examineVerifyList-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="examineVerifyList-dispatchBillNo" v-model.trim="queryParam.dispatchBillNo" allowClear placeholder="请输入备货单号"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="出库单号">
                  <a-input id="examineVerifyList-stockOutNo" v-model.trim="queryParam.stockOutNo" allowClear placeholder="请输入出库单号"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="业务状态">
                  <v-select
                    v-model="queryParam.billStatus"
                    ref="billStatus"
                    id="examineVerifyList-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.printStatus"
                    ref="printStatus"
                    id="examineVerifyList-printStatus"
                    code="PRINT_STATUS"
                    placeholder="请选择打印状态"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="所在区域">
                  <subarea id="examineVerifyList-subarea" ref="subarea" @change="subareaChange"></subarea>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="地区" prop="shippingAddrProvinceSn">
                  <Area id="examineVerifyList-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="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="examineVerifyList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="examineVerifyList-reset">重置</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>

    <a-card size="small" :bordered="false" class="examineVerifyList-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- alert -->
        <div class="tongji-bar">
          <span v-if="$hasPermissions('M_examineVerifyList_salesPrice')">总售价：<strong>{{ totalData&&(totalData.totalAmount || totalData.totalAmount==0) ? toThousands(totalData.totalAmount) : '--' }}</strong>；</span>
          总单数：<strong>{{ totalData&&(totalData.totalRecord || totalData.totalRecord==0) ? totalData.totalRecord : '--' }}</strong>；
          总款数：<strong>{{ totalData&&(totalData.totalCategory || totalData.totalCategory==0) ? totalData.totalCategory : '--' }}</strong>；
          总数量：<strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '--' }}</strong>；
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+70+'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="action" slot-scope="text, record">
            <div>
              <a-button
                size="small"
                type="link"
                class="button-info"
                v-if="record.billStatus=='WAIT_STOCK_UP_AUDIT'&&$hasPermissions('B_dispatchAduit')"
                @click="handleExamine(record)"
                id="examineVerifyList-examine-btn">备货审核</a-button>
              <!-- <a-button
                size="small"
                type="link"
                class="button-info"
                v-if="record.billStatus=='OUTING_WAREHOUSE'&&$hasPermissions('B_dispatchAduit')"
                @click="handleNAudit(record)"
                id="examineVerifyList-examine-btn">反审核</a-button> -->
            </div>
          </template>
        </s-table>
      </a-spin>
      <!-- 审核 -->
      <auditModal
        v-drag
        :openModal="visibleAudit"
        :spinning="spinningAudit"
        @close="visibleAudit=false"
        @ok="auditOrder('OUTING_WAREHOUSE')"
        @fail="auditOrder('STOCK_UP_REJECT')" />
      <auditRejectModal
        v-drag
        :openModal="visibleAuditReject"
        :spinning="spinningAuditReject"
        :itemData="auditInfo"
        @close="visibleAuditReject=false"
        @ok="auditReject" />
      <!-- 查看销售单或备货单详情 -->
      <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>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import commonModal from '@/views/common/commonModal.vue'
import salesDetail from '@/views/salesManagement/salesQueryNew/detail.vue'
import dispatchDetail from '@/views/salesManagement/pushOrderManagement/detail.vue'
import getDate from '@/libs/getDate.js'
import subarea from '@/views/common/subarea.js'
import Area from '@/views/common/area.js'
import rangeDate from '@/views/common/rangeDate.vue'
import auditModal from '@/views/common/auditModal.vue'
import { STable, VSelect } from '@/components'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import auditRejectModal from './auditRejectModal.vue'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import customerService from '@/views/common/customerService'
import { dispatchlBhshList, dispatchQueryBhshCount, dispatchStockUpAduit } from '@/api/dispatch'
export default {
  name: 'ExamineVerifyList',
  mixins: [commonMixin],
  components: { STable, VSelect, dealerSubareaScopeList, rangeDate, commonModal, salesDetail, dispatchDetail, auditModal, subarea, auditRejectModal, Area, chooseWarehouse, customerService },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0,
      showDetailModal: false,
      detailType: 2,
      bizSn: null,
      time: [
        moment(getDate.getThreeMonthDays().starttime, 'YYYY-MM-DD'),
        moment(getDate.getCurrMonthDays().endtime, 'YYYY-MM-DD')
      ],
      queryParam: { //  查询条件
        pushedBeginDate: getDate.getThreeMonthDays().starttime,
        pushedEndDate: getDate.getCurrMonthDays().endtime,
        buyerSn: undefined, //  客户名称
        salesBillNo: '', //  销售单号
        dispatchBillNo: '', // 备货单号
        stockOutNo: '', // 出库单号
        printStatus: undefined, //  打印状态
        billStatus: undefined, //  业务状态
        subareaArea: {
          subareaSn: undefined,
          subareaAreaSn: undefined
        },
        shippingAddrProvinceSn: undefined,
        warehouseSn: undefined,
        bizUserSn: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      selectedRowKeys: [], // Check here to configure the default column
      loading: false,
      totalData: {
        totalAmount: 0,
        totalQty: 0,
        totalRecord: 0
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        // 查询总计
        dispatchQueryBhshCount(Object.assign(parameter, this.queryParam)).then(res => {
          this.totalData = Object.assign(this.totalData, res.data || {})
        })
        return dispatchlBhshList(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
        })
      },
      visibleAudit: false,
      visibleAuditReject: false,
      auditInfo: null,
      spinningAudit: false,
      spinningAuditReject: false
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '下推时间', dataIndex: 'pushedDate', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据来源', dataIndex: 'salesBillEntity.salesBillSourceDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售单号', scopedSlots: { customRender: 'salesBillNo' }, width: '9%', align: 'center' },
        { title: '备货单号', scopedSlots: { customRender: 'dispatchBillNo' }, width: '9%', align: 'center' },
        { title: '出库单号', dataIndex: 'stockOutNo', width: '9%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'buyerName', width: '14%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '数量', dataIndex: 'totalQty', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '售价', dataIndex: 'totalAmount', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '备货时间', dataIndex: 'stockUpDate', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '打印次数', dataIndex: 'stockUpPrintTimes', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ]
      // 仓库管理权限设置是否显示 （当客户有且只有一条仓库管理权限时，不显示仓库信息）
      if (this.isShowWarehouse) {
        arr.splice(7, 0, { title: '仓库', dataIndex: 'warehouseName', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true })
      }
      if (this.$hasPermissions('M_examineVerifyList_salesPrice')) { //  售价权限
        arr.splice(this.isShowWarehouse ? 9 : 8, 0, { title: '售价', dataIndex: 'totalAmount', width: '5%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }

      return arr
    }
  },
  methods: {
    custChange (val) {
      this.queryParam.buyerSn = val.key
    },
    //  时间  change
    dateChange (date) {
      this.queryParam.pushedBeginDate = date[0]
      this.queryParam.pushedEndDate = date[1]
    },
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : undefined
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : undefined
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.pushedBeginDate = getDate.getThreeMonthDays().starttime
      this.queryParam.pushedEndDate = getDate.getCurrMonthDays().endtime
      this.queryParam.buyerSn = undefined
      this.$refs.dealerSubareaScopeList.resetForm()
      this.queryParam.salesBillNo = ''
      this.queryParam.dispatchBillNo = '' // 备货单号
      this.queryParam.stockOutNo = '' // 出库单号
      this.queryParam.billStatus = undefined
      this.queryParam.printStatus = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.warehouseSn = undefined
      this.queryParam.bizUserSn = undefined
      if (this.advanced) {
        this.$refs.subarea.clearData()
      }
      this.$refs.table.refresh(true)
    },
    //  审核
    handleExamine (row) {
      this.auditInfo = row
      this.visibleAudit = true
    },
    // 反审核
    handleNAudit (row) {
      const _this = this
      this.$confirm({
        title: '操作提示',
        content: '该单据状态会改为待备货审核状态，可再次对该单据进行审核操作，确认操作吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          financeBookDgainEditBySn({ bookSn: row.bookSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
            }
            _this.spinning = false
          })
        }
      })
    },
    auditOrder (billStatus) {
      if (billStatus == 'STOCK_UP_REJECT') { // 审核不通过
        // 已对单
        if (this.auditInfo.checkStatus == 'PASS') {
          this.$info({
            title: '操作提示',
            content: '此备货单已经对单通过，不能操作备货审核不通过。'
          })
        } else {
          this.visibleAuditReject = true
        }
      } else {
        const params = {
          dispatchBillSn: this.auditInfo.dispatchBillSn,
          billStatus: billStatus
        }
        this.auditFun(params)
      }
    },
    auditFun (params) {
      this.spinningAudit = true
      this.spinningAuditReject = true
      dispatchStockUpAduit(params).then(res => {
        if (res.status == 200) {
          this.visibleAudit = false
          this.visibleAuditReject = false
          this.$message.success(res.message)
          this.$refs.table.refresh()
          this.spinningAudit = false
          this.spinningAuditReject = false
        } else {
          this.visibleAudit = false
          this.visibleAuditReject = false
          this.spinningAudit = false
          this.spinningAuditReject = false
        }
      })
    },
    // 审核不通过  提交
    auditReject (remarks) {
      const params = {
        dispatchBillSn: this.auditInfo.dispatchBillSn,
        billStatus: 'STOCK_UP_REJECT',
        remarks: remarks
      }
      this.auditFun(params)
    },
    // 详情
    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 = ''
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 228
    }
  },
  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">
  .examineVerifyList-wrap{
    .sTable{
      margin-top: 8px;
    }
  }
</style>
