<template>
  <div class="purchaseReceiptEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="purchaseReceiptEdit-back">
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="purchaseReceiptEdit-back-btn" href="javascript:;" @click="handleBack">
            <a-icon type="left" />
            返回列表
          </a>
          <span style="margin: 0 15px;color: #666;font-weight: bold;">单号：{{ detailsData&&detailsData.sparePartsNo }}</span>
          <span style="margin: 0 10px;color: #666;">供应商：{{ detailsData&&detailsData.supplierName ||'--' }}</span>
          <a-button type="link" size="small" id="purchaseReceiptEdit-showDetail-btn" class="button-default" @click="showDetail=!showDetail">
            <a-icon :type="showDetail ? 'eye-invisible' : 'eye'"/> {{ showDetail?'隐藏':'查看' }}信息
          </a-button>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="purchaseReceiptEdit-cont" v-show="showDetail">
        <div slot="title">
          <span>基础信息</span>
          <div style="cursor:pointer;color: #00aaff;float:right;" id="purchaseReceiptEdit-btn" @click.stop="handleEditBase" v-if="$hasPermissions('B_purchaseReceiptEdit_basicInfo')&&!(detailsData&&detailsData.supplierName)">
            <a-icon type="edit" /> 编辑基础信息
          </div>
        </div>
        <a-descriptions size="small" :column="4" style="margin-bottom: 10px;">
          <a-descriptions-item label="客户名称">{{ (detailsData && detailsData.lockBizDealerName) || '--' }}</a-descriptions-item>
          <a-descriptions-item label="收货地址">{{ (detailsData && detailsData.shippingAddr) || '--' }}</a-descriptions-item>
          <a-descriptions-item label="收货人">{{ (detailsData &&detailsData.consigneeName) || '--' }}</a-descriptions-item>
          <a-descriptions-item label="收货电话">{{ (detailsData && detailsData.consigneeTel) || '--' }}</a-descriptions-item>
          <a-descriptions-item label="业务状态">{{ detailsData&&detailsData.stateDictValue || '--' }}</a-descriptions-item>
          <a-descriptions-item label="备注">{{ detailsData&&detailsData.bizRemark || '--' }}</a-descriptions-item>
          <a-descriptions-item label="关联单号">{{ (detailsData && detailsData.lockBizNo) || '--' }}</a-descriptions-item>
          <a-descriptions-item label="销售类型">{{ (detailsData && detailsData.purchaseFlowType)?detailsData.purchaseFlowType==='DIRECT'?'直购':'平台购':'--' }}</a-descriptions-item>
        </a-descriptions>
      </a-card>
      <a-card size="small" :bordered="false" class="purchaseReceiptEdit-cont">
        <div class="table-page-search-wrapper" style="display:flex;align-items: center;justify-content: space-between;">
          <div style="flex-grow:1;">
            <a-form layout="inline" id="purchaseReceiptEdit-form-btn" @keyup.enter.native="$refs.table.refresh(true)">
              <a-row :gutter="15">
                <a-col :md="6" :sm="24">
                  <a-form-item label="产品编码"><a-input id="purchaseReceiptEdit-productCode" v-model.trim="productForm.productCode" allowClear placeholder="请输入产品编码" /></a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="产品名称"><a-input id="purchaseReceiptEdit-productName" v-model.trim="productForm.productName" allowClear placeholder="请输入产品名称" /></a-form-item>
                </a-col>
                <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                  <a-button type="primary" id="purchaseReceiptEdit-refresh" @click="$refs.table.refresh(true)">查询</a-button>
                  <a-button style="margin-left: 5px" id="purchaseReceiptEdit-reset" @click="resetSearchForm">重置</a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
        <div class="showBtn">
          <a-button id="purchaseReceiptEdit-add" v-if="$hasPermissions('B_purchaseReceiptEdit_add')" type="primary" class="button-warning" @click="handleAddEdit">新增产品</a-button>
          <a-button style="margin-right:6px;" id="purchaseReceiptEdit-ex" v-if="$hasPermissions('B_purchaseReceiptEdit_import')" class="button-warning" @click="handleImport">导入产品</a-button>
          <!-- <a-button
            id="purchaseReceiptEdit-queryQty"
            type="primary"
            class="button-warning"
            :loading="loading"
            v-if="$hasPermissions('B_purchaseReceiptEdit_thirdQty')"
            @click="handleThirdQty">第三方库存</a-button> -->
          <a-alert type="info">
            <div slot="message" class="total-bar">
              <span>采购数量：{{ statisticsObj && (statisticsObj.productTotalQty || statisticsObj.productTotalQty == 0) ? statisticsObj.productTotalQty : '--' }}；</span>
              <span v-if="$hasPermissions('M_purchaseReceiptEdit_costPrice')">采购金额：{{ (statisticsObj && (statisticsObj.productTotalCost || statisticsObj.productTotalCost == 0) )? statisticsObj.productTotalCost : '--' }}；</span>
            </div>
          </a-alert>
        </div>
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          bordered>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              v-if="$hasPermissions('B_purchaseReceiptEdit_edit')"
              @click="handleAddEdit(record)"
              class="button-info"
              :id="'purchaseReceiptEdit-edit-btn'+record.id">编辑</a-button>
            <a-button
              size="small"
              type="link"
              :loading="delLoading"
              class="button-error"
              v-if="$hasPermissions('B_purchaseReceiptEdit_del')"
              @click="handleDel(record)"
              :id="'purchaseReceiptEdit-del-btn'+record.id">删除</a-button>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        size="large"
        style="padding: 0 60px;"
        :disabled="spinning"
        type="primary"
        class="button-primary"
        v-if="$hasPermissions('B_purchaseReceiptEdit_submit')"
        @click="handleSubmit"
        id="purchaseReceiptEdit-submit">提交</a-button>
    </div>
    <!-- 新增弹窗-->
    <add-modal
      v-drag
      :itemSn="itemSn"
      :openModal="openAddModal"
      :nowData="detailsData"
      @ok="resetTable(true)"
      @close="openAddModal=false" />
    <!-- 导入弹窗 -->
    <importGuideModal :openModal="openGuideModal" :params="{sparePartsSn: $route.query.sn}" @close="openGuideModal=false" @ok="hanldleImportOk" />
    <!-- 编辑基础信息弹窗 -->
    <basic-info-modal
      v-drag
      :openModal="openBasicInfoModal"
      :itemData="itemObj"
      :itemSn="sparePartsSn"
      @ok="resetSearchForm"
      @close="openBasicInfoModal = false" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable, VSelect } from '@/components'
import addModal from './addModal.vue'
import basicInfoModal from './basicInfoModal.vue'
import importGuideModal from './importGuideModal.vue'
// 接口
import { purchaseDetailPageList, queryDetailCount, purchaseDetailDel, purchaseSubmit, purchaseImportBatchInsert, purchaseDetailPageCount } from '@/api/purchase'
import { getThirdStockQty } from '@/api/salesNew'
export default {
  name: 'PurchaseReturnEdit',
  mixins: [commonMixin],
  components: { STable, VSelect, basicInfoModal, addModal, importGuideModal },
  data () {
    return {
      spinning: false,
      showDetail: true, // 是否显示基础信息
      delLoading: false, // 删除loading
      openAddModal: false, // 打开新增产品弹窗
      openBasicInfoModal: false, // 打开编辑基础信息弹窗
      openGuideModal: false, // 导入产品弹窗
      detailsData: null, // 基础信息数据
      addMoreLoading: false, // 防止多次添加  加载状态
      loading: false, // 第三方库存按钮加载状态
      // 查询参数
      productForm: {
        productCode: '', // 产品编码
        productName: '' // 产品名称
      },
      statisticsObj: undefined, // 统计明细
      sparePartsSn: undefined, // 采购入库sn
      itemSn: undefined, // 列表行 sn
      itemObj: null, // 基础信息弹窗回显数据
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.productForm.sparePartsSn = this.sparePartsSn
        const parames = Object.assign(parameter, this.productForm)
        // 获取列表数据  有分页
        return purchaseDetailPageList(parames).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.getStatisticsData(parames)
            // 获取基础信息
            this.getBasicsData()
          }
          return data
        })
      }
    }
  },
  computed: {
    // 列表表头配置
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', align: 'center', width: '4%' },
        { title: '产品编码', dataIndex: 'productCode', width: '18%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '25%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '单位', dataIndex: 'unit', align: 'center', width: '6%', customRender: function (text) { return text || '--' } },
        { title: '采购数量', dataIndex: 'productQty', align: 'center', width: '13%', customRender: function (text) { return text || text == 0 ? text : '--' } },
        { title: '第三方库存', dataIndex: 'thirdStockQty', align: 'center', width: '10%', customRender: function (text) { return text || text == 0 ? text : '--' } },
        // { title: '采购单价', dataIndex: 'productCost', width: '8%', align: 'right', customRender: function (text) { return text || text == 0 ? _this.toThousands(text, 2) : '--' }, },
        // { title: '采购金额', dataIndex: 'subtotal', width: '8%', align: 'right', customRender: function (text) { return text || text == 0 ? _this.toThousands(text, 2) : '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      if (this.$hasPermissions('M_purchaseReceiptEdit_costPrice')) {
        arr.splice(6, 0, { title: '采购单价', dataIndex: 'productCost', width: '8%', align: 'right', customRender: function (text) { return text || text == 0 ? _this.toThousands(text, 2) : '--' } })
        if (this.detailsData && this.detailsData.supplierName) {
          arr.splice(7, 0, { title: '采购金额', dataIndex: 'subtotal', width: '8%', align: 'right', customRender: function (text) { return text || text == 0 ? _this.toThousands(text, 2) : '--' } })
        } else {
          arr.splice(7, 0, { title: '采购金额', dataIndex: 'subtotal', width: '8%', align: 'right', customRender: function (text) { return text || '--' } })
        }
      }
      return arr
    }
  },
  methods: {
    // 新增产品成功 刷新基础信息时间，防止重复提交
    handleAddOk () {
      this.pageInit()
    },
    // 第三方库存
    handleThirdQty () {
      const params = {
        sparePartsSn: this.sparePartsSn
      }
      getThirdStockQty(params).then(res => {
        if (res.status == 200) {
          this.handleAddOk(true)
        }
      })
    },
    // 导入产品
    hanldleImportOk (listCon) {
      this.spinning = true
      purchaseImportBatchInsert(listCon).then(res => {
        if (res.status == 200) {
          this.$message.success('导入成功')
          this.handleAddOk()
        }
        this.spinning = false
      })
    },
    // 编辑基础信息
    handleEditBase () {
      this.itemObj = { dealerName: this.detailsData.lockBizDealerName, lockBizNo: this.detailsData.lockBizNo, bizRemark: this.detailsData.bizRemark }
      this.openBasicInfoModal = true
    },
    //  返回列表并刷新
    handleBack () {
      this.$router.push({ name: 'purchaseReceiptList', query: { closeLastOldTab: true } })
    },
    // 新增/编辑产品
    handleAddEdit (row) {
      if (this.detailsData && !this.detailsData.supplierName) {
        this.$message.warning('供应商不能为空，请先编辑基础信息！')
        return
      }
      this.itemSn = (row && row.sparePartsDetailSn) ? row.sparePartsDetailSn : null
      this.openAddModal = true
    },
    // 导入产品
    handleImport () {
      this.openGuideModal = true
    },
    // 删除所选产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.delLoading = true
          _this.spinning = true
          purchaseDetailDel({ sn: row.sparePartsDetailSn })
            .then(res => {
              if (res.status == 200) {
                _this.resetTable(false)
              }
              _this.$message.info(res.message)
              _this.delLoading = false
              _this.spinning = false
            })
            .catch(err => {
              _this.$message.info(err.message)
              _this.delLoading = false
            })
        }
      })
    },
    // 刷新列表  更新操作时间
    resetTable (flag) {
      this.itemSn = undefined
      this.$refs.table.refresh(flag)
    },
    //  重置
    resetSearchForm () {
      this.productForm.productName = ''
      this.productForm.productCode = ''
      this.$refs.table.refresh(true)
    },
    // 提交采购入库
    handleSubmit (data) {
      this.spinning = true
      purchaseSubmit({ sn: this.sparePartsSn }).then(res => {
        if (res.status == 200) {
          this.handleBack()
          this.$message.success(res.message)
        }
        this.spinning = false
      })
    },
    // 初始化
    pageInit () {
      this.sparePartsSn = this.$route.query.sn
      this.$nextTick(() => {
        this.resetSearchForm()
      })
    },
    // 获取页面统计数据
    getStatisticsData (ajaxData) {
      purchaseDetailPageCount(ajaxData).then(res => {
        if (res.status == 200) {
          if (res.data) {
            this.statisticsObj = res.data
          } else {
            this.statisticsObj = null
          }
        }
      })
    },
    // 获取基础信息
    getBasicsData () {
      queryDetailCount({ sn: this.sparePartsSn }).then(res => {
        if (res.status == 200) {
          this.detailsData = res.data
        } else {
          this.detailsData = null
        }
      })
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) {
      // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
.purchaseReceiptEdit-wrap {
  position: relative;
  height: 100%;
  padding-bottom: 51px;
  box-sizing: border-box;
  > .ant-spin-nested-loading {
    overflow-y: scroll;
    height: 100%;
  }
  .showBtn{
    display:flex;
    align-items:center;
    margin-bottom:10px;
  }
  .purchaseReceiptEdit-cont {
    margin-top: 6px;
    .ant-divider-horizontal {
      margin: 10px 0 24px;
    }
    .total-bar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      > div {
        &:last-child {
          display: flex;
          align-items: center;
          justify-content: space-between;
          > div {
            padding: 0 10px;
          }
        }
      }
    }
  }
}
</style>
