<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" id="purchaseReceiptList-form" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate ref="rangeDate" id="purchaseReceiptList-time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="采购单号">
                <a-input id="purchaseReceiptList-sparePartsNo" v-model.trim="queryParam.sparePartsNo" allowClear placeholder="请输入采购单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="供应商名称">
                <supplier id="purchaseReceiptList-supplierSn" v-model="queryParam.supplierSn" isPermission placeholder="请输入供应商名称"></supplier>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="客户名称">
                  <custList ref="custList" id="purchaseReceiptList-buyerSn" @change="custChange"></custList>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="关联单号">
                  <a-input id="purchaseReceiptList-salesBillNo" v-model.trim="queryParam.salesBillNo" allowClear 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="purchaseReceiptList-serviceState"
                    code="SPARE_PARTS_RETURN_STATE"
                    placeholder="请选择审核状态"
                    allowClear
                  ></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="供应商状态">
                  <v-select
                    v-model="queryParam.state"
                    ref="state"
                    id="purchaseReceiptList-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="purchaseReceiptList-refresh">查询</a-button>
                <a-button style="margin-left: 10px" @click="resetSearchForm()" :disabled="disabled" id="purchaseReceiptList-reset">重置</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="purchaseReceiptList-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 统计数据 -->
        <div class="tongji-bar">
          总单数：<strong>{{ totalData&&(totalData.totalRecord || totalData.totalRecord==0) ? totalData.totalRecord : '--' }}</strong>；
          总款数：<strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '--' }}</strong>；
          总采购数量：<strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '--' }}</strong>；
          <span>总采购金额：<strong>{{ totalData&&(totalData.totalAmount || totalData.totalAmount==0) ? toThousands(totalData.totalAmount) : '--' }}</strong>；</span>
          <span>已完结金额：<strong>{{ totalData&&(totalData.totalAmount || totalData.totalAmount==0) ? toThousands(totalData.totalAmount) : '--' }}</strong>；</span>
        </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')" id="purchaseReceiptList-detail-btn" 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"
              class="button-warning"
              @click="handleCheck(record)"
              v-if="$hasPermissions('B_purchaseReturnRate') && record.state !='WAIT_SUBMIT'"
              id="purchaseReceiptList-examine-btn">审核</a-button>
            <a-button
              size="small"
              type="link"
              v-if="$hasPermissions('B_purchaseReturnEdit')"
              @click="handleEdit(record)"
              class="button-info"
              id="purchaseReceiptList-edit-btn">编辑</a-button>
            <a-button
              size="small"
              type="link"
              v-if="$hasPermissions('B_purchaseReturnDel')"
              @click="handleDel(record)"
              class="button-error"
              id="purchaseReceiptList-del-btn">取消</a-button>
            <a-button
              size="small"
              type="link"
              class="button-warning"
              @click="handleCheck(record)"
              v-if="$hasPermissions('B_purchaseReturnRate') && record.state !='WAIT_SUBMIT'"
              id="purchaseReceiptList-logistics-btn">物流</a-button>
            <a-button
              size="small"
              type="link"
              class="button-warning"
              @click="handleCheck(record)"
              v-if="$hasPermissions('B_purchaseReturnRate') && record.state !='WAIT_SUBMIT'"
              id="purchaseReceiptList-addVoucher-btn">上传凭证</a-button>
            <a-button
              size="small"
              type="link"
              class="button-warning"
              @click="handleCheck(record)"
              v-if="$hasPermissions('B_purchaseReturnRate') && record.state !='WAIT_SUBMIT'"
              id="purchaseReceiptList-seeVoucher-btn">查看凭证</a-button>
          </template>
        </s-table>
      </a-spin>
      <!-- 详情弹窗 -->
      <detailModal v-drag :openModal="openDetailModal" :itemSn="itemSn" @close="closeDetailModal" />
      <!-- 审核弹窗 -->
      <reviewModal v-drag :openModal="openReviewModal" @close="openReviewModal=false"></reviewModal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import custList from '@/views/common/custList.vue'
import supplier from '@/views/common/supplier.js'
import warehouse from '@/views/common/chooseWarehouse.js'
import reviewModal from './reviewModal.vue'
import detailModal from './detailModal.vue'
// 接口
import { sparePartsReturnList, sparePartsReturnDelete, sparePartsReturnExportDetail, againSubmit } from '@/api/sparePartsReturn'
export default {
  name: 'PurchaseReceiptList',
  mixins: [commonMixin],
  components: { STable, supplier, VSelect, custList, rangeDate, warehouse, reviewModal, detailModal },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0, // 表格高度
      advanced: true, // 高级搜索 展开/关闭
      // 查询参数
      queryParam: {
        beginDate: undefined,
        endDate: undefined,
        sparePartsReturnNo: undefined,
        supplierSn: undefined,
        returnReason: undefined,
        warehouseSn: undefined, // 仓库
        state: undefined
      },
      openReviewModal: false, // 审核弹窗
      openDetailModal: false, // 详情弹窗
      itemSn: null, // 采购入库sn
      totalData: null, // 统计数据
      // 加载数据方法 必须为 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
        })
      }
    }
  },
  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: 'auditDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '供应商名称', dataIndex: 'supplier.supplierName', align: 'left', width: '14%', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '采购数量', dataIndex: 'totalQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '采购金额', dataIndex: 'totalCost', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } },
        { title: '入库仓库', dataIndex: 'returnReasonDictValue', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '关联单号', dataIndex: 'stateDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'returnReasonDictValue', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '业务状态', dataIndex: 'returnReasonDictValue', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '供应商状态', dataIndex: 'returnReasonDictValue', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '备注', dataIndex: 'returnReasonDictValue', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      // 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]
    },
    //  编辑
    handleEdit (row) {
      this.$router.push({ name: 'purchaseReceiptEdit', query: { returnSn: row.sparePartsReturnSn, no: row.sparePartsReturnNo, sn: row.supplierSn } })
    },
    // 审核
    handleCheck (row) {
      const _this = this
      _this.openReviewModal = true
    },
    //  采购单号 打开详情弹窗
    handleDetail (row) {
      this.itemSn = row.sparePartsReturnSn
      this.openDetailModal = true
    },
    // 关闭采购退货详情弹框
    closeDetailModal () {
      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
            }
          })
        }
      })
    },
    // 客户名称 change
    custChange (obj) {
      this.queryParam.buyerSn = obj.key
    },
    //  重置
    resetSearchForm () {
      this.queryParam = {
        beginDate: undefined,
        endDate: undefined,
        sparePartsReturnNo: undefined,
        supplierSn: undefined,
        returnReason: undefined,
        warehouseSn: undefined, // 仓库
        state: undefined
      }
      this.$refs.custList.resetForm()
      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 - 225
    }
  },
  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" scoped>
  .purchaseReceiptList-wrap{
    .tongji-bar{
     margin-bottom:13px;
    }

  }
</style>
