<template>
  <div 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>
          <span style="margin: 0 15px;color: #666;">客户名称：{{ detailData&&detailData.buyerName }}</span>
          <!-- <a-button id="salesEdit-edit-btn" size="small" @click="handleEdit" style="margin-left:10px" key="0">编辑</a-button> -->
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <!-- <template slot="extra">
          <a-button key="2" id="salesEdit-preview-btn">打印预览</a-button>
          <a-button key="1" type="primary" id="salesEdit-print-btn">快速打印</a-button>
        </template> -->
      </a-page-header>
      <a-card size="small" :bordered="false" class="salesEdit-cont">
        <div slot="title">
          <div class="p-title">
            选择产品
          </div>
        </div>
        <!-- 查询配件列表 -->
        <queryPart ref="partQuery" :buyerSn="detailData&&detailData.buyerSn" :newLoading="isInster" @add="insterProduct"></queryPart>
      </a-card>
      <a-card size="small" :bordered="false" class="salesEdit-cont">
        <div slot="title">
          <a-row :gutter="15" type="flex">
            <a-col :span="2">
              <div class="p-title">
                已选产品
              </div>
            </a-col>
            <a-col :span="16" v-if="activeName">
              <div class="p-notes">
                <a-icon style="color: #FF9900;" type="bell" /> 已选产品可参加<span>{{ activeName }}</span>的促销活动，促销产品为指定产品
              </div>
            </a-col>
            <!-- <a-col :span="6">
              <div style="float:right;overflow: hidden;">
                <a-button size="small" id="salesEdit-dru">导入明细</a-button>
                <a-button
                  size="small"
                  type="primary"
                  @click="delSalerDetailAll"
                  :loading="delLoading"
                  style="margin-left: 10px"
                  id="salesEdit-del-all">整单删除</a-button>
              </div>
            </a-col> -->
          </a-row>
        </div>
        <!-- 总计 -->
        <a-alert type="info" style="margin-bottom: 10px;">
          <div slot="message" class="total-bar">
            <div>
              总售价：<strong>￥{{ detailData&&(detailData.totalCommonAmount || detailData.totalCommonAmount==0) ? detailData.totalCommonAmount : '--' }}</strong>；
              总款数：<strong>{{ detailData&&(detailData.totalCommonCategory || detailData.totalCommonCategory==0) ? detailData.totalCommonCategory : '--' }}</strong>；
              总数量：<strong>{{ detailData&&(detailData.totalCommonQty || detailData.totalCommonQty==0) ? detailData.totalCommonQty : '--' }}</strong>；
            </div>
            <div>
            </div>
          </div>
        </a-alert>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ x:840, y: 300 }"
          bordered>
          <!-- 产品名称 -->
          <template slot="productName" slot-scope="text, record">
            <span>{{ text }}</span>
            <a-badge :number-style="{ backgroundColor: '#52c41a' }" count="活动" v-if="record.promotableFlag == 1"></a-badge>
          </template>
          <!-- 销售数量 -->
          <template slot="salesNums" slot-scope="text, record">
            <a-input-number
              id="salesEdit-qty"
              size="small"
              v-model="record.qty"
              :precision="0"
              :min="1"
              :max="999999"
              placeholder="请输入"
              @blur="e => onCellBlur(e.target.value, record)"
              style="width: 100%;" />
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="primary"
              :loading="delLoading"
              class="button-error"
              @click="handleDel(record)"
            >删除</a-button>
            <a-button
              size="small"
              type="primary"
              :loading="delLoading"
              class="button-warning"
              @click="handleSelCx(record)"
              v-if="record.promotableFlag == 1"
            >选择促销品</a-button>
          </template>
        </s-table>
      </a-card>
      <a-card size="small" :bordered="false" class="salesEdit-cont">
        <div slot="title">
          <div class="p-title">
            已选促销品
          </div>
        </div>
        <!-- 总计 -->
        <a-alert type="info" style="margin-bottom: 10px;">
          <div slot="message" class="total-bar">
            <div>
              总成本：<strong>{{ detailData&&(detailData.totalPromoCost || detailData.totalPromoCost==0) ? '￥'+detailData.totalPromoCost : '--' }}</strong>；
              总款数：<strong>{{ detailData&&(detailData.totalPromoCategory || detailData.totalPromoCategory==0) ? detailData.totalPromoCategory : '--' }}</strong>；
              总数量：<strong>{{ detailData&&(detailData.totalPromoQty || detailData.totalPromoQty==0) ? detailData.totalPromoQty : '--' }}</strong>；
            </div>
            <div>
            </div>
          </div>
        </a-alert>
        <!-- 已选促销品列表 -->
        <queryPromotable ref="promotable" :salesBillSn="$route.params.sn" :delLoading="delLoading" @onCellBlur="onCellBlur" @del="handleDel"></queryPromotable>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        size="large"
        style="padding: 0 60px;"
        :disabled="spinning"
        type="primary"
        class="button-primary"
        @click="handleSubmit()"
        id="productInfoList-handleSubmit">提交</a-button>
    </div>
    <!-- 选择客户弹框 -->
    <choose-custom-modal ref="custModal" :show="openModal" @cancel="openModal=false" />
    <!-- 添加产品 -->
    <ChooseActive
      ref="activeProduct"
      :buyerSn="detailData&&detailData.buyerSn"
      :openModal="newActive"
      @ok="addNewActive"
      :newLoading="isInster"
      @close="newActive=false"></ChooseActive>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import queryPart from './queryPart.vue'
import queryPromotable from './queryPromotable.vue'
import chooseCustomModal from './chooseCustomModal.vue'
import ChooseActive from './chooseActive.vue'
import { salesDetailBySn, salesWriteSubmit, getPromoacActiveList } from '@/api/sales'
import { salesDetailList, salesDetailInsert, salesDetailUpdateQty, salesDetailDel, salesDetailDelAll, addPromoGoods } from '@/api/salesDetail'
export default {
  name: 'SalesDetail',
  components: { STable, VSelect, queryPart, queryPromotable, chooseCustomModal, ChooseActive },
  data () {
    return {
      spinning: false,
      salesBillSn: null, // 销售单sn
      disabled: false, //  查询、重置按钮是否可操作
      isInster: false, // 是否正在添加产品
      openModal: false, // 客户弹框
      delLoading: false,
      newActive: false, // 选择促销品
      detailData: { discountAmount: 0, id: null, salesBillSn: '' }, // 订单基础数据
      dataSource: [],
      productForm: {
        salesBillSn: '',
        promotionFlag: 0
      },
      activeName: '', // 促销活动
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 70, align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', width: 120, align: 'center', customRender: function (text) { return text || '--' }, sorter: true },
        { title: '产品名称', dataIndex: 'productEntity.name', scopedSlots: { customRender: 'productName' }, align: 'center' },
        { title: '售价', dataIndex: 'price', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '销售数量', scopedSlots: { customRender: 'salesNums' }, width: 100, align: 'center' },
        { title: '单位', dataIndex: 'productEntity.unit', width: 60, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '售价小计', dataIndex: 'totalAmount', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 170, align: 'center', fixed: 'right' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.productForm.salesBillSn = this.$route.params.sn
        return salesDetailList(Object.assign(parameter, this.productForm)).then(res => {
          const 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
          }
          this.disabled = false
          this.dataSource = data.list
          return data
        })
      }
    }
  },
  methods: {
    // 已选产品  blur
    onCellBlur (val, record) {
      const _this = this
      //  光标移出，值发生改变再调用编辑接口
      if (val && val != record.qtyBackups) {
        _this.spinning = true
        salesDetailUpdateQty({
          salesBillDetailSn: record.salesBillDetailSn,
          qty: record.qty,
          salesBillSn: _this.salesBillSn
        }).then(res => {
          _this.resetSearchForm(true)
          _this.$refs.promotable.resetCurForm()
          if (res.status == 200) {
            _this.$message.success(res.message)
          }
          _this.spinning = false
        })
      } else {
        record.qty = record.qtyBackups
      }
    },
    // 编辑客户信息
    handleEdit () {
      this.openModal = true
      setTimeout(() => {
        this.$refs.custModal.editCust(this.detailData)
      }, 500)
    },
    //  重置
    resetSearchForm (flag) {
      this.$refs.table.refresh(!!flag)
      this.getPromoacActiveList()
      this.getOrderDetail()
    },
    // 重置列表
    resetForm () {
      this.$refs.table.refresh()
    },
    //  返回
    handleBack () {
      this.$router.push({ path: '/salesManagement/salesQuery/list', query: { closeLastOldTab: true } })
    },
    // 整单删除
    delSalerDetailAll () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要整单删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.delLoading = true
          _this.spinning = true
          salesDetailDelAll({ salesBillSn: _this.salesBillSn }).then(res => {
            if (res.status == 200) {
              _this.resetSearchForm()
              _this.$refs.promotable.resetCurForm()
              _this.$message.success(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({ salesBillDetailSn: row.salesBillDetailSn, salesBillSn: _this.salesBillSn }).then(res => {
            if (res.status == 200) {
              _this.resetSearchForm(true)
              _this.$refs.promotable.resetCurForm()
              _this.$message.success(res.message)
            }
            _this.delLoading = false
            _this.spinning = false
          })
        }
      })
    },
    // 添加产品
    insterProduct (row, promotionFlag) {
      console.log(row)
      // 防止多次添加产品
      if (this.isInster) { return }
      const _this = this
      _this.saveNewProduct(row, promotionFlag)
    },
    // 保存添加的产品到销售列表
    saveNewProduct (row, promotionFlag) {
      this.$message.loading('正在添加产品...', 1)
      this.isInster = true
      this.spinning = true
      salesDetailInsert({
        packQty: row.productPackQty,
        productSn: row.productSn,
        showCost: row.lastStockCost,
        price: row.productPrice,
        origPrice: row.productPrice,
        promotionGiftsAmount: 0,
        usePromotionGiftsAmount: 0,
        qty: row.salesNums,
        salesBillSn: this.detailData.salesBillSn,
        salesBillNo: this.detailData.salesBillNo,
        purchaseBillSn: this.detailData.purchaseBillSn,
        purchaseBillNo: this.detailData.purchaseBillNo,
        stockSn: row.stockSn,
        promotableFlag: row.isJoinActivityProduct || 0, // 可促销标记 有活动的传1，没活动的传0
        promotionFlag: promotionFlag // 促销标记 正品传0，促销品传1
      }).then(res => {
        if (res.status == 200) {
          this.resetSearchForm()
          this.$message.success('产品添加成功', 2.5)
          this.spinning = false
        } else {
          this.spinning = false
        }
        this.isInster = false
      })
    },
    //  销售单详情
    getOrderDetail () {
      salesDetailBySn({ salesBillSn: this.$route.params.sn }).then(res => {
        console.log('getOrderDetail')
        if (res.status == 200) {
          this.detailData = res.data
          console.log(this.detailData)
        }
      })
    },
    // 提交销售单
    handleSubmit () {
      this.spinning = true
      salesWriteSubmit({ salesBillSn: this.salesBillSn }).then(res => {
        if (res.status == 200) {
          this.handleBack()
          this.$message.success(res.message)
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    // 获取促销活动
    getPromoacActiveList () {
      const _this = this
      getPromoacActiveList({ salesBillSn: this.salesBillSn }).then(res => {
        if (res.status == 200) {
          _this.activeName = ''
          res.data.map(item => {
            _this.activeName += item.name + '、'
          })
          _this.activeName = _this.activeName.slice(0, _this.activeName.length - 1)
        }
      })
    },
    // 选择促销品
    handleSelCx (row) {
      this.newActive = true
      this.$refs.activeProduct.getData(row)
    },
    // 批量添加促销品
    addNewActive (list) {
      const temp = []
      list.map(item => {
        temp.push(Object.assign(item, {
          salesBillSn: this.detailData.salesBillSn,
          salesBillNo: this.detailData.salesBillNo,
          purchaseBillSn: this.detailData.purchaseBillSn,
          purchaseBillNo: this.detailData.purchaseBillNo
        }))
      })
      this.isInster == true
      this.spinning = true
      addPromoGoods(temp).then(res => {
        if (res.status == 200) {
          this.$refs.promotable.getData()
          this.getOrderDetail()
          this.newActive = false
          this.isInster == false
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    }
  },
  mounted () {
    this.getOrderDetail()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.salesBillSn = vm.$route.params.sn
      // 获取促销活动
      vm.getPromoacActiveList()
      // 查询已选促销品
      vm.$refs.promotable.getData()
    })
  }
}
</script>

<style lang="less">
  .salesEdit-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
    .salesEdit-cont{
      margin-top: 10px;
    }
    .p-title{
      font-weight: bold;
      font-size: 16px;
    }
    .p-notes{
      font-size: 14px;
      span{
        color: #FF9900;
      }
    }
    .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>
