<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>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra" v-if="$hasPermissions('B_salesPrint')">
          <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) ? '￥'+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) ? detailData.totalCost : '--' }}</strong>；
                毛利：<strong>{{ detailData&&(detailData.grossProfit || detailData.grossProfit==0) ? detailData.grossProfit : '--' }}</strong>；
              </span>
            </div>
            <div>
              <div>
                折扣金额：
                <a-input-number
                  id="discount"
                  size="small"
                  v-model="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) ? '￥'+detailData.discountedAmount : '--' }}</strong>；
              </div>
            </div>
          </div>
        </a-alert>
        <!-- 搜索条件 -->
        <div class="table-page-search-wrapper">
          <a-row :gutter="15">
            <a-col :span="18">
              <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 :span="6">
              <div style="float:right;overflow: hidden;">
                <a-button
                  type="primary"
                  @click="delSalerOrder"
                  :loading="delLoading"
                  style="margin-right: 10px"
                  id="salesEdit-del-all">整单删除</a-button>
                <a-button
                  style="padding: 0 25px;"
                  type="primary"
                  :disabled="spinning"
                  class="button-primary"
                  @click="handleSubmit()"
                  id="productInfoList-handleSubmit">提交</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>
          <!-- 产品编码 -->
          <template slot="productCode" slot-scope="text, record">
            <a-badge count="急" v-if="record.oosFlag == 1">
              <div style="padding-right: 15px;">{{ text }}</div>
            </a-badge>
            <span v-else>{{ text }}</span>
          </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"
              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" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import queryPart from './queryPart.vue'
import chooseCustomModal from './chooseCustomModal.vue'
import { stockByProductSn } from '@/api/stock'
import { salesDetail, salesWriteSubmit, salesWriteDiscount, salesDetailPrint, salesDetailExport, salesDel } from '@/api/sales'
import { salesDetailList, salesDetailInsert, salesDetailUpdatePrice, salesDetailUpdateQty, salesDetailDel, salesDetailDelAll } from '@/api/salesDetail'
import Print from '@/views/common/print.vue'
import { hdPrint } from '@/libs/JGPrint'
export default {
  name: 'SalesEdit',
  components: { STable, VSelect, queryPart, chooseCustomModal, Print },
  mixins: [commonMixin],
  data () {
    return {
      showPage: false,
      spinning: false,
      orderId: null, // 销售单id
      salesBillSn: null, // 销售单sn
      disabled: false, //  查询、重置按钮是否可操作
      isInster: false, // 是否正在添加产品
      openModal: false, // 客户弹框
      delLoading: false,
      detailData: { discountAmount: 0, id: null, salesBillSn: '' }, // 订单基础数据
      dataSource: [],
      productForm: {
        productName: '',
        productCode: '',
        orderBy: 'sales_bill_detail.CREATE_DATE desc'
      },
      // 表头
      columns: [
        { 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', customRender: function (text) { return text || '--' }, 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: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '折后小计', dataIndex: 'discountedAmount', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '7%', align: 'center' }
      ],
      // 加载数据方法 必须为 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
    }
  },
  methods: {
    // 打印预览/快捷打印
    handlePrint (type, printerType) {
      const _this = this
      _this.spinning = true
      let url = salesDetailPrint
      const params = { sn: this.outBizSn || this.$route.params.sn }
      if (type == 'export') { //  导出
        url = salesDetailExport
      }
      // 打印或导出
      hdPrint(printerType, type, url, params, '销售单', function () {
        _this.spinning = false
      })
    },
    // 已选产品 销售数量  blur
    qtyBlur (val, record) {
      const _this = this
      this.dataSource = record || []
      if (val && val != record.qtyBackups) {
        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
          }
        })
      } else {
        record.qty = record.qtyBackups
      }
    },
    changeQty (record) {
      salesDetailUpdateQty({
        id: record.id,
        qty: record.qty
      }).then(res => {
        this.resetSearchForm(false)
        if (res.status == 200) {
          this.$message.info(res.message)
        }
        this.spinning = false
      })
    },
    // 已选产品 售价  blur
    priceBlur (val, record) {
      this.dataSource = record || []
      //  光标移出，值发生改变再调用编辑接口
      if (val && val != record.priceBackups) {
        this.spinning = true
        salesDetailUpdatePrice({
          salesBillSn: record.salesBillSn,
          productSn: record.productSn,
          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
    },
    // 更新产品列表
    updateData (priceType) {
      // 价格类型变更
      if (priceType != this.$route.params.priceType) {
        this.$router.push({ name: 'salesEdit', params: { id: this.orderId, sn: this.salesBillSn, priceType: priceType } })
      } else {
        this.getOrderDetail(true)
      }
    },
    //  重置
    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 () {
      if (this.detailData.discountAmount < 0) {
        return
      }
      this.spinning = true
      salesWriteDiscount({
        discountAmount: this.detailData.discountAmount,
        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
          })
        }
      })
    },
    // 删除产品
    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.$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)
        }
        this.isInster = false
        // this.spinning = false
      })
    },
    //  销售单详情
    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.salesBillSource && vm.detailData.salesBillSource == 'PURCHASE') ? '' : vm.detailData.buyerSn
            const priceType = vm.$route.params.priceType
            vm.$refs.partQuery.pageInit(buyerSn, priceType)
          }
        }
      })
    },
    // 提交销售单
    handleSubmit () {
      this.spinning = true
      salesWriteSubmit({ id: this.orderId }).then(res => {
        if (res.status == 200) {
          this.handleBack()
          this.$message.success(res.message)
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    pageInit () {
      const vm = this
      vm.$nextTick(() => {
        vm.orderId = vm.$route.params.id
        vm.salesBillSn = vm.$route.params.sn
        vm.getOrderDetail(true)
        vm.$refs.table.refresh(true)
      })
    }
  },
  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()
    }
  },
  deactivated () {
    // this.dataSource = []
    // this.showPage = false
  },
  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: scroll;
      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>
