<template>
  <div v-if="showPage" class="salesEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" @back="handleBack" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="salesEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <a style="margin: 0 15px;color: #666;font-size: 18px;font-weight: 600;">单号：{{ detailData&&detailData.salesBillNo || '--' }}</a>
          <span style="margin: 0 10px;color: #666;">客户名称：{{ detailData&&detailData.buyerName || '--' }}</span>
          <a-button
            id="salesEdit-edit-btn"
            v-if="detailData&&detailData.salesTragetType != 'DEALER'"
            size="small"
            @click="handleEdit"
            style="margin-left:10px"
            key="0">编辑</a-button>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra" v-if="$hasPermissions('B_salesPrint')">
          <a-checkbox v-model="printAllName" :checked="printAllName" id="salesQuery-printAllName">打印完整产品名称</a-checkbox>
          <a-checkbox v-model="printOrgCode" :checked="printOrgCode" id="salesQuery-printOrgCode">打印原厂编码</a-checkbox>
          <Print :disabled="dataSource.length==0" @handlePrint="handlePrint"></Print>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="salesEdit-cont">
        <!-- 查询配件列表 -->
        <queryPart
          ref="partQuery"
          :newLoading="isInster"
          @add="insterProduct"
          @isCost="isCost"></queryPart>
      </a-card>
      <a-card size="small" :bordered="false" class="salesEdit-cont">
        <!-- 总计 -->
        <a-alert v-if="detailData" style="margin-bottom: 10px;" type="info">
          <div slot="message" class="total-bar">
            <div>
              总售价：<strong>{{ detailData&&(detailData.totalAmount || detailData.totalAmount==0) ? toThousands(detailData.totalAmount) : '--' }}</strong>；
              总款数：<strong>{{ detailData&&(detailData.totalCategory || detailData.totalCategory==0) ? detailData.totalCategory : '--' }}</strong>；
              总数量：<strong>{{ detailData&&(detailData.totalQty || detailData.totalQty==0) ? detailData.totalQty : '--' }}</strong>；
              赠品总数量：<strong>{{ detailData&&(detailData.giftQty || detailData.giftQty==0) ? detailData.giftQty : '--' }}</strong>；
              <span v-if="isCosts">
                总成本价：<strong>{{ detailData&&(detailData.totalCost || detailData.totalCost==0) ? toThousands(detailData.totalCost) : '--' }}</strong>；
                毛利：<strong>{{ detailData&&(detailData.grossProfit || detailData.grossProfit==0) ? toThousands(detailData.grossProfit) : '--' }}</strong>；
              </span>
            </div>
            <div>
              <div>
                折扣金额：
                <a-input-number
                  id="discount"
                  size="small"
                  v-model.trim="detailData.discountAmount"
                  :min="0"
                  :precision="2"
                  :max="999999"/>
                <a-button size="small" type="primary" class="button-primary" @click="salesDiscount">打折</a-button>
              </div>
              <div>
                折扣：<strong>{{ detailData&&(detailData.discountRate || detailData.discountRate==0) ? detailData.discountRate+'%' : '--' }}</strong>；
                折后总售价：<strong>{{ detailData&&(detailData.discountedAmount || detailData.discountedAmount==0) ? toThousands(detailData.discountedAmount) : '--' }}</strong>；
              </div>
            </div>
          </div>
        </a-alert>
        <!-- 搜索条件 -->
        <div class="table-page-search-wrapper">
          <a-row :gutter="15">
            <a-col :md="24" :lg="12">
              <a-form-model :model="productForm" ref="ruleForm" layout="inline" @keyup.enter.native="$refs.table.refresh(true)" >
                <a-row :gutter="15">
                  <a-col :md="8" :sm="24">
                    <a-form-model-item label="产品编码">
                      <a-input v-model.trim="productForm.productCode" allowClear placeholder="输入产品编码" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :md="8" :sm="24">
                    <a-form-model-item label="产品名称">
                      <a-input v-model.trim="productForm.productName" allowClear placeholder="输入产品名称" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :md="8" :sm="24">
                    <a-form-model-item style="margin-bottom: 10px;">
                      <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="salesEdit-refresh">查询</a-button>
                      <a-button style="margin-left: 5px" @click="resetForm" id="salesEdit-reset">重置</a-button>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-form-model>
            </a-col>
            <a-col :md="24" :lg="12">
              <div style="float:right;overflow: hidden;margin-bottom:10px;">
                <a-checkbox :value="0" :checked="tbForm.indexOf('AUDIT')>=0" @change="(e)=>{tbFormChange(e,0)}" id="salesQuery-tbsh">同步审核</a-checkbox>
                <a-checkbox :value="1" :checked="tbForm.indexOf('STOCK_OUT')>=0" @change="(e)=>{tbFormChange(e,1)}" id="salesQuery-tbck">同步出库</a-checkbox>
                <a-checkbox :value="2" :checked="tbForm.indexOf('SETTLE')>=0" @change="(e)=>{tbFormChange(e,2)}" id="salesQuery-tbsk">同步收款</a-checkbox>
                <a-button
                  style="padding: 0 25px;"
                  type="primary"
                  :disabled="spinning"
                  class="button-primary"
                  @click="enableFundAccount && tbForm.length == 3 ? handleSettleAcountPay(null,0) : handleSubmit({})"
                  id="productInfoList-handleSubmit">提交</a-button>
                <a-button
                  type="default"
                  @click="openGuideModal=true"
                  style="margin-right:5px;"
                  id="salesEdit-import">导入产品</a-button>
                <a-button
                  type="default"
                  v-if="shelfInfo&&shelfInfo.state=='ENABLE'"
                  @click="showShelfModal=true"
                  style="margin-right:5px;"
                  id="salesEdit-shelf">货架产品</a-button>
                <a-button
                  type="primary"
                  ghost
                  @click="delSalerOrder"
                  :loading="delLoading"
                  id="salesEdit-del-all">整单删除</a-button>
              </div>
            </a-col>
          </a-row>
        </div>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          :pageSize="5"
          :rowClassName="(record, index) => record.cost > record.price ? 'redBg-row':''"
          bordered>
          <div slot="costTitle">
            <a-tooltip placement="top">
              <template slot="title">
                系统中不同批次的产品，成本价可能不同，此值是按照实际出库批次的成本计算得到。
              </template>
              <span style="margin-right: 5px;">实际总成本</span> <a-icon type="question-circle" />
            </a-tooltip>
          </div>
          <!-- 产品名称 -->
          <template slot="productName" slot-scope="text, record">
            <a-tag color="blue" v-if="record.shelfPlaceCode">{{ record.shelfPlaceCode }}</a-tag>
            <span>{{ text }}</span>
          </template>
          <!-- 产品编码 -->
          <template slot="productCode" slot-scope="text, record">
            <div v-if="detailData">
              <div v-if="isOwerEdit">
                <a-badge count="急" v-if="record.oosFlag == 1">
                  <div style="padding-right: 15px;">{{ text }}</div>
                </a-badge>
                <span v-else>{{ text }}</span>
              </div>
              <div v-else>
                <a-badge count="急" v-if="isAudit&&record.oosFlag == 1">
                  <div style="padding-right: 15px;">{{ text }}</div>
                </a-badge>
                <a-badge count="缺" v-else-if="!isAudit&&(!record.currentStockQty || record.currentStockQty < record.qty)">
                  <div style="padding-right: 15px;">{{ text }}</div>
                </a-badge>
                <span v-else>{{ text }}</span>
              </div>
            </div>
          </template>
          <!-- 售价 -->
          <template slot="price" slot-scope="text, record">
            <a-input-number
              id="salesEdit-price"
              size="small"
              v-model="record.price"
              :precision="2"
              :min="0"
              :max="999999"
              placeholder="请输入"
              @blur="e => priceBlur(e.target.value, record)"
              style="width: 100%;" />
          </template>
          <!-- 销售数量 -->
          <template slot="salesNums" slot-scope="text, record">
            <a-input-number
              id="salesEdit-salesNums"
              size="small"
              v-model="record.qty"
              :precision="0"
              :min="1"
              :max="999999"
              placeholder="请输入"
              @blur="e => qtyBlur(e.target.value, record)"
              style="width: 100%;" />
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button size="small" v-if="record.oosFlag == 0" type="link" class="button-primary" @click="handleViewDetail(record)">出库明细</a-button>
            <a-button
              size="small"
              type="link"
              :loading="delLoading"
              class="button-error"
              @click="handleDel(record)"
              id="productInfoList-Del">删除</a-button>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <!-- <div class="affix-cont"></div> -->
    <!-- 选择客户弹框 -->
    <choose-custom-modal ref="custModal" :show="openModal" @updateData="updateData" @cancel="openModal=false" />
    <!-- 导入产品 -->
    <importGuideModal :openModal="openGuideModal" :params="{salesBillSn: $route.params.sn, salesBillNo:detailData?detailData.salesBillNo:''}" @close="openGuideModal=false" @ok="hanldeImprotOk" />
    <!-- 收付款弹框 -->
    <settleModal ref="settleModal" @ok="settleAcountPay" :openModal="openSettleModal" @close="openSettleModal=false"></settleModal>
    <!-- 出库明细 -->
    <outInDetialModal ref="outInDetialModal" outBizType="SALES" :openModal="showOutInModal" @close="showOutInModal=false"></outInDetialModal>
    <!-- 选择货架产品 -->
    <chooseShelfProduct
      v-if="showShelfModal"
      ref="chooseShelfProduct"
      @add="insterProduct"
      @plAdd="plInsterProduct"
      :baseData="shelfInfo"
      :openModal="showShelfModal"
      @close="showShelfModal=false"></chooseShelfProduct>
  </div>
</template>
<script>
import { commonMixin } from '@/utils/mixin'
import { mapActions } from 'vuex'
import { STable, VSelect } from '@/components'
import queryPart from './queryPart.vue'
import chooseCustomModal from './chooseCustomModal.vue'
import importGuideModal from './importGuideModal.vue'
import settleModal from '@/views/financialManagement/settleModal/settleModal.vue'
import { stockByProductSn } from '@/api/stock'
import { queryByCustomerSn } from '@/api/shelf'
import { salesDetail, salesWriteSubmit, salesWriteDiscount, salesDetailPrint, salesDetailExport, salesDel } from '@/api/sales'
import { salesDetailList, salesDetailInsert, salesDetailInsertBatch, salesDetailUpdatePrice, salesDetailUpdateQty, salesDetailDel, salesDetailDelAll, salesDetailInsertImport } from '@/api/salesDetail'
import outInDetialModal from '@/views/common/outInDetialModal.vue'
import chooseShelfProduct from './chooseShelfProduct.vue'
import Print from '@/views/common/print.vue'
import { hdPrint } from '@/libs/JGPrint'
export default {
  name: 'SalesEdit',
  components: { STable, VSelect, queryPart, chooseCustomModal, Print, importGuideModal, settleModal, outInDetialModal, chooseShelfProduct },
  mixins: [commonMixin],
  data () {
    return {
      showOutInModal: false, // 出入库明细
      showPage: false,
      spinning: false,
      orderId: null, // 销售单id
      salesBillSn: null, // 销售单sn
      disabled: false, //  查询、重置按钮是否可操作
      isInster: false, // 是否正在添加产品
      openModal: false, // 客户弹框
      openGuideModal: false, // 导入产品弹框
      openSettleModal: false, // 打开收款弹框
      enableFundAccount: false, // 是否开启资金账户管理
      showShelfModal: false, // 货架产品弹框
      delLoading: false,
      detailData: { discountAmount: 0, id: null, salesBillSn: '' }, // 订单基础数据
      dataSource: [],
      productForm: {
        productName: '',
        productCode: '',
        orderBy: 'sales_bill_detail.CREATE_DATE desc'
      },
      tbForm: [], // 同步操作
      printOrgCode: false, // 打印原创编码
      printAllName: false, // 打印全部名称
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.productForm.salesBillSn = this.$route.params.sn
        return salesDetailList(Object.assign(parameter, this.productForm)).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
              data.list[i].qtyBackups = data.list[i].qty
              data.list[i].priceBackups = data.list[i].price
            }
            this.disabled = false
            this.dataSource = data.list || []
          }
          return data
        })
      },
      printerType: 'NEEDLE', //  打印机类型
      isCosts: false, // 是否显示成本价
      shelfInfo: null // 是否有货架
    }
  },
  computed: {
    // 是否自建单据
    isOwerEdit () {
      return this.detailData && this.detailData.sourceType == 'SALES'
    },
    // 是否审核通过
    isAudit () {
      return this.detailData && (this.detailData.billStatus == 'WAIT_OUT_WAREHOUSE' || this.detailData.billStatus == 'FINISH')
    },
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'dealerProductEntity.code', width: '13%', scopedSlots: { customRender: 'productCode' }, align: 'center' },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', width: '13%', align: 'center', scopedSlots: { customRender: 'productName' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'dealerProductEntity.origCode', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'dealerProductEntity.productBrandName', width: '8%', align: 'center', sorter: true, customRender: function (text) { return text || '--' } },
        // { title: '仓库', dataIndex: 'warehouseEntity.name', width: '8%', align: 'center', sorter: true, customRender: function (text) { return text || '--' } },
        // { title: '仓位', dataIndex: 'warehouseLocationEntity.name', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '售价', dataIndex: 'price', scopedSlots: { customRender: 'price' }, width: '7%', align: 'center' },
        { title: '销售数量', scopedSlots: { customRender: 'salesNums' }, width: '7%', align: 'center' },
        { title: '单位', dataIndex: 'dealerProductEntity.unit', width: '4%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '售价小计', dataIndex: 'totalAmount', width: '5%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '折后小计', dataIndex: 'discountedAmount', width: '5%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '7%', align: 'center' }
      ]
      // 下级创建，不显示仓库仓位
      if (!this.isOwerEdit) {
        arr.splice(7, 0, { title: '库存数量', dataIndex: 'currentStockQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      } else {
        arr.splice(5, 0, { title: '仓库', dataIndex: 'warehouseEntity.name', width: '8%', align: 'center', sorter: true, customRender: function (text) { return text || '--' } })
        arr.splice(6, 0, { title: '仓位', dataIndex: 'warehouseLocationEntity.name', width: '8%', align: 'center', customRender: function (text) { return text || '--' } })
      }
      // 实际总成本
      if (this.isCosts) {
        arr.splice(!this.isOwerEdit ? 11 : 12, 0, { slots: { title: 'costTitle' }, dataIndex: 'totalCost', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr
    }
  },
  methods: {
    ...mapActions(['GetSettleAccountState']),
    // 打印预览/快捷打印
    handlePrint (type, printerType) {
      const _this = this
      _this.spinning = true
      let url = salesDetailPrint
      const params = { sn: this.outBizSn || this.$route.params.sn, printOrgCode: this.printOrgCode ? 1 : 0, printAllName: this.printAllName ? 1 : 0 }
      if (type == 'export') { //  导出
        url = salesDetailExport
      }
      // 打印或导出
      hdPrint(printerType, type, url, params, '销售单', function () {
        _this.spinning = false
      })
    },
    tbFormChange (e, val) {
      this.tbForm = []
      const tbTypes = ['AUDIT', 'STOCK_OUT', 'SETTLE']
      if (e.target.checked) {
        for (let i = val; i >= 0; i--) {
          this.tbForm.push(tbTypes[i])
        }
      } else {
        this.tbForm = []
      }
    },
    // 编辑客户信息
    handleEdit () {
      this.openModal = true
      this.$refs.custModal.editCust(this.detailData)
    },
    // 更新产品列表
    updateData (priceType) {
      // 价格类型变更
      if (priceType != this.$route.params.priceType) {
        this.getOrderDetail(true)
        this.$router.push({ name: 'salesEdit', params: { id: this.orderId, sn: this.salesBillSn, priceType: priceType } })
      } else {
        this.getOrderDetail(true)
      }
    },
    // 非下级创建的单据，修改数量时校验库存
    validStock (val, record) {
      const _this = this
      this.spinning = true
      //  校验库存
      stockByProductSn({ productSn: record.productSn }).then(res => {
        if (res.status == 200) {
          if (res.data && (!res.data.currentStockQty || val <= res.data.currentStockQty)) {
            _this.changeQty(record)
          } else {
            this.$confirm({
              title: '提示',
              content: '库存不足，确认添加为急件吗？',
              centered: true,
              closable: true,
              onOk () {
                _this.changeQty(record)
              },
              onCancel () {
                record.qty = record.qtyBackups
                _this.spinning = false
              }
            })
          }
        } else {
          this.spinning = false
          record.qty = record.qtyBackups
        }
      })
    },
    // 修改已选产品数量
    changeQty (record) {
      salesDetailUpdateQty({
        id: record.id,
        salesBillSn: record.salesBillSn,
        productSn: record.productSn,
        salesBillDetailSn: record.salesBillDetailSn,
        qty: record.qty,
        price: record.price
      }).then(res => {
        this.resetSearchForm(false)
        if (res.status == 200) {
          this.$message.info(res.message)
        }
        this.spinning = false
      })
    },
    // 已选产品 销售数量 input 输入框 blur
    qtyBlur (val, record) {
      this.dataSource = record || []
      if (val && val != record.qtyBackups) {
        // 自建的单据，修改数量时校验库存
        if (this.isOwerEdit) {
          this.validStock(val, record)
        } else {
          this.changeQty(record)
        }
      } else {
        record.qty = record.qtyBackups
      }
    },
    // 已选产品 售价 input 输入框 blur
    priceBlur (val, record) {
      this.dataSource = record || []
      //  光标移出，值发生改变再调用编辑接口
      if (val && val != record.priceBackups) {
        this.spinning = true
        salesDetailUpdatePrice({
          id: record.id,
          salesBillSn: record.salesBillSn,
          productSn: record.productSn,
          salesBillDetailSn: record.salesBillDetailSn,
          qty: record.qty,
          price: record.price
        }).then(res => {
          this.resetSearchForm(false)
          if (res.status == 200) {
            this.$message.info(res.message)
            this.spinning = false
          } else {
            this.spinning = false
          }
        })
      } else {
        record.price = record.priceBackups
      }
    },
    isCost (val) {
      this.isCosts = val
    },
    //  重置
    resetSearchForm (flag) {
      if (flag) { this.$refs.partQuery.onlyList = true }
      this.$refs.table.refresh(!!flag)
      this.getOrderDetail(false)
    },
    // 重置列表
    resetForm () {
      this.productForm = {
        productName: '',
        productCode: '',
        orderBy: 'sales_bill_detail.CREATE_DATE desc'
      }
      this.$refs.table.refresh()
    },
    //  返回
    handleBack () {
      this.$router.push({ path: '/salesManagement/salesQuery/list' })
    },
    // 打折
    salesDiscount () {
      this.spinning = true
      salesWriteDiscount({
        discountAmount: this.detailData.discountAmount || 0,
        salesBillSn: this.detailData.salesBillSn,
        id: this.detailData.id
      }).then(res => {
        if (res.status == 200) {
          this.resetSearchForm(true)
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    // 删除销售单
    delSalerOrder () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认删除该销售单吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          salesDel({ id: _this.orderId }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.handleBack()
            }
            _this.spinning = false
          })
        }
      })
    },
    // 删除已选产品
    delSalerDetailAll () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要整单删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.delLoading = true
          _this.spinning = true
          salesDetailDelAll({ salesBillSn: _this.detailData.salesBillSn }).then(res => {
            if (res.status == 200) {
              _this.resetSearchForm(true)
              _this.productForm = {
                productName: '',
                productCode: '',
                orderBy: 'sales_bill_detail.CREATE_DATE desc'
              }
            }
            _this.$message.info(res.message)
            _this.delLoading = false
            _this.spinning = false
          })
        }
      })
    },
    // 出入库明细
    handleViewDetail (row) {
      this.showOutInModal = true
      this.$refs.outInDetialModal.getData(row)
    },
    // 删除产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.delLoading = true
          _this.spinning = true
          salesDetailDel({ id: row.id }).then(res => {
            if (res.status == 200) {
              _this.resetSearchForm(false)
            }
            _this.$message.info(res.message)
            _this.delLoading = false
            _this.spinning = false
          })
        }
      })
    },
    // 添加产品
    insterProduct (row) {
      // 防止多次添加产品
      if (this.isInster) { return }
      const _this = this
      // 判断是否已添加此产品
      if (this.dataSource && this.dataSource.length > 0) {
        const hasRow = this.dataSource.find(item => item.productSn == row.productSn)
        if (hasRow) {
          this.$message.info('该产品已在当前销售单中存在！')
          this.productForm = {
            productName: '',
            productCode: hasRow.dealerProductEntity && hasRow.dealerProductEntity.code || '',
            orderBy: 'sales_bill_detail.CREATE_DATE desc'
          }
          this.$refs.table.refresh(true)
          return
        } else {
          this.productForm = {
            productName: '',
            productCode: '',
            orderBy: 'sales_bill_detail.CREATE_DATE desc'
          }
        }
      }
      // 自建的单据显示库存不足时
      if (row.currentQty < row.salesNums && this.isOwerEdit) {
        _this.$confirm({
          title: '提示',
          content: '库存不足，确认添加为急件吗？',
          centered: true,
          closable: true,
          onOk () {
            _this.isPutCostDyPrice(row)
          }
        })
      } else {
        _this.isPutCostDyPrice(row)
      }
    },
    // 判断售价低于成本价
    isPutCostDyPrice (row) {
      const _this = this
      if (row.putCost > row.price) {
        // 销售价低于成本价
        _this.$confirm({
          title: '提示',
          content: '售价低于成本价，确认要添加吗？',
          centered: true,
          closable: true,
          onOk () {
            _this.saveNewProduct(row)
          }
        })
      } else {
        _this.saveNewProduct(row)
      }
    },
    // 保存添加的产品到销售列表
    saveNewProduct (row) {
      this.$message.loading('正在添加产品...', 1)
      this.isInster = true
      // this.spinning = true
      salesDetailInsert({
        buyerSn: this.detailData.buyerSn,
        productSn: row.productSn,
        cost: row.putCost,
        // productCode: row.productCode,
        // productOrigCode: row.productOrigCode,
        price: row.price,
        qty: row.salesNums,
        salesBillSn: this.detailData.salesBillSn,
        salesBillNo: this.detailData.salesBillNo,
        warehouseSn: row.warehouseSn,
        warehouseLocationSn: row.warehouseLocationSn,
        stockSn: row.stockSn
      }).then(res => {
        if (res.status == 200) {
          // this.resetSearchForm(true)  //  不刷新库存
          this.$refs.table.refresh(true)
          this.getOrderDetail(false)
          if (this.showShelfModal) {
            this.$refs.chooseShelfProduct.reload()
          }
        }
        this.isInster = false
        // this.spinning = false
      })
    },
    // 批量添加接口
    plInsterProduct (list) {
      const params = []
      list.map(item => {
        params.push({
          buyerSn: this.detailData.buyerSn,
          productSn: item.productSn,
          cost: item.putCost,
          price: item.price,
          qty: item.salesNums,
          salesBillSn: this.detailData.salesBillSn,
          salesBillNo: this.detailData.salesBillNo,
          stockSn: item.stockSn
        })
      })
      this.$message.loading('正在批量添加产品...', 1)
      salesDetailInsertBatch(params).then(res => {
        if (res.status == 200) {
          this.$refs.table.refresh(true)
          this.getOrderDetail(false)
          if (this.showShelfModal) {
            this.$refs.chooseShelfProduct.reload()
          }
        }
      })
    },
    //  销售单详情
    getOrderDetail (flag) {
      salesDetail({ id: this.$route.params.id }).then(res => {
        if (res.status == 200) {
          this.detailData = res.data
          if (flag) {
            const vm = this
            const buyerSn = (vm.detailData && vm.detailData.buyerSn && vm.detailData.sourceType && vm.detailData.sourceType == 'PURCHASE') ? '' : vm.detailData.buyerSn
            const priceType = vm.$route.params.priceType
            vm.$refs.partQuery.pageInit(buyerSn, priceType, vm.salesBillSn)
            // 查询关联的客户
            if (vm.detailData && vm.detailData.buyerSn) {
              this.getShelfQueryByCustomer()
            }
          }
        }
      })
    },
    getShelfQueryByCustomer () {
      queryByCustomerSn({ sn: this.detailData.buyerSn }).then(res => {
        if (res.data) {
          this.shelfInfo = Object.assign(res.data, { salePriceType: this.$route.params.priceType, salesBillSn: this.salesBillSn })
        } else {
          this.shelfInfo = null
        }
      })
    },
    // 提交销售单
    handleSubmit (params) {
      this.spinning = true
      const submitTypes = this.tbForm.join(',')
      salesWriteSubmit({ id: this.orderId, submitTypes: submitTypes, ...params }).then(res => {
        console.log(res)
        if (res.status == 200) {
          this.handleBack()
          this.$message.success(res.message)
          // this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    // 开启结算账户功能收款, type:0 单条收款，1 批量收款
    handleSettleAcountPay (row, type) {
      this.openSettleModal = true
      const data = {
        totalAmount: this.detailData.discountedAmount,
        settleClientName: '',
        title: '收款',
        type,
        row
      }
      this.$nextTick(() => {
        this.$refs.settleModal.setData(data)
      })
    },
    // 去收款
    settleAcountPay (form, data) {
      const params = {}
      // 资金管理开启
      if (this.enableFundAccount) {
        params.settleStyleSn = form.settleStyleSn
        params.settleAccountSn = form.settleAccountSn
      }
      this.spinning = true
      this.handleSubmit(params)
    },
    // 确认导入明细
    hanldeImprotOk (obj) {
      this.spinning = true
      salesDetailInsertImport(obj).then(res => {
        if (res.status == 200) {
          this.$refs.table.refresh(true)
          this.getOrderDetail(false)
        }
        this.spinning = false
      })
    },
    pageInit () {
      const vm = this
      vm.$nextTick(() => {
        vm.orderId = vm.$route.params.id
        vm.salesBillSn = vm.$route.params.sn
        // 是否默认打印原厂编码
        vm.printOrgCode = localStorage.getItem('printOrgCode-' + this.$store.state.user.info.orgId) == 'true'
        vm.printAllName = localStorage.getItem('printAllName-' + this.$store.state.user.info.orgId) == 'true'
        vm.getOrderDetail(true)
        vm.$refs.table.refresh(true)
      })
    }
  },
  watch: {
    printOrgCode (newValue, oldValue) {
      localStorage.setItem('printOrgCode-' + this.$store.state.user.info.orgId, newValue)
    },
    printAllName (newValue, oldValue) {
      localStorage.setItem('printAllName-' + this.$store.state.user.info.orgId, newValue)
    }
  },
  mounted () {
    this.showPage = true
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    this.showPage = true
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
    // 结算账户状态查询
    if (this.$hasPermissions('M_fundAccountList') && this.$hasPermissions('B_fundAccountEnable')) {
    	this.GetSettleAccountState().then(res => {
    	  if (res.status == 200) {
    		this.enableFundAccount = res.data.functionEnableFlag == 1
    	  }
    	})
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .salesEdit-wrap{
    position: relative;
    height: 100%;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: auto;
      height: 100%;
    }
    .salesEdit-cont{
      margin-top: 10px;
    }
    .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;
          }
        }
      }
    }
    .redBg-row{
      background-color: #f5cdc8;
    }
  }
</style>
