<template>
  <div v-if="showPage" class="jg-page-wrap salesEdit-news-wrap">
    <a-page-header :ghost="false" :backIcon="false" class="header-bar">
      <!-- 自定义的二级文字标题 -->
      <template slot="subTitle">
        <a class="billno" style="margin-right:15px;">单号：{{ detailData&&detailData.salesBillNo || '--' }}</a>
        <a-tag color="green" v-if="detailData.billStatusDictValue">{{ detailData.billStatusDictValue }}</a-tag>
        <a-tag color="orange" v-if="detailData.financialStatusDictValue">{{ detailData.financialStatusDictValue }}</a-tag>
        <span style="margin-left:10px;color: #666;">客户名称：{{ detailData&&detailData.buyerNameCurrent?detailData.buyerName?detailData.buyerNameCurrent==detailData.buyerName?detailData.buyerNameCurrent:detailData.buyerNameCurrent+'（'+detailData.buyerName+'）':detailData.buyerNameCurrent:'--' }}</span>
        <a-button
          id="salesEdit-edit-btn"
          type="link"
          style="margin-left:10px"
          v-if="detailData&&detailData.salesTragetType != 'DEALER'"
          size="small"
          class="button-info"
          @click="handleEdit"
          key="0"><a-icon type="edit" /> 编辑</a-button>
        <a-button id="purchaseNewOrderEdit-back-btn" type="link" @click="handleBack" class="button-default"> <a-icon type="rollback" /> 返回列表</a-button>
        <span style="margin-right:10px;color: #ED1C24;" v-if="detailData.sourceType==='XPRH_PURCHASE'">请注意：该销售单若为促销订单，增删改产品会影响促销活动</span>
      </template>
      <!-- 操作区，位于 title 行的行尾 -->
      <template slot="extra" v-if="$hasPermissions('B_salesPrint')">
        <div style="margin-top: 5px;">
          <PrintPanel ref="printBox" :disabled="dataSource.length==0" @handlePrint="handlePrint">
            <div style="padding:10px;" slot="extendCons">
              <a-checkbox v-model="printAllName" :checked="printAllName" id="salesQuery-printAllName">打印完整产品名称</a-checkbox>
              <a-checkbox v-model="printOrgCode" :checked="printOrgCode" id="salesQuery-printOrgCode">打印原厂编码</a-checkbox>
              <a-checkbox v-model="printPrice" :checked="printPrice" id="salesQuery-printPrice">打印售价</a-checkbox>
              <a-checkbox v-model="printRemarks" :checked="printRemarks" id="salesQuery-printRemarks">打印备注</a-checkbox>
              <a-checkbox v-model="printNo" :checked="printNo" id="salesQuery-printNo">打印销售单号</a-checkbox>
            </div>
          </PrintPanel>
          <a-divider type="vertical" v-if="detailData&&detailData.totalCategory" />
          <a-button type="link" v-if="detailData&&detailData.totalCategory" @click="showSearch=!showSearch" :class="showSearch?'button-error':'button-default'"> <a-icon type="search" /> 筛选</a-button>
          <a-divider type="vertical" v-if="detailData&&detailData.totalCategory" />
          <a-button v-if="detailData&&detailData.totalCategory" id="salesNewOrderEdit-add-btn" type="link" @click="openChooseProduct=true"><a-icon type="plus" />添加产品</a-button>
          <a-divider type="vertical" v-if="detailData&&detailData.totalCategory" />
          <a-dropdown v-model="showCell" v-if="$hasPermissions('M_ShowAllCost')&&detailData&&detailData.totalCategory">
            <a-button type="link" class="button-default" id="salesQuery-edit-showCell"> <a-icon type="setting" />  显示</a-button>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-checkbox v-model="isCosts" id="salesQuery-edit-cost">成本价</a-checkbox>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
          <a-divider type="vertical" v-if="$hasPermissions('M_ShowAllCost')"/>
          <a-dropdown>
            <a-menu slot="overlay" @click="handleActions" id="salesQuery-edit-action-menus">
              <a-menu-item key="4" id="salesQuery-edit-import">
                <a-icon type="import" />导入产品
              </a-menu-item>
              <a-menu-item key="3" v-if="shelfInfo&&shelfInfo.state=='ENABLE'" id="salesQuery-edit-shelfproduct">
                <a-icon type="hdd"/>货架产品
              </a-menu-item>
              <a-menu-item key="2" id="salesQuery-edit-delAll">
                <a-icon type="close-square"/>清空列表
              </a-menu-item>
              <a-menu-item key="1" id="salesQuery-edit-delJdOrQh">
                <a-icon type="rest" style="font-size: 14px;" />{{ isOwerEdit?'删除急件':'删除缺货' }}
              </a-menu-item>
            </a-menu>
            <a-button id="salesQuery-edit-moreBtn" type="link" class="button-default"> <a-icon type="unordered-list" />  更多</a-button>
          </a-dropdown>
        </div>
      </template>
    </a-page-header>
    <!-- 已选产品 -->
    <div class="choosedList-cont">
      <div class="choosed-table" v-if="detailData&&detailData.totalCategory">
        <!-- 搜索条件 -->
        <div class="table-page-search-wrapper" style="margin-bottom:0;" v-if="showSearch">
          <a-form-model :model="productForm" ref="ruleForm" layout="inline" @keyup.enter.native="$refs.table.refresh(true)" >
            <a-row :gutter="10">
              <a-col :md="5" :sm="24">
                <a-form-model-item label="产品编码">
                  <a-input id="salesQuery-edit-productCode" v-model.trim="productForm.productCode" allowClear placeholder="输入产品编码" />
                </a-form-model-item>
              </a-col>
              <a-col :md="5" :sm="24">
                <a-form-model-item label="产品名称">
                  <a-input id="salesQuery-edit-productName" v-model.trim="productForm.productName" allowClear placeholder="输入产品名称" />
                </a-form-model-item>
              </a-col>
              <a-col :md="4" :sm="24" v-if="isOwerEdit">
                <a-form-item label="是否为急件">
                  <a-select id="salesQuery-edit-oosFlag" allowClear v-model="productForm.oosFlag" placeholder="请选择是否">
                    <a-select-option value="1">
                      是
                    </a-select-option>
                    <a-select-option value="0">
                      否
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <!-- <a-col :md="4" :sm="24" v-else>
                <a-form-item label="是否为缺货">
                  <a-select allowClear v-model="productForm.oosFlag" placeholder="请选择是否">
                    <a-select-option value="1">
                      是
                    </a-select-option>
                    <a-select-option value="0">
                      否
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col> -->
              <a-col :md="4" :sm="24">
                <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-col>
            </a-row>
          </a-form-model>
        </div>
        <div class="discount-box">

        </div>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          :pageSize="30"
          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 :title="text">{{ 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">
            <div style="display:flex;align-items: center;" :class="record.cost > record.price?'redBg-row':''">
              <div v-if="record.cost > record.price">
                <a-tooltip placement="top">
                  <template slot="title">
                    售价低于成本价
                  </template>
                  <a-icon type="warning" />
                </a-tooltip>
              </div>
              <a-input-number
                size="small"
                :id="'salesEdit-price-'+record.id"
                v-model="record.price"
                :precision="2"
                :min="0"
                :max="999999"
                placeholder="请输入"
                @blur="e => priceBlur(e.target.value, record)"
                style="flex-grow: 1;margin-left: 3px;text-align: right;"
              />
            </div>
          </template>
          <!-- 销售数量 -->
          <template slot="salesNums" slot-scope="text, record">
            <a-input-number
              :id="'salesEdit-salesNums-'+record.id"
              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
              :id="'salesEdit-viewRecord-'+record.id"
              size="small"
              v-if="record.oosFlag == 0 && isOwerEdit"
              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="'salesEdit-del-'+record.id">删除</a-button>
          </template>
        </s-table>
      </div>
      <div class="choosed-table" v-else>
        <div v-if="!spinning&&detailData.totalCategory==0">
          <a-empty
            :image="simpleImage"
            :image-style="{
              height: '60px',
            }"
          >
            <span slot="description"> 暂无产品 </span>
            <a-button id="salesEdit-newAddProduct" type="primary" class="button-error" @click="openChooseProduct=true"><a-icon type="plus" />立即添加产品</a-button>
          </a-empty>
        </div>
        <div style="text-align: center;padding: 30px 50px;" v-if="spinning">
          <a-spin :spinning="spinning" tip="Loading..."></a-spin>
        </div>
      </div>

      <!-- 底部栏 -->
      <div class="footer-bar" v-if="detailData&&detailData.totalCategory">
        <!-- 总计 -->
        <div v-if="detailData" class="total-bar">
          <div>
            总款数：<span>{{ detailData&&(detailData.totalCategory || detailData.totalCategory==0) ? detailData.totalCategory : '--' }}</span>，
            总数量：<span>{{ detailData&&(detailData.totalQty || detailData.totalQty==0) ? detailData.totalQty : '--' }}</span>，
            赠品总数量：<span>{{ detailData&&(detailData.giftQty || detailData.giftQty==0) ? detailData.giftQty : '--' }}</span>，
            <template v-if="isCosts">
              总成本价：<span class="red">{{ detailData&&(detailData.totalCost || detailData.totalCost==0) ? toThousands(detailData.totalCost) : '--' }}</span>，
              毛利：<span class="red">{{ detailData&&(detailData.grossProfit || detailData.grossProfit==0) ? toThousands(detailData.grossProfit) : '--' }}</span>，
            </template>
            <div style="display: inline-block;">
              总售价：<span class="red">{{ detailData&&(detailData.totalAmount || detailData.totalAmount==0) ? toThousands(detailData.totalAmount) : '--' }}</span>
            </div>
          </div>
          <div>
            <div style="display: inline-block;">
              折扣金额：
              <a-input-number
                id="salesEdit-discount"
                size="small"
                v-model.trim="detailData.discountAmount"
                @blur="salesDiscount"
                :min="0"
                :precision="2"
                :max="999999"/>
              折扣：<span class="red">{{ detailData&&(detailData.discountRate || detailData.discountRate==0) ? detailData.discountRate+'%' : '--' }}</span>，
            </div>
            <div class="totalPrice" style="display: inline-block;padding:0;">
              折后合计：<strong>{{ detailData&&(detailData.discountedAmount || detailData.discountedAmount==0) ? toThousands(detailData.discountedAmount) : '--' }}</strong>
            </div>
          </div>
        </div>
        <div>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item key="1"> <a-checkbox :value="0" :checked="tbForm.indexOf('AUDIT')>=0" @change="(e)=>{tbFormChange(e,0)}" id="salesQuery-tbsh">同步审核</a-checkbox> </a-menu-item>
              <a-menu-item key="2"> <a-checkbox :value="1" :checked="tbForm.indexOf('STOCK_OUT')>=0" @change="(e)=>{tbFormChange(e,1)}" id="salesQuery-tbck">同步出库</a-checkbox> </a-menu-item>
              <a-menu-item key="3"> <a-checkbox :value="2" :checked="tbForm.indexOf('SETTLE')>=0" @change="(e)=>{tbFormChange(e,2)}" id="salesQuery-tbsk">同步收款</a-checkbox></a-menu-item>
            </a-menu>
            <a-button id="salesEdit-tb-action" style="margin-left: 8px" size="large"> 选择同步操作 <a-icon type="down" /> </a-button>
          </a-dropdown>
        </div>
        <div>
          <a-button
            type="primary"
            id="salesEdit-handleSubmit"
            size="large"
            class="button-primary"
            :loading="spinning"
            @click="enableFundAccount && tbForm.length == 3 ? handleSettleAcountPay(null,0) : handleSubmit({})"
            style="padding: 0 60px;">提交</a-button>
        </div>
      </div>
    </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"></importGuideModal>
    <!-- 收付款弹框 -->
    <settleModal ref="settleModal" @ok="settleAcountPay" :openModal="openSettleModal" @close="openSettleModal=false"></settleModal>
    <!-- 出库明细 -->
    <outInDetialModal ref="outInDetialModal" outBizType="SALES" :openModal="showOutInModal" @close="showOutInModal=false"></outInDetialModal>
    <!-- 销售记录 -->
    <product-salesRecord-modal ref="salseRecord" :openModal="openSalesRecordModal" @close="openSalesRecordModal=false" />
    <!-- 添加产品 -->
    <chooseProductModal
      ref="partQuery"
      :newLoading="isInster"
      :showModal="openChooseProduct"
      :checkedList="checkedProductList"
      @viewRecord="hanldSalesRecord"
      @close="openChooseProduct=false"
      @add="insterProduct"
    ></chooseProductModal>
    <!-- 选择货架产品 -->
    <chooseShelfProduct
      v-if="showShelfModal"
      ref="chooseShelfProduct"
      @viewRecord="hanldSalesRecord"
      @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 { Empty } from 'ant-design-vue'
import { hdPrint } from '@/libs/JGPrint'
// 组件
import { STable, VSelect } from '@/components'
import outInDetialModal from './outInDetialModal.vue'
import chooseShelfProduct from './chooseShelfProduct.vue'
import PrintPanel from '@/views/common/printPanel.vue'
import chooseProductModal from './chooseProductModal.vue'
import chooseCustomModal from './chooseCustomModal.vue'
import importGuideModal from './importGuideModal.vue'
import settleModal from '@/views/financialManagement/settleModal/settleModal.vue'
import productSalesRecordModal from './productSalesRecordModal.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, salesDetailInsertImport, queryCheckedList } from '@/api/salesDetail'

export default {
  name: 'SalesEdit',
  components: { STable, VSelect, chooseProductModal, chooseCustomModal, PrintPanel, importGuideModal, settleModal, outInDetialModal, chooseShelfProduct, productSalesRecordModal },
  mixins: [commonMixin],
  data () {
    return {
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE, // 默认空图片
      tableHeight: 0, // 表格高度
      showOutInModal: false, // 出入库明细
      showCell: false, // 显示列下拉选项
      showPage: false, // 是否显示组件
      spinning: false,
      showSearch: false, // 是否显示查询条件
      openChooseProduct: false, // 是否显示产品列表弹框
      orderId: null, // 销售单id
      salesBillSn: null, // 销售单sn
      disabled: false, //  查询、重置按钮是否可操作
      isInster: false, // 是否正在添加产品
      openModal: false, // 客户弹框
      openSalesRecordModal: false, // 销售记录
      openGuideModal: false, // 导入产品弹框
      openSettleModal: false, // 打开收款弹框
      enableFundAccount: false, // 是否开启资金账户管理
      showShelfModal: false, // 货架产品弹框
      checkedProductList: [], // 已选所有产品
      delLoading: false, // 按钮loading
      detailData: { discountAmount: 0, id: null, salesBillSn: '' }, // 订单基础数据
      dataSource: [], // 原始数据
      productForm: {
        productName: '', // 产品名称
        productCode: '', // 产品编码
        oosFlag: undefined, // 是否急件
        orderBy: 'sales_bill_detail.CREATE_DATE desc' // 排序
      },
      tbForm: [], // 同步操作选项值
      printOrgCode: false, // 是否打印原创编码
      printAllName: false, // 是否打印全部名称
      printRemarks: false, // 是否打印备注
      printNo: true, // 是否打印销售单号
      printPrice: false, // 是否打印价格
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        this.productForm.salesBillSn = this.$route.params.sn
        this.getChoosedList({ 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 || []
          }
          this.spinning = false
          return data
        })
      },
      printerType: 'NEEDLE', //  打印机类型
      isCosts: false, // 是否显示成本价
      shelfInfo: null, // 是否有货架
      discountAmountBak: 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: '11%', scopedSlots: { customRender: 'productCode' }, align: 'center' },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', width: '15%', align: 'left', 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: '10%', 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.detailData && this.detailData.sourceType && this.detailData.sourceType === 'XPRH_PURCHASE') {
        arr.splice(10, 0, { title: <a-tooltip placement="bottom" title='返券金额以销售单完结时的活动规则为准'>返券金额&nbsp;<a-icon type="question-circle" /></a-tooltip>, dataIndex: 'giveAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(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']),
    // 更多操作
    handleActions (e) {
      // 导入产品
      if (e.key == 4) {
        this.openGuideModal = true
      }
      // 货架产品
      if (e.key == 3) {
        this.showShelfModal = true
      }
      if (e.key == 2) { // 清空列表
        this.delSalerOrder()
      }
      if (e.key == 1) { // 删除急件
        this.delSalerOrder(this.isOwerEdit ? 1 : 2)
      }
    },
    // 打印预览/快捷打印
    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,
        remarksShowFlag: this.printRemarks ? 1 : 0,
        printNo: this.printNo ? 1 : 0,
        priceFlag: this.printPrice ? 1 : 0
      }
      if (type == 'export') { //  导出
        url = salesDetailExport
      }
      // 打印或导出
      hdPrint(printerType, type, url, params, '销售单', function () {
        _this.spinning = false
        _this.$refs.printBox.hovered = 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)
    },
    // 查看销售记录
    hanldSalesRecord (row) {
      console.log(row)
      this.openSalesRecordModal = true
      this.$refs.salseRecord.getDetail(this.detailData.buyerSn, row.productSn, row)
    },
    // 查询已选所以产品
    getChoosedList (params) {
      this.isInster = true
      queryCheckedList(params).then(res => {
        this.checkedProductList = res.data || []
        this.isInster = false
      })
    },
    // 更新产品列表
    updateData (priceType) {
      // 价格类型变更
      if (priceType != this.$route.params.priceType) {
        this.getOrderDetail(true)
        this.$router.push({ name: 'salesNewEdit', 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.getOrderDetail(false, true)
        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.getOrderDetail(false, true)
          if (res.status == 200) {
            this.$message.info(res.message)
            this.spinning = false
          } else {
            this.spinning = false
          }
        })
      } else {
        record.price = record.priceBackups
      }
    },
    // 重置列表
    resetForm () {
      this.productForm = {
        productName: '',
        productCode: '',
        oosFlag: undefined,
        orderBy: 'sales_bill_detail.CREATE_DATE desc'
      }
      this.$nextTick(() => {
        this.$refs.table.refresh()
      })
    },
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesNewList' })
    },
    // 打折
    salesDiscount () {
      if (this.discountAmountBak == this.detailData.discountAmount) {
        return false
      }
      this.spinning = true
      salesWriteDiscount({
        discountAmount: this.detailData.discountAmount || 0,
        salesBillSn: this.detailData.salesBillSn,
        id: this.detailData.id
      }).then(res => {
        if (res.status == 200) {
          this.getOrderDetail(true)
        } else {
          this.spinning = false
        }
      })
    },
    // 清空已选产品
    delSalerOrder (flag) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: !flag ? '确认要清空已选产品列表吗？' : (flag == 1 ? '确认要删除所有急件吗？删除后不可恢复。' : '确认要删除所有缺货吗？删除后不可恢复。'),
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          const params = { id: _this.orderId, oosFlag: !flag ? undefined : 1 }
          salesDel(params).then(res => {
            if (res.status == 200) {
              _this.getOrderDetail(true)
              if (!flag) {
                _this.dataSource = []
              }
              _this.$message.success(res.message)
            }
            _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.getOrderDetail(false, true)
            }
            _this.$message.info(res.message)
            _this.delLoading = false
            _this.spinning = false
          })
        }
      })
    },
    // 添加产品
    insterProduct (row) {
      // 防止多次添加产品
      if (this.isInster) { return }
      const _this = this
      // 自建的单据显示库存不足时
      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,
        priceLevel: row.priceLevel,
        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.getOrderDetail(true)
          if (this.showShelfModal) {
            this.$refs.chooseShelfProduct.reload()
          }
        } else {
          if (res.errCode == 'VALID_F_00001') {
            this.productForm = {
              productName: '',
              productCode: row.productCode || '',
              orderBy: 'sales_bill_detail.CREATE_DATE desc'
            }
            this.showSearch = true
            this.$refs.table.refresh(true)
          }
          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,
          priceLevel: item.priceLevel,
          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.getOrderDetail(true)
          if (this.showShelfModal) {
            this.$refs.chooseShelfProduct.reload()
          }
        }
      })
    },
    //  销售单详情
    getOrderDetail (flag, resetTable) {
      const vm = this
      vm.spinning = true
      salesDetail({ id: vm.$route.params.id }).then(res => {
        if (res.status == 200) {
          vm.detailData = res.data
          vm.discountAmountBak = vm.detailData.discountAmount
          if (res.data.delFlag == 1) {
            vm.$message.info('该销售单已删除')
            vm.handleBack()
            return false
          }
          if (flag) {
            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.totalCategory) {
              vm.resetForm()
            } else {
              vm.spinning = false
              vm.checkedProductList = []
            }
            // 查询关联的客户货架信息
            if (vm.detailData && vm.detailData.buyerSn) {
              vm.getShelfQueryByCustomer()
            }
          } else {
            if (resetTable) {
              vm.$refs.table.refresh()
            } else {
              vm.spinning = false
            }
          }
        }
      })
    },
    // 查询关联的客户货架信息
    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 => {
        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.getOrderDetail(true)
        }
        this.spinning = false
      })
    },
    // 计算表格高度
    setTableH () {
      this.tableHeight = window.innerHeight - (this.showSearch ? 42 : 0) - 300
    },
    // 页面初始话
    pageInit () {
      const vm = this
      vm.$nextTick(() => {
        vm.setTableH()
        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.printRemarks = localStorage.getItem('printRemarks-' + this.$store.state.user.info.orgId) == 'true'
        vm.printPrice = localStorage.getItem('printPrice-' + this.$store.state.user.info.orgId) == 'true'
        const printNo = localStorage.getItem('printNo-' + this.$store.state.user.info.orgId)
        vm.printNo = printNo ? printNo == 'true' : true
        // 获取详情
        vm.getOrderDetail(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)
    },
    printPrice (newValue, oldValue) {
      localStorage.setItem('printPrice-' + this.$store.state.user.info.orgId, newValue)
    },
    printRemarks (newValue, oldValue) {
      localStorage.setItem('printRemarks-' + this.$store.state.user.info.orgId, newValue)
    },
    printNo (newValue, oldValue) {
      localStorage.setItem('printNo-' + this.$store.state.user.info.orgId, newValue)
    },
    showSearch (newValue, oldValue) {
      this.setTableH()
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  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-news-wrap{
    position: relative;
    height: 100%;
    box-sizing: border-box;

    .choosedList-cont{
      position: relative;
      background-color: #fff;
      height: calc(100% - 60px);
      .choosed-table{
        position: relative;
      }
      .redBg-row{
        color: #f5452e;
        input{
          color: #f5452e;
        }
      }
      .discount-box{
        position: absolute;
        left: 15px;
        bottom: 15px;
        .red{
          color: #f5452e;
          font-size: 14px;
        }
      }
    }
    .total-bar{
      > div{
        text-align: right;
        &:first-child{
          span{
            color: #666;
          }
          .red{
            color: #f5452e;
            font-size: 14px;
          }
        }
        &:last-child{
          display: flex;
          align-items: center;
          justify-content: flex-end;
        }
      }
    }
  }
</style>
