<template>
  <a-card size="small" :bordered="false" class="purchaseOrderList-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" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="采购单号">
                <a-input id="purchaseOrderList-purchaseBillNo" v-model.trim="queryParam.purchaseBillNo" 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="purchaseOrderList-purchaseTargetSn"
                  placeholder="请选择供应商"
                  allowClear
                  v-model="queryParam.purchaseTargetSn"
                  :showSearch="true"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  @change="tragetTypeChange">
                  <a-select-option v-for="item in supplierList" :key="item.purchaseTargetSn" :value="item.purchaseTargetSn">{{ item.purchaseTargetName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" v-show="advanced">
              <a-form-item label="业务状态">
                <v-select
                  v-model="queryParam.billStatus"
                  ref="billStatus"
                  id="purchaseOrderList-billStatus"
                  code="PURCHASE_BILL_STATUS"
                  placeholder="请选择业务状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" v-show="advanced">
              <a-form-item label="财务状态">
                <v-select
                  v-model="queryParam.financialStatus"
                  ref="financialStatus"
                  id="purchaseOrderList-financialStatus"
                  code="FINANCIAL_PAY_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.purchaseBillSource"
                  ref="purchaseBillSource"
                  id="purchaseOrderList-purchaseBillSource"
                  code="PURCHASE_SOURCE"
                  placeholder="请选择单据来源"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="purchaseOrderList-refresh">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearchForm()" :disabled="disabled" id="purchaseOrderList-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>
      <!-- 操作按钮 -->
      <div class="table-operator">
        <a-button id="purchaseOrderList-add" type="primary" v-if="$hasPermissions('B_purchaseNew')&&($hasPermissions('B_SUPPLIER_SJ')||$hasPermissions('B_SUPPLIER_ZB'))" class="button-error" @click="handleAdd">新增</a-button>
      </div>
      <!-- alert -->
      <a-alert type="info" style="margin-bottom:10px">
        <div slot="message">
          共 <strong>{{ totalData&&(totalData.totalRecord || totalData.totalRecord==0) ? totalData.totalRecord : '--' }}</strong> 条记录，
          采购数量合计 <strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '--' }}</strong> ，
          采购金额合计 <strong>{{ totalData&&(totalData.totalAmount || totalData.totalAmount==0) ? '￥'+totalData.totalAmount : '--' }}</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="purchaseBillNo" slot-scope="text, record">
          <span style="color: #ed1c24;cursor: pointer;" v-if="$hasPermissions('B_purchaseDetail')" @click="handleDetail(record)">{{ record.purchaseBillNo }}</span>
          <span v-else>{{ record.purchaseBillNo }}</span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            class="button-info"
            v-if="(record.billStatus == 'WAIT_SUBMIT'||record.billStatus == 'AUDIT_REJECT') && $hasPermissions('B_purchaseEdit')"
            @click="handleEdit(record)"
          >编辑</a-button>
          <a-button
            size="small"
            type="link"
            class="button-warning"
            v-if="record.billStatus == 'WAIT_PUT_WAREHOUSE'&&$hasPermissions('B_purchaseReceiving')"
            @click="handleWarehouse(record)"
          >签收入库</a-button>
          <a-button
            size="small"
            type="link"
            class="button-error"
            v-if="(record.billStatus == 'WAIT_SUBMIT'||record.billStatus == 'AUDIT_REJECT') &&$hasPermissions('B_purchaseDel')"
            @click="handleDel(record)"
          >删除</a-button>
          <span v-if="record.billStatus != 'WAIT_SUBMIT'&&record.billStatus != 'AUDIT_REJECT'&&record.billStatus != 'WAIT_PUT_WAREHOUSE'">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 选择基本信息弹框 -->
    <basic-info-modal :openModal="openModal" @ok="handleOk" @close="openModal=false" />
  </a-card>
</template>

<script>
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import basicInfoModal from './basicInfoModal.vue'
import { purchaseList, purchaseDel, purchaseCount, purchaseTargetList } from '@/api/purchase'
export default {
  components: { STable, VSelect, basicInfoModal, rangeDate },
  data () {
    return {
      spinning: false,
      advanced: true, //  高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      openModal: false, // 基本信息弹框是否显示
      supplierList: [],
      tableHeight: 0,
      // 查询参数
      queryParam: {
        purchaseBillNo: '',
        purchaseTargetSn: undefined,
        purchaseTargetType: undefined,
        billStatus: undefined,
        financialStatus: undefined,
        purchaseBillSource: undefined,
        beginDate: '',
        endDate: ''
      },
      totalData: {
        totalRecord: 0,
        totalCategory: 0,
        totalQty: 0,
        totalAmount: 0
      },
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '采购单号', scopedSlots: { customRender: 'purchaseBillNo' }, width: '16%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '供应商', dataIndex: 'purchaseTargetName', width: '15%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品款数', dataIndex: 'totalCategory', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '采购数量', dataIndex: 'totalQty', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '缺货数量', dataIndex: 'totalCancelQty', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '采购金额', dataIndex: 'discountedAmount', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '业务状态', dataIndex: 'billStatusDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '财务状态', dataIndex: 'financialStatusDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        // 获取统计数据
        this.getTotalData(Object.assign(parameter, this.queryParam))
        return purchaseList(Object.assign(parameter, this.queryParam)).then(res => {
          const 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
        })
      }
    }
  },
  methods: {
    getTotalData (params) {
      purchaseCount(params).then(res => {
        this.totalData = res.data || null
      })
    },
    // 供应商change
    tragetTypeChange (val) {
      const ind = this.supplierList.findIndex(item => item.purchaseTargetSn == val)
      if (ind != -1) {
        this.queryParam.purchaseTargetType = this.supplierList[ind].purchaseTargetType
      }
    },
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  新增
    handleAdd () {
      this.openModal = true
    },
    //  基本信息  保存
    handleOk (row) {
      this.$router.push({ name: `purchaseOrderAdd`, params: { sn: row.purchaseBillSn } })
    },
    //  编辑
    handleEdit (row) {
      this.$router.push({ name: `purchaseOrderEdit`, params: { sn: row.purchaseBillSn } })
    },
    //  详情
    handleDetail (row) {
      this.$router.push({ name: `purchaseOrderDetail`, params: { sn: row.purchaseBillSn } })
    },
    //  签收入库
    handleWarehouse (row) {
      this.$router.push({ name: `purchaseOrderWarehousing`, params: { sn: row.purchaseBillSn } })
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          purchaseDel({
            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
            }
          })
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate()
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.orderBundleNo = ''
      this.queryParam.purchaseBillNo = ''
      this.queryParam.purchaseTargetSn = undefined
      this.queryParam.purchaseTargetType = undefined
      this.queryParam.billStatus = undefined
      this.queryParam.financialStatus = undefined
      this.queryParam.purchaseBillSource = undefined
      this.$refs.table.refresh(true)
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 获取供应商数据
    getSupperList () {
      purchaseTargetList({}).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.getSupperList()
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 275
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      setTimeout(() => {
        _this.setTableH()
      }, 400)
    }
  },
  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>
