<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form-model
          layout="inline"
          ref="ruleForm"
          :model="queryParam"
          :rules="rules"
          id="purchaseReceiptList-form"
          @keyup.enter.native="handleSearch">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="创建时间" prop="time">
                <rangeDate ref="rangeDate" id="purchaseReceiptList-time" @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="采购单号">
                <a-input id="purchaseReceiptList-sparePartsNo" v-model.trim="queryParam.sparePartsNo" allowClear placeholder="请输入采购单号"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="供应商名称">
                <supplier
                  id="purchaseReceiptList-supplierSn"
                  enableFlag="1"
                  pageSn="福麦斯"
                  v-model="queryParam.supplierSn"
                  isPermission
                  placeholder="请输入供应商名称"></supplier>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="业务状态">
                  <v-select
                    v-model="queryParam.state"
                    ref="state"
                    id="purchaseReceiptList-state"
                    code="PURCHASE_STATE"
                    placeholder="请选择业务状态"
                    allowClear
                  ></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户名称">
                  <custList ref="custList" id="purchaseReceiptList-buyerSn" @change="custChange"></custList>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="关联单号">
                  <a-input id="purchaseReceiptList-relationNo" v-model.trim="queryParam.relationNo" allowClear placeholder="请输入关联单号"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="供应商状态">
                  <v-select
                    v-model="queryParam.thirdpartyBizState"
                    ref="thirdpartyBizState"
                    id="purchaseReceiptList-thirdpartyBizState"
                    code="THIRD_PARTY_BIZ_STATE"
                    placeholder="请选择供应商状态"
                    allowClear
                  ></v-select>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="handleSearch" :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" id="purchaseReceiptList-advanced">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </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.productTotalCategory || totalData.productTotalCategory==0) ? totalData.productTotalCategory : '--' }}</strong>；
          总采购数量：<strong>{{ totalData&&(totalData.productTotalQty || totalData.productTotalQty==0) ? totalData.productTotalQty : '--' }}</strong>；
          <span v-if="$hasPermissions('M_purchaseReceiptList_costPrice')">总采购金额：<strong>{{ totalData&&(totalData.productTotalCost || totalData.productTotalCost==0) ? toThousands(totalData.productTotalCost) : '--' }}</strong>；</span>
          <span v-if="$hasPermissions('M_purchaseReceiptList_costPrice')">已完结金额：<strong>{{ totalData&&(totalData.finishProductTotalCost || totalData.finishProductTotalCost==0) ? toThousands(totalData.finishProductTotalCost) : '--' }}</strong>；</span>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+70+'px' }"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :pageSize="30"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 采购退货单号 -->
          <template slot="purchaseReceiptNo" slot-scope="text, record">
            <span v-if="$hasPermissions('B_purchaseReceiptDetail')" :id="'purchaseReceiptList-detail-btn'+record.id" class="link-bule" @click="handleDetail(record)">{{ record.sparePartsNo }}</span>
            <span v-else>{{ record.sparePartsNo }}</span>
          </template>
          <!-- 操作 -->
          <!-- state  取消 CANCEL 待提交 WAIT_SUBMIT 待审核 WAIT_AUDIT 待入库 WAIT_PUT 已完结 FINISH 审核通过 PASS 审核不通过 REJECT -->
          <!-- thirdpartyBizState 审核通过	AUDIT_PASS 审核不通过	AUDIT_REJECT  已取消	CANCEL 已出库	FINISH 待审核	WAIT_AUDIT 待发货	WAIT_RECEIVE -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              class="button-warning"
              @click="handleCheck(record)"
              v-if="$hasPermissions('B_purchaseReceiptAudit') && record.state ==='WAIT_AUDIT'&&(!record.thirdpartyBizState)"
              :id="'purchaseReceiptList-examine-btn'+record.id">审核</a-button>
            <a-button
              size="small"
              type="link"
              @click="handleEdit(record)"
              class="button-info"
              v-if="$hasPermissions('M_purchaseReceiptEdit') && (record.state ==='WAIT_SUBMIT'||record.state ==='WAIT_AUDIT'||record.state ==='REJECT') && (!record.thirdpartyBizState)"
              :id="'purchaseReceiptList-edit-btn'+record.id">编辑</a-button>
            <a-button
              size="small"
              type="link"
              v-if="$hasPermissions('B_purchaseReceiptDel')&&isShowCancelBtn(record)"
              @click="handleDel(record)"
              class="button-error"
              :id="'purchaseReceiptList-del-btn'+record.id">取消</a-button>
            <a-button
              v-if="$hasPermissions('B_purchaseReceiptTransportNo') && (record.state === 'WAIT_PUT'&&record.thirdpartyBizState==='FINISH')||(record.state === 'FINISH'&&record.thirdpartyBizState==='FINISH')"
              size="small"
              type="link"
              class="button-warning"
              :id="'purchaseReceiptList-logistics-btn'+record.id"
              @click="handleFlow(record)"
            >
              物流
            </a-button>
            <a-button
              size="small"
              type="link"
              class="button-warning"
              @click="addVoucher(record)"
              v-if="$hasPermissions('B_purchaseReceiptAddVoucher') && isShowUploadBtn(record)"
              :id="'purchaseReceiptList-addVoucher-btn'+record.id">上传凭证</a-button>
            <a-button
              size="small"
              type="link"
              class="button-warning"
              @click="seeVoucher(record)"
              v-if="$hasPermissions('B_purchaseReceiptSeeVoucher') && isShowCheckBtn(record)"
              :id="'purchaseReceiptList-seeVoucher-btn'+record.id">查看凭证</a-button>
            <span v-if="(!$hasPermissions('B_purchaseReceiptSeeVoucher')&&!$hasPermissions('B_purchaseReceiptAddVoucher')&&!$hasPermissions('B_purchaseReceiptTransportNo')&&!$hasPermissions('B_purchaseReceiptDel')&&!$hasPermissions('M_purchaseReceiptEdit')&&!$hasPermissions('B_purchaseReceiptAudit'))||isShowNoBtn(record)">--</span>
          </template>
        </s-table>
      </a-spin>
      <!-- 查看物流单号 -->
      <viewLogistics v-drag :openModal="openFlowModal" :itemNo="noInfo" @close="closeFlowModal"></viewLogistics>
      <!-- 详情弹窗 -->
      <detailModal v-drag :openModal="openDetailModal" :itemSn="itemSn" @close="closeDetailModal" />
      <!-- 审核弹窗 -->
      <reviewModal v-drag :openModal="openReviewModal" :itemSn="itemSn" @ok="okReviewModal" @close="closeReviewModal"></reviewModal>
      <!-- 上传凭证 -->
      <uploadVoucherModal v-drag :openModal="openVoucherModal" :itemSn="itemSn" @ok="handleSearch" @close="openVoucherModal=false"></uploadVoucherModal>
      <!-- 查看上传凭证 -->
      <seeVoucherModal v-drag :openModal="openSeeVoucherModal" :itemData="itemSeeData" @close="openSeeVoucherModal=false;itemSeeData=null"></seeVoucherModal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import getDate from '@/libs/getDate.js'
// 组件
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 reviewModal from './reviewModal.vue'
import detailModal from './detailModal.vue'
import uploadVoucherModal from './uploadVoucherModal.vue'
import seeVoucherModal from './seeVoucherModal.vue'
import viewLogistics from './viewLogisticsModal.vue'
// 接口
import { purchaseList, purchasePageCount, purchaseCancel, purchaseAudit } from '@/api/purchase'
export default {
  name: 'PurchaseReceiptList',
  mixins: [commonMixin],
  components: { STable, supplier, VSelect, custList, rangeDate, reviewModal, detailModal, uploadVoucherModal, seeVoucherModal, viewLogistics },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0, // 表格高度
      advanced: true, // 高级搜索 展开/关闭
      // 查询参数
      queryParam: {
        // 创建时间默认值
        time: [ moment(getDate.getThreeMonthDays().starttime, 'YYYY-MM-DD'),
          moment(getDate.getCurrMonthDays().endtime, 'YYYY-MM-DD')],
        beginDate: getDate.getThreeMonthDays().starttime, // 创建开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 创建结束时间
        sparePartsNo: undefined, // 采购单号
        supplierSn: undefined, // 供应商名称
        lockBizDealerSn: undefined, // 客户名称
        relationNo: undefined, // 关联单号
        state: undefined, // 业务状态
        thirdpartyBizState: undefined// 供应商状态
      },
      openReviewModal: false, // 审核弹窗
      openVoucherModal: false, // 上传凭证
      openSeeVoucherModal: false, // 查看上传凭证弹窗
      openDetailModal: false, // 详情弹窗
      itemSn: null, // 采购入库sn
      itemSeeData: null, // 查看凭证数据
      totalData: null, // 统计数据
      openFlowModal: false, // 物流弹窗
      noInfo: '', // 物流单号
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        const newParams = JSON.parse(JSON.stringify(params))
        delete newParams.time
        // 获取列表数据 有分页
        return purchaseList(newParams).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            // 获取统计数据
            this.getCount(newParams)
            // 计算列表序号
            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
        })
      },
      rules: {
        'time': [{ required: true, message: '请选择创建时间', trigger: 'change' }]
      }
    }
  },
  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: 'purchaseReceiptNo' }, width: '9%', align: 'center' },
        { title: '提交时间', dataIndex: 'updateDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '供应商名称', dataIndex: 'supplierName', align: 'left', width: '14%', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '采购数量', dataIndex: 'productTotalQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '采购金额', dataIndex: 'productTotalCost', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } },
        { title: '入库仓库', dataIndex: 'warehouseName', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '关联单号', dataIndex: 'lockBizNo', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'lockBizDealerName', width: '14%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '业务状态', dataIndex: 'stateDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '供应商状态', dataIndex: 'thirdpartyBizStateDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '备注', dataIndex: 'bizRemark', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      if (this.$hasPermissions('M_purchaseReceiptList_costPrice')) { //  成本价权限
        arr.splice(6, 0, { title: '采购金额', dataIndex: 'productTotalCost', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } })
      }
      return arr
    }
  },
  methods: {
    // 是否显示取消按钮
    isShowCancelBtn (row) {
      const res = ((row.state === 'WAIT_SUBMIT' || row.state === 'WAIT_AUDIT' || row.state === 'REJECT') && !row.thirdpartyBizState) || (row.state === 'PASS' && row.thirdpartyBizState === 'WAIT_AUDIT')
      return res
    },
    // 是否显示上传凭证按钮
    isShowUploadBtn (con) {
      const res = ((con.state === 'WAIT_PUT' && con.thirdpartyBizState === 'AUDIT_PASS') || (con.state === 'WAIT_PUT' && con.thirdpartyBizState === 'FINISH') || (con.state === 'FINISH' && con.thirdpartyBizState === 'AUDIT_PASS') || (con.state === 'FINISH' && con.thirdpartyBizState === 'FINISH') || (con.state === 'WAIT_PUT' && con.thirdpartyBizState === 'CANCEL')) && !con.attachmentList
      return res
    },
    // 是否显示查看凭证按钮
    isShowCheckBtn (con) {
      const res = ((con.state === 'WAIT_PUT' && con.thirdpartyBizState === 'AUDIT_PASS') || (con.state === 'WAIT_PUT' && con.thirdpartyBizState === 'FINISH') || (con.state === 'FINISH' && con.thirdpartyBizState === 'AUDIT_PASS') || (con.state === 'FINISH' && con.thirdpartyBizState === 'FINISH') || (con.state === 'WAIT_PUT' && con.thirdpartyBizState === 'CANCEL')) && (con.attachmentList && con.attachmentList.length > 0)
      return res
    },
    // 是否显示 --
    isShowNoBtn (rowVal) {
      const res = (rowVal.state === 'CANCEL' && !rowVal.thirdpartyBizState) || (rowVal.state === 'CANCEL' && rowVal.thirdpartyBizState === 'WAIT_AUDIT') || (rowVal.state === 'PASS' && rowVal.thirdpartyBizState === 'AUDIT_REJECT') || (rowVal.state === 'WAIT_PUT' && rowVal.thirdpartyBizState === 'CANCEL')
      return res
    },
    // 创建时间
    dateChange (date) {
      if (date[0] && date[1]) {
        this.queryParam.time = date
      } else {
        this.queryParam.time = []
      }
      this.queryParam.beginDate = date[0] || undefined
      this.queryParam.endDate = date[1] || undefined
    },
    // 查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择创建时间')
          return false
        }
      })
    },
    // 获取统计数据
    getCount (params) {
      purchasePageCount(params).then(res => {
        if (res.status == 200 && res.data) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    //  编辑
    handleEdit (row) {
      this.$router.push({ name: 'purchaseReceiptEdit', query: { sn: row.sparePartsSn } })
    },
    // 审核
    handleCheck (row) {
      const _this = this
      _this.itemSn = row.sparePartsSn
      _this.openReviewModal = true
    },
    // 审核结果
    okReviewModal (val) {
      const _this = this
      const ajaxData = {
        sparePartsSn: _this.itemSn,
        auditState: val
      }
      _this.spinning = true
      purchaseAudit(ajaxData).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$refs.table.refresh(true)
          _this.spinning = false
          _this.closeReviewModal()
        } else {
          _this.spinning = false
        }
      })
    },
    // 审核完成，清理sn数据
    closeReviewModal () {
      this.itemSn = null
      this.openReviewModal = false
    },
    //  采购单号 打开详情弹窗
    handleDetail (row) {
      this.itemSn = row.sparePartsSn
      this.openDetailModal = true
    },
    // 关闭采购入库详情弹框
    closeDetailModal () {
      this.itemSn = null
      this.openDetailModal = false
    },
    // 上传凭证
    addVoucher (row) {
      this.itemSn = row.sparePartsSn
      this.openVoucherModal = true
    },
    // 查看凭证
    seeVoucher (row) {
      this.itemSeeData = row.attachmentList
      this.$nextTick(() => {
        this.openSeeVoucherModal = true
      })
    },
    //  取消
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认取消吗？取消后不可恢复？',
        centered: true,
        onOk () {
          _this.spinning = true
          purchaseCancel({ sn: row.sparePartsSn }).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.lockBizDealerSn = obj.key
    },
    //  重置
    resetSearchForm () {
      this.queryParam.beginDate = getDate.getThreeMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.time = [
        getDate.getThreeMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ]
      this.$refs.rangeDate.resetDate(this.queryParam.time)
      this.queryParam.sparePartsNo = undefined
      this.queryParam.supplierSn = undefined
      this.queryParam.lockBizDealerSn = undefined
      this.queryParam.relationNo = undefined
      this.queryParam.state = undefined
      this.queryParam.thirdpartyBizState = undefined
      this.itemSn = null
      this.$refs.custList.resetForm()
      this.$refs.ruleForm.resetFields()
      this.$refs.table.refresh(true)
    },
    // 打开物流弹窗
    handleFlow (row) {
      this.noInfo = row.transportNo
      this.openFlowModal = true
    },
    // 关闭物流弹窗
    closeFlowModal () {
      this.noInfo = ''
      this.openFlowModal = false
    },
    // 初始化数据
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算表格高度
    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>
