<template>
  <a-card size="small" :bordered="false" class="examineVerifyList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <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-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.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-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="备货单号">
                  <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-model-item label="所在区域">
                  <subarea id="examineVerifyList-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="examineVerifyList-shippingAddrProvinceSn" v-model="queryParam.shippingAddrProvinceSn" placeholder="请选择省"></Area>
                  </a-form-model-item>
                </a-form-model-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>
      <!-- alert -->
      <a-alert type="info" style="margin-bottom:10px">
        <div slot="message">
          <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>
      </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 }"
        :defaultLoadData="false"
        bordered>
        <!-- 下推单号 -->
        <template slot="dispatchBillNo" slot-scope="text, record">
          <span class="link-bule" v-if="$hasPermissions('B_dispatchDetail')" @click="handleDetail(record)">{{ record.dispatchBillNo }}</span>
          <span v-else>{{ record.dispatchBillNo }}</span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <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>
          <span v-else>--</span>
        </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" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
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 { dispatchlBhshList, dispatchQueryBhshCount, dispatchStockUpAduit } from '@/api/dispatch'
export default {
  name: 'ExamineVerifyList',
  mixins: [commonMixin],
  components: { STable, VSelect, dealerSubareaScopeList, rangeDate, auditModal, subarea, auditRejectModal, Area },
  data () {
    return {
      spinning: false,
      advanced: false, // 高级搜索 展开/关闭
      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, //  客户名称
        salesBillNo: '', //  销售单号
        dispatchBillNo: '', // 备货单号
        stockOutNo: '', // 出库单号
        printStatus: undefined, //  打印状态
        billStatus: undefined, //  业务状态
        subareaSn: undefined,
        shippingAddrProvinceSn: 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: 'createDate', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据来源', dataIndex: 'salesBillEntity.salesBillSourceDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售单号', dataIndex: 'salesBillNo', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '备货单号', scopedSlots: { customRender: 'dispatchBillNo' }, width: '12%', align: 'center' },
        { title: '出库单号', dataIndex: 'stockOutNo', width: '12%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'buyerName', width: '11%', 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: '5%', 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.$hasPermissions('M_examineVerifyList_salesPrice')) { //  售价权限
        arr.splice(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.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getThreeMonthDays().starttime
      this.queryParam.endDate = 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.subareaSn = undefined
      this.queryParam.shippingAddrProvinceSn = undefined
      this.$refs.table.refresh(true)
    },
    //  审核
    handleExamine (row) {
      this.auditInfo = row
      this.visibleAudit = true
    },
    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) {
      this.$router.push({ name: 'pushOrderDetail', params: { sn: row.dispatchBillSn, type: 'examineVerify' } })
    },
    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>
