<template>
  <a-card size="small" :bordered="false" class="bulkReturnGoodsList-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="散件退货单号">
                <a-input id="bulkReturnGoodsList-sparePartsReturnNo" v-model.trim="queryParam.sparePartsReturnNo" 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}">
                <a-select
                  id="bulkReturnGoodsList-supplierSn"
                  placeholder="请选择供应商"
                  allowClear
                  v-model="queryParam.supplierSn"
                  :showSearch="true"
                  option-filter-prop="children"
                  :filter-option="filterOption">
                  <a-select-option v-for="item in supplierList" :key="item.supplierSn" :value="item.supplierSn">{{ item.supplierName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="是否抓单">
                  <v-select code="FLAG" id="bulkReturnGoodsList-isGrab" v-model="queryParam.isGrab" allowClear placeholder="请选择"></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="业务状态">
                  <v-select code="SPARE_PARTS_RETURN" id="bulkReturnGoodsList-state" v-model="queryParam.state" allowClear placeholder="请选择"></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="财务状态">
                  <v-select code="FINANCIAL_RECEIVE_STATUS" id="bulkReturnGoodsList-settleState" v-model="queryParam.settleState" allowClear placeholder="请选择"></v-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="bulkReturnGoodsList-refresh">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="bulkReturnGoodsList-reset">重置</a-button>
              <a @click="advanced=!advanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 操作按钮 -->
      <div class="table-operator">
        <a-button id="bulkReturnGoodsList-add" v-if="$hasPermissions('B_bulkReturnGoodsAdd')" type="primary" class="button-error" @click="handleAdd()">新增</a-button>
      </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="sparePartsReturnNo" slot-scope="text, record">
          <span style="color: #ed1c24;cursor: pointer;" v-if="$hasPermissions('B_bulkReturnGoodsDetail')" @click="handleDetail(record)">{{ record.sparePartsReturnNo }}</span>
          <span v-else>{{ record.sparePartsReturnNo }}</span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            v-if="(record.state == 'WAIT_SUBMIT' || record.state == 'AUDIT_REJECT') && $hasPermissions('B_bulkReturnGoodsEdit')"
            @click="handleEdit(record)"
            class="button-info"
            id="bulkReturnGoodsList-edit-btn">编辑</a-button>
          <a-button
            size="small"
            type="link"
            v-if="record.state == 'WAIT_OUT_WAREHOUSE' && $hasPermissions('B_bulkReturnGoodsOutStock')"
            @click="handleWarehouse(record)"
            class="button-primary"
            id="bulkReturnGoodsList-warehouse-btn">出库</a-button>
          <a-button
            size="small"
            type="link"
            v-if="record.state == 'WAIT_AUDIT' && $hasPermissions('B_bulkReturnGoodsAudit')"
            @click="handleEexamine(record)"
            class="button-primary"
            id="bulkReturnGoodsList-warehouse-btn">审核</a-button>
          <a-button
            size="small"
            type="link"
            v-if="(record.state == 'WAIT_SUBMIT' || record.state == 'AUDIT_REJECT') && $hasPermissions('B_bulkReturnGoodsDel')"
            @click="handleDel(record)"
            class="button-error"
            id="bulkReturnGoodsList-del-btn">删除</a-button>
          <span v-if="!((record.state == 'WAIT_SUBMIT' || record.state == 'AUDIT_REJECT') && ($hasPermissions('B_bulkReturnGoodsEdit') || $hasPermissions('B_bulkReturnGoodsDel'))) && !(record.state == 'WAIT_OUT_WAREHOUSE' && $hasPermissions('B_bulkReturnGoodsOutStock')) && !(record.state == 'WAIT_AUDIT' && $hasPermissions('B_bulkReturnGoodsAudit'))">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 选择基本信息弹框 -->
    <basic-info-modal :openModal="openModal" @ok="handleOk" @close="openModal=false" />
    <!-- 详情 -->
    <bulkReturnGoods-detail-modal :openModal="openDetailModal" :itemSn="itemSn" :isGrab="isGrab" @close="handleDetailClose" />
    <!-- 审核 -->
    <auditModal :openModal="visibleAudit" :spinning="spinningAudit" @close="visibleAudit=false" @ok="auditOrder(true)" @fail="auditOrder(false)" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import basicInfoModal from './basicInfoModal.vue'
import bulkReturnGoodsDetailModal from './detailModal.vue'
import rangeDate from '@/views/common/rangeDate.vue'
import getDate from '@/libs/getDate.js'
import auditModal from '@/views/common/auditModal.vue'
import { supplierAllList } from '@/api/supplier'
import { sparePartsRetList, sparePartsRetDel, sparePartsRetOutStock, sparePartsRetAudit } from '@/api/sparePartsRet'
export default {
  name: 'BulkReturnGoodsList',
  components: { STable, VSelect, basicInfoModal, rangeDate, bulkReturnGoodsDetailModal, auditModal },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0,
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      queryParam: { //  查询条件
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime,
        sparePartsReturnNo: '', //  散件退货单号
        supplierSn: undefined, //  供应商
        isGrab: undefined,
        settleState: undefined,
        state: undefined
      },
      disabled: false, //  查询、重置按钮是否可操作
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '散件退货单号', scopedSlots: { customRender: 'sparePartsReturnNo' }, width: '16%', align: 'center' },
        { title: '供应商', dataIndex: 'supplierName', width: '13%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品款数', dataIndex: 'productTotalCategory', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总数量', dataIndex: 'productTotalQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总金额', dataIndex: 'productTotalCost', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '是否抓单', dataIndex: 'isGrabDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'stateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '财务状态', dataIndex: 'settleStateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '创建时间', dataIndex: 'createDate', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '出库时间', dataIndex: 'outStockTime', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '9%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return sparePartsRetList(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
        })
      },
      supplierList: [], //  供应商列表数据
      openModal: false, // 基本信息弹框是否显示
      openDetailModal: false,
      itemSn: null,
      isGrab: null,
      visibleAudit: false,
      auditInfo: null,
      spinningAudit: false
    }
  },
  methods: {
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    //  重置
    resetSearchForm () {
      this.resetData()
      this.$refs.table.refresh(true)
    },
    // 重置数据
    resetData () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.sparePartsReturnNo = ''
      this.queryParam.supplierSn = undefined
      this.queryParam.isGrab = undefined
      this.queryParam.settleState = undefined
      this.queryParam.state = undefined
    },
    //  基本信息  保存
    handleOk (data) {
      this.handleEdit(data)
    },
    //  新增
    handleAdd () {
      this.openModal = true
    },
    //  编辑
    handleEdit (row) {
      if (row.isGrab == 1) {
        this.$router.push({ name: 'bulkReturnGoodsGrabEdit', params: { id: row.id, sn: row.sparePartsReturnSn, supplierSn: row.supplierSn } })
      } else {
        this.$router.push({ name: 'bulkReturnGoodsEdit', params: { id: row.id, sn: row.sparePartsReturnSn } })
      }
    },
    //  详情
    handleDetail (row) {
      this.itemSn = row.sparePartsReturnSn
      this.isGrab = row.isGrab
      this.openDetailModal = true
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          sparePartsRetDel({
            id: row.id
          }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
            }
          })
        }
      })
    },
    //  入库
    handleWarehouse (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确定要出库吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          sparePartsRetOutStock({ id: row.id }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  审核
    handleEexamine (row) {
      this.auditInfo = row
      this.visibleAudit = true
    },
    auditOrder (billStatus) {
      this.spinningAudit = true
      sparePartsRetAudit({
        sparePartsReturnSnList: [ this.auditInfo.sparePartsReturnSn ],
        auditFlag: billStatus
      }).then(res => {
        if (res.status == 200) {
          this.visibleAudit = false
          this.$message.success(res.message)
          this.$refs.table.refresh()
          this.spinningAudit = false
        } else {
          this.visibleAudit = false
          this.spinningAudit = false
        }
      })
    },
    handleDetailClose () {
      this.itemSn = null
      this.isGrab = null
      this.openDetailModal = false
    },
    // 供应商下拉数据
    getSupplierList () {
      supplierAllList().then(res => {
        if (res.status == 200) {
          this.supplierList = res.data
        } else {
          this.supplierList = []
        }
      })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.openModal = false
      this.getSupplierList()
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 235
    }
  },
  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.resetData()
      if (this.$route.query.pageParams) {
        this.queryParam.state = this.$route.query.pageParams.state
      }
      this.pageInit()
      this.$refs.table.refresh(true)
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
