<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" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="供应商名称">
                <supplier v-model="queryParam.supplierSn" isPermission placeholder="请输入供应商名称"></supplier>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="采购退货单号">
                <a-input id="bulkWarehousingOrderList-productCode" v-model.trim="queryParam.sparePartsReturnNo" allowClear placeholder="请输入采购退货单号"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="退货原因">
                  <v-select
                    v-model="queryParam.returnReason"
                    ref="returnReason"
                    id="purchaseReturn-returnReason"
                    code="SPARE_PARTS_RETURN_REASON"
                    placeholder="请选择退货原因"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowWarehouse">
                <a-form-item label="退货仓库">
                  <warehouse
                    v-model="queryParam.warehouseSn"
                    isPermission
                    id="purchaseReturn-warehouseSn"
                    placeholder="请选择退货仓库"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="业务状态">
                  <v-select
                    v-model="queryParam.state"
                    ref="state"
                    id="purchaseReturn-state"
                    code="SPARE_PARTS_RETURN_STATE"
                    placeholder="请选择审核状态"
                    allowClear
                  ></v-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="bulkWarehousingOrderList-refresh">查询</a-button>
                <a-button style="margin-left: 10px" @click="resetSearchForm()" :disabled="disabled" id="bulkWarehousingOrderList-reset">重置</a-button>
                <a-button
                  style="margin-left: 10px"
                  type="primary"
                  class="button-warning"
                  @click="handleExport"
                  :disabled="disabled"
                  :loading="exportLoading"
                  v-if="$hasPermissions('B_purchaseReturnExport')"
                >导出明细</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>
    </a-card>
    <a-card size="small" :bordered="false" class="bulkWarehousingOrderList-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 操作按钮 -->
        <div class="table-operator">
          <a-button v-if="$hasPermissions('B_purchaseReturnAdd')" id="bulkWarehousingOrderList-add" type="primary" class="button-error" @click="handleAdd">新增</a-button>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+70+'px' }"
          size="small"
          :rowKey="(record) => record.sparePartsReturnNo"
          :columns="columns"
          :data="loadData"
          :pageSize="30"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 采购退货单号 -->
          <template slot="sparePartsReturnNo" slot-scope="text, record">
            <span v-if="$hasPermissions('B_purchaseReturnDetail')" class="link-bule" @click="handleDetail(record)">{{ record.sparePartsReturnNo }}</span>
            <span v-else>{{ record.sparePartsReturnNo }}</span>
          </template>
          <!-- 操作 -->
          <!-- state 待提交 WAIT_SUBMIT 待审核 WAIT_AUDIT 已完结 FINISH 审核不通过 AUDIT_REJECT -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              v-if="$hasPermissions('B_purchaseReturnEdit') && record.state == 'WAIT_SUBMIT'"
              @click="handleEdit(record)"
              class="button-info"
              id="bulkWarehousingOrderList-edit-btn">编辑</a-button>
            <a-button
              size="small"
              type="link"
              class="button-warning"
              @click="handleSH(record)"
              v-if="$hasPermissions('B_purchaseReturnRate') && record.state !='WAIT_SUBMIT'"
              id="allocateBillList-examine-btn">审核进度</a-button>
            <a-button
              size="small"
              type="link"
              v-if="$hasPermissions('B_purchaseReturnSubmit') && record.state == 'AUDIT_REJECT'"
              @click="handleResubmit(record)"
              class="button-info"
              id="bulkWarehousingOrderList-edit-btn">再次提交</a-button>
            <a-button
              size="small"
              type="link"
              v-if="$hasPermissions('B_purchaseReturnDel') && record.state == 'WAIT_SUBMIT'"
              @click="handleDel(record)"
              class="button-error"
              id="bulkWarehousingOrderList-del-btn">删除</a-button>
          </template>
        </s-table>
      </a-spin>
      <!-- 新增、详情弹窗-->
      <add-modal v-drag :openModal="openModal" @ok="handleOk" @close="openModal=false" />
      <detailModal v-drag :openModal="openDetailModal" :itemSn="itemSn" @close="closeDetailModal" />
      <!-- 导出提示框 -->
      <reportModal :visible="showExport" @close="showExport=false"></reportModal>
      <!-- 审核进度弹窗 -->
      <reviewProgressModal
        v-drag
        :itemSn="itemSnSh"
        :itemId="itemIdSh"
        :auditTime="auditTime"
        :openModal="openReviewModal"
        @close="openReviewModal=false"></reviewProgressModal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import addModal from './addModal.vue'
import detailModal from './detailModal.vue'
import rangeDate from '@/views/common/rangeDate.vue'
import chooseDepartUserModal from './chooseDepartUserModal.vue'
import reviewProgressModal from './reviewProgressModal.vue'
import reportModal from '@/views/common/reportModal.vue'
import { hdExportExcel } from '@/libs/exportExcel'
import supplier from '@/views/common/supplier.js'
import warehouse from '@/views/common/chooseWarehouse.js'
import { sparePartsReturnList, sparePartsReturnDelete, sparePartsReturnExportDetail, againSubmit } from '@/api/sparePartsReturn'
export default {
  name: 'PurchaseReturnList',
  mixins: [commonMixin],
  components: { STable, supplier, VSelect, reportModal, detailModal, addModal, chooseDepartUserModal, rangeDate, reviewProgressModal, warehouse },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      openModal: false, // 新增弹框是否显示
      openDetailModal: false, // 详情弹窗
      openReviewModal: false, // 审核进度弹窗
      showExport: false,
      exportLoading: false,
      advanced: true,
      tableHeight: 0,
      // 查询参数
      queryParam: {
        beginDate: undefined,
        endDate: undefined,
        sparePartsReturnNo: undefined,
        supplierSn: undefined,
        returnReason: undefined,
        warehouseSn: undefined, // 仓库
        state: undefined
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return sparePartsReturnList(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
        })
      },
      itemSnSh: null,
      itemIdSh: null, // 采购退货审核进度ID
      itemSn: null, // 采购退货SN
      auditTime: null// 审核时间
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '采购退货单号', scopedSlots: { customRender: 'sparePartsReturnNo' }, width: '9%', align: 'center' },
        { title: '供应商名称', dataIndex: 'supplier.supplierName', align: 'left', width: '14%', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '退货原因', dataIndex: 'returnReasonDictValue', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '申请退货数量', dataIndex: 'totalQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '审核时间', dataIndex: 'auditDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核状态', dataIndex: 'stateDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      if (this.isShowWarehouse) {
        arr.splice(5, 0, { title: '退货仓库', dataIndex: 'warehouseName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } })
      }
      if (this.$hasPermissions('M_purchaseReturnList_costPrice')) { //  售价权限
        arr.splice(7, 0, { title: '退货金额', dataIndex: 'totalCost', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } })
      }
      return arr
    }
  },
  methods: {
    // 创建时间
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  导出
    handleExport () {
      const _this = this
      _this.$store.state.app.curActionPermission = 'B_purchaseReturnExport'
      _this.exportLoading = true
      _this.spinning = true
      hdExportExcel(sparePartsReturnExportDetail, _this.queryParam, '采购退货', function () {
        _this.exportLoading = false
        _this.spinning = false
        _this.showExport = true
        _this.$store.state.app.curActionPermission = ''
      })
    },
    //  新增
    handleAdd () {
      this.openModal = true
    },
    //  基本信息  保存
    handleOk (row) {
      this.$router.push({ name: 'purchaseReturnAdd', query: { returnSn: row.sparePartsReturnSn, no: row.sparePartsReturnNo, sn: row.supplierSn } })
    },
    //  编辑
    handleEdit (row) {
      if (row.grabFlag == 0) {
        this.$router.push({ name: 'purchaseReturnEdit', query: { returnSn: row.sparePartsReturnSn, no: row.sparePartsReturnNo, sn: row.supplierSn } })
      } else {
        this.$router.push({ name: 'purchaseReturnEditGrab', query: { returnSn: row.sparePartsReturnSn, no: row.sparePartsReturnNo, sn: row.supplierSn } })
      }
    },
    // 审核进度
    handleSH (row) {
      this.itemSnSh = row.sparePartsReturnSn
      this.itemIdSh = row.id
      this.auditTime = row.submitDate
      const _this = this
      _this.$nextTick(() => {
        _this.openReviewModal = true
      })
    },
    // 再次提交
    handleResubmit (row) {
      const _this = this
      this.$confirm({
        title: '操作提示',
        content: '系统将自动生成一个新的采购退货单，新单据中的产品申退数量将以最大可用库存为准，最大可用库存为0时，系统将强制删除已选的对应产品。您可以对新单据进行编辑、提交等操作，原单据保持不变，确认操作吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          againSubmit({ sparePartsReturnSn: row.sparePartsReturnSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  采购退货详情
    handleDetail (row) {
      this.itemSn = row.sparePartsReturnSn
      const _this = this
      _this.$nextTick(() => {
        _this.openDetailModal = true
      })
    },
    // 关闭采购退货详情弹框
    closeDetailModal () {
      this.itemSn = null
      this.openDetailModal = false
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          sparePartsReturnDelete({ sn: row.sparePartsReturnSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.queryParam = {
        beginDate: undefined,
        endDate: undefined,
        sparePartsReturnNo: undefined,
        supplierSn: undefined,
        returnReason: undefined,
        warehouseSn: undefined, // 仓库
        state: undefined
      }
      this.$refs.rangeDate.resetDate()
      this.$refs.table.refresh(true)
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.openModal = false
      this.openDetailModal = false
      this.itemSn = null
      this.rowSelectionInfo = null
      this.$refs.table.clearTable()
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 240
    }
  },
  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">
  .bulkWarehousingOrderList-wrap{
    .active{
      color: #ed1c24;
      cursor: pointer;
    }
    .common{
      color: rgba(0, 0, 0);
    }
  }
</style>
