<template>
  <div class="purchaseNewOrderList-wrap jg-page-wrap">
    <a-card size="small" :bordered="false" class="table-page-search-wrapper">
        <!-- 搜索条件 -->
      <div ref="tableSearch">
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row type="flex" justify="start" :gutter="15">
            <a-col flex="350px">
              <a-form-item label="创建时间">
                <rangeDate style="width:100%" ref="rangeDate" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col flex="300px">
              <a-form-item label="采购单号">
                <a-input id="purchaseOrderList-purchaseBillNo" v-model.trim="queryParam.purchaseBillNo" allowClear placeholder="请输入采购单号"/>
              </a-form-item>
            </a-col>
            <a-col flex="300px">
              <a-form-item label="供应商">
                <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" :pyCode="item.pyCode" :key="item.purchaseTargetSn" :value="item.purchaseTargetSn">{{ item.purchaseTargetName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col flex="200px">
              <a-form-item label="业务状态">
                <a-select id="purchaseOrderList-billStatus" allowClear v-model="queryParam.billStatus" placeholder="请选择业务状态">
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option value="WAIT_SUBMIT">待提交</a-select-option>
                  <a-select-option value="SUBMIT">已提交</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col flex="200px">
              <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 flex="200px">
              <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 :span="24" style="display:flex;justify-content: center;align-items: center;">
              <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-col>
          </a-row>
        </a-form>
      </div>
    </a-card>

    <a-card size="small" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 操作按钮 -->
        <div class="table-operator" style="display:flex;align-items:center;justify-content: space-between;">
          <div class="alert-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) ? toThousands(totalData.totalAmount,2) : '--' }}</strong>，
            审核金额合计 <strong>{{ totalData&&(totalData.totalAuthAmount || totalData.totalAuthAmount==0) ? toThousands(totalData.totalAuthAmount,2) : '--' }}</strong>
          </div>
          <div class="action-buttons">
            <a-button id="purchaseOrderList-add" type="primary" v-if="$hasPermissions('B_purchaseNew')&&($hasPermissions('B_SUPPLIER_SJ')||$hasPermissions('B_SUPPLIER_ZB'))" @click="handleAdd"><a-icon type="plus" />新增</a-button>
          </div>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+72+'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 class="table-td-link" v-if="$hasPermissions('B_purchaseDetail')" @click="handleDetail(record)">{{ record.purchaseBillNo }}</span>
            <span v-else>{{ record.purchaseBillNo }}</span>
            <a-badge count="改" :offset="[10,0]" v-if="record.billStatus=='HQ_CHANGE'||record.billStatus=='SUPERIOR_CHANGE'"></a-badge>
          </template>
          <!-- 审核 -->
          <template slot="audit" slot-scope="text, record">
            <stateIcon :title="record.billStatusDictValue" v-if="record.billStatus!='AUDIT_REJECT'" :state="record.billStatus == 'WAIT_PUT_WAREHOUSE'||record.billStatus=='AUDIT_PASS'||record.billStatus == 'FINISH'?'1':'2'"></stateIcon>
            <stateIcon :title="record.billStatusDictValue" v-else :state="0"></stateIcon>
          </template>
          <!-- 付款 -->
          <template slot="financial" slot-scope="text, record">
            <stateIcon :title="record.financialStatusDictValue" :state="record.financialStatus == 'FINISH'?'1':'2'"></stateIcon>
          </template>
          <!-- 入库 -->
          <template slot="waitOut" slot-scope="text, record">
            <stateIcon :state="record.billStatus == 'FINISH'?'1':'2'"></stateIcon>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              class="button-primary"
              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-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') && $hasPermissions('B_purchaseEdit')) && !((record.billStatus == 'WAIT_SUBMIT'||record.billStatus == 'AUDIT_REJECT') &&$hasPermissions('B_purchaseDel'))">--</span>
          </template>
        </s-table>
      </a-spin>
  </a-card>
      <!-- 选择基本信息弹框 -->
      <basic-info-modal :openModal="openModal" @ok="handleOk" @close="openModal=false" />
  </div>
 
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import basicInfoModal from './basicInfoModal.vue'
import stateIcon from '@/views/common/stateIcon'
import getDate from '@/libs/getDate.js'
import { purchaseList, purchaseDel, purchaseCount } from '@/api/purchase'
import { queryReturnSupplierList } from '@/api/purchaseReturn'
export default {
  name: 'PurchaseOrderNewList',
  components: { STable, VSelect, basicInfoModal, rangeDate, stateIcon },
  mixins: [commonMixin],
  data () {
    const _this = this
    return {
      spinning: false,
      advanced: false, //  高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      openModal: false, // 基本信息弹框是否显示
      supplierList: [],
      tableHeight: 0,
      time: [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      // 查询参数
      queryParam: {
        purchaseBillNo: '',
        purchaseTargetSn: undefined,
        purchaseTargetType: undefined,
        billStatus: undefined,
        financialStatus: undefined,
        purchaseBillSource: undefined,
        beginDate: getDate.getCurrMonthDays().starttime,
        endDate: getDate.getCurrMonthDays().endtime
      },
      totalData: {
        totalRecord: 0,
        totalCategory: 0,
        totalQty: 0,
        totalAmount: 0
      },
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '采购单号', scopedSlots: { customRender: 'purchaseBillNo' }, width: '13%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '供应商', dataIndex: 'purchaseTargetName', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品款数', dataIndex: 'totalCategory', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '采购数量', dataIndex: 'totalQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '采购金额', dataIndex: 'discountedAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } },
        { title: '审核数量', dataIndex: 'totalPushedQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '审核金额', dataIndex: 'totalPushedAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } },
        { title: '已取消数量', dataIndex: 'totalCancelQty', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '采购状态', dataIndex: 'billStatusDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核', scopedSlots: { customRender: 'audit' }, width: '3%', align: 'center' },
        { title: '入库', scopedSlots: { customRender: 'waitOut' }, width: '3%', align: 'center' },
        { title: '付款', scopedSlots: { customRender: 'financial' }, width: '3%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '9%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        if (!params.billStatus) {
          params.billStatus = undefined
        }
        // 获取统计数据
        this.getTotalData(params)
        return purchaseList(params).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
        })
      }
    }
  },
  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
      } else {
        this.queryParam.purchaseTargetSn = undefined
        this.queryParam.purchaseTargetType = undefined
      }
    },
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  新增
    handleAdd () {
      this.openModal = true
    },
    //  基本信息  保存
    handleOk (row) {
      this.$router.push({ name: `purchaseOrderNewAdd`, params: { sn: row.purchaseBillSn, dealerSn: (row.purchaseTargetType == 'DEALER_UP' ? row.purchaseTargetSn : 'NONE') } })
    },
    //  编辑
    handleEdit (row) {
      this.$router.push({ name: `purchaseOrderNewEdit`, params: { sn: row.purchaseBillSn, dealerSn: (row.purchaseTargetType == 'DEALER_UP' ? row.purchaseTargetSn : 'NONE') } })
    },
    //  详情
    handleDetail (row) {
      this.$router.push({ name: `purchaseOrderNewDetail`, 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 (flag) {
      this.$refs.rangeDate.resetDate(flag ? '' : this.time)
      this.queryParam.beginDate = flag ? '' : getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = flag ? '' : getDate.getCurrMonthDays().endtime
      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
      if (!flag) {
        this.$refs.table.refresh(true)
        this.setIsHomeNav(this.$route.name, null)
      }
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 获取供应商数据
    getSupperList () {
      queryReturnSupplierList({}).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()

      // 是否打开的页签
      const a = this.$store.state.app.isNewTab
      // 是否要刷新列表
      const b = this.$store.state.app.updateList
      // 是否从首页点击进入
      const isHomeNav = this.getIsHomeNav()[this.$route.name]
      console.log(a, b, this.getIsHomeNav(), isHomeNav, this.$route.name)

      // 从首页进入,判断式新建还式待办查询
      if (isHomeNav) {
        // 新增
        if (isHomeNav.type == 'new') {
          this.resetSearchForm()
          this.openModal = true
        }
        // 待办
        if (isHomeNav.type == 'todo') {
          this.resetSearchForm(true)
          this.queryParam = Object.assign(this.queryParam, isHomeNav.pageParams)
          this.$refs.rangeDate.resetDate([this.queryParam.beginDate, this.queryParam.endDate])
          this.$refs.table.refresh(true)
        }
      } else {
        // 如果是新页签打开，则重置当前页面
        if (a && !b) {
          this.resetSearchForm()
        }
      }
      // 仅刷新列表，不重置页面
      if (b || a == b) {
        this.$refs.table.refresh()
      }
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 255
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  activated () {
    this.pageInit()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
    })
  }
}
</script>
<style lang="less">
   
</style>