<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>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra" v-if="$hasPermissions('B_salesPrint')">
          <a-radio-group key="3" v-model="printerType">
            <a-radio value="NEEDLE">针式</a-radio>
            <a-radio value="INK">喷墨</a-radio>
          </a-radio-group>
          <a-button key="2" id="salesEdit-preview-btn" :disabled="dataSource.length==0" @click="handlePrint('preview')">打印预览</a-button>
          <a-button key="1" type="primary" id="salesEdit-print-btn" :disabled="dataSource.length==0" @click="handlePrint('print')">快捷打印</a-button>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="salesEdit-cont">
        <!-- 查询配件列表 -->
        <queryPart ref="partQuery" :buyerSn="detailData&&detailData.buyerSn" :priceType="$route.params.priceType" :newLoading="isInster" @add="insterProduct"></queryPart>
      </a-card>
      <a-card size="small" :bordered="false" class="salesEdit-cont">
        <!-- 总计 -->
        <a-alert style="margin-bottom: 15px;" type="info">
          <div slot="message" class="total-bar">
            <div>
              总售价：<strong>￥{{ detailData&&detailData.totalAmount || 0 }}</strong>；
              总款数：<strong>{{ detailData&&detailData.totalCategory || 0 }}</strong>；
              总数量：<strong>{{ detailData&&detailData.totalQty || 0 }}</strong>；
              赠品总数量：<strong>{{ detailData&&detailData.giftQty || 0 }}</strong>；
            </div>
            <div>
              <div>
                折扣金额：
                <a-input-number id="discount" v-model="detailData.discountAmount" :min="0" :precision="2" :max="999999"/>
                <a-button type="primary" @click="salesDiscount" class="button-info">打折</a-button>
              </div>
              <div>
                折扣：<strong>{{ detailData&&detailData.discountRate || 0 }}%</strong>；
                折后总售价：<strong>￥{{ detailData&&detailData.discountedAmount || 0 }}</strong>；
              </div>
            </div>
          </div>
        </a-alert>
        <!-- 查询条件 -->
        <a-row :gutter="15">
          <a-col :span="18">
            <a-form-model layout="inline" :model="productForm">
              <a-form-model-item label="产品编码">
                <a-input v-model="productForm.productCode" allowClear placeholder="输入产品编码" />
              </a-form-model-item>
              <a-form-model-item label="产品名称">
                <a-input v-model="productForm.productName" allowClear placeholder="输入产品名称" />
              </a-form-model-item>
              <a-form-model-item>
                <a-button style="margin-bottom: 18px;" type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="salesEdit-refresh">查询</a-button>
                <a-button style="margin: 0 0 18px 8px" @click="resetForm" id="salesEdit-reset">重置</a-button>
              </a-form-model-item>
            </a-form-model>
          </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>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ x: 1940, y: 300 }"
          :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">
            <editable-cell
              size="small"
              :text="text"
              id="salesEdit-price"
              :max="999999"
              :min="0"
              :precision="2"
              punit="￥"
              @change="onCellChange(record.id, 'price', $event)" />
          </template>
          <!-- 销售数量 -->
          <template slot="salesNums" slot-scope="text, record">
            <editable-cell
              size="small"
              :text="record.qty"
              id="salesEdit-salesNums"
              :max="999999"
              :min="1"
              :precision="0"
              @change="onCellChange(record.id, 'qty', $event)" />
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="primary"
              :loading="delLoading"
              class="button-error"
              @click="handleDel(record)"
              id="productInfoList-Del">删除</a-button>
          </template>
        </s-table>
      </a-card>
      <a-affix :offset-bottom="0">
        <div
          style="text-align: center;width: 100%;background-color: #fff;padding: 12px 0;box-shadow: 0 0 20px #dcdee2;">
          <a-button
            size="large"
            style="width: 150px;"
            type="primary"
            class="button-primary"
            @click="handleSubmit()"
            id="productInfoList-handleSubmit">提交</a-button>
        </div>
      </a-affix>
    </a-spin>
    <!-- 选择客户弹框 -->
    <choose-custom-modal ref="custModal" :show="openModal" @updateData="updateData" @cancel="openModal=false" />
    <!-- 打印 -->
    <div id="print"></div>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import queryPart from './queryPart.vue'
import chooseCustomModal from './chooseCustomModal.vue'
import { salesDetail, salesWriteSubmit, salesWriteDiscount, salesDetailPrint } from '@/api/sales'
import EditableCell from '@/views/common/editInput.js'
import { salesDetailList, salesDetailInsert, salesDetailUpdatePrice, salesDetailUpdateQty, salesDetailDel, salesDetailDelAll } from '@/api/salesDetail'
export default {
  name: 'SalesDetail',
  components: { STable, VSelect, queryPart, chooseCustomModal, EditableCell },
  data () {
    return {
      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: ''
      },
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '产品编码', dataIndex: 'dealerProductEntity.code', scopedSlots: { customRender: 'productCode' }, width: 220, align: 'center', sorter: true },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'dealerProductEntity.origCode', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'dealerProductEntity.productBrandName', width: 200, align: 'center', sorter: true, customRender: function (text) { return text || '--' } },
        { title: '仓库', dataIndex: 'warehouseEntity.name', width: 150, align: 'center', sorter: true, customRender: function (text) { return text || '--' } },
        { title: '仓位', dataIndex: 'warehouseLocationEntity.name', width: 150, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '售价', dataIndex: 'price', scopedSlots: { customRender: 'price' }, width: 150, align: 'center' },
        { title: '销售数量', scopedSlots: { customRender: 'salesNums' }, width: 150, align: 'center' },
        { title: '单位', dataIndex: 'dealerProductEntity.unit', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '售价小计', dataIndex: 'totalAmount', width: 100, align: 'center', customRender: function (text) { return '￥' + (text || 0) } },
        { title: '折后小计', dataIndex: 'discountedAmount', width: 100, align: 'center', customRender: function (text) { return '￥' + (text || 0) } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 100, 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
          }
          this.disabled = false
          this.dataSource = data.list
          return data
        })
      },
      printerType: 'NEEDLE' //  打印机类型
    }
  },
  methods: {
    onCellChange (id, key, value) {
      const dataSource = [...this.dataSource]
      const row = dataSource.find(item => item.id === id)
      if (row) {
        row[key] = Number(value)
        this.dataSource = dataSource
      }
      // 修改价格
      if (key == 'price') {
        this.spinning = true
        salesDetailUpdatePrice({
          salesBillSn: row.salesBillSn,
          productSn: row.productSn,
          price: row.price
        }).then(res => {
          this.resetSearchForm(true)
          this.$message.info(res.message)
          this.spinning = false
        })
      }
      if (key == 'qty') {
        this.spinning = true
        salesDetailUpdateQty({
          id: row.id,
          qty: row.qty
        }).then(res => {
          this.resetSearchForm(true)
          if (res.status == 200) {
            this.$refs.partQuery.resetCurForm()
          }
          this.$message.info(res.message)
          this.spinning = false
        })
      }
    },
    // 打印预览/快捷打印
    handlePrint (type) {
      const _this = this
      _this.spinning = true
      salesDetailPrint({ sn: this.$route.params.sn, type: this.printerType }).then(res => {
        _this.spinning = false
        if (res.type == 'application/json') {
          var reader = new FileReader()
          reader.addEventListener('loadend', function () {
            const obj = JSON.parse(reader.result)
            _this.$notification.error({
              message: '提示',
              description: obj.message
            })
          })
          reader.readAsText(res)
        } else {
          this.print(res, type)
        }
      })
    },
    print (data, type) {
      if (!data) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([data], { type: 'application/pdf' }))
      document.getElementById('print').innerHTML = '<iframe id="printf" name="printf" src="' + url + '" hidden></iframe>'
      if (type == 'preview') { //  预览
        window.open(url)
      } else if (type == 'print') { //  打印
        window.frames['printf'].focus()
        window.frames['printf'].print()
      }
    },
    // 编辑客户信息
    handleEdit () {
      this.openModal = true
      setTimeout(() => {
        this.$refs.custModal.editCust(this.detailData)
      }, 500)
    },
    // 更新产品列表
    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()
      }
    },
    //  重置
    resetSearchForm (flag) {
      this.$refs.table.refresh(!!flag)
      this.getOrderDetail()
    },
    // 重置列表
    resetForm () {
      this.productForm = {
        productName: '',
        productCode: ''
      }
      this.$refs.table.refresh()
    },
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesQueryList' })
    },
    // 打折
    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()
          this.spinning = false
        } else {
          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()
            }
            _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(true)
            }
            _this.$message.info(res.message)
            _this.delLoading = false
            _this.spinning = false
          })
        }
      })
    },
    // 添加产品
    insterProduct (row) {
      console.log(row)
      // 防止多次添加产品
      if (this.isInster) { return }
      const _this = this
      // 判断是否已添加此产品
      const hasRow = this.dataSource.find(item => item.productSn == row.productSn && item.warehouseSn == row.warehouseSn && item.warehouseLocationSn == row.warehouseLocationSn)
      if (hasRow) {
        this.$message.info('该产品已在当前销售单中存在！')
        return
      }

      // 库存不足时
      if (row.currentQty < row.salesNums) {
        this.$confirm({
          title: '提示',
          content: '库存不足，确认添加为急件吗？',
          centered: true,
          closable: true,
          onOk () {
            _this.saveNewProduct(row)
          }
        })
      } else if (row.putCost > row.salePrice) {
        // 销售价低于成本价
        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.salePrice,
        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()
          this.$refs.partQuery.resetCurForm()
          this.$message.success('产品添加成功', 2.5)
        }
        this.isInster = false
        this.spinning = false
      })
    },
    //  销售单详情
    getOrderDetail () {
      salesDetail({ id: this.$route.params.id }).then(res => {
        console.log('getOrderDetail')
        if (res.status == 200) {
          this.detailData = res.data
          console.log(this.detailData)
        }
      })
    },
    // 提交销售单
    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
        }
      })
    }
  },
  mounted () {
    this.getOrderDetail()
    this.orderId = this.$route.params.id
    this.salesBillSn = this.$route.params.sn
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      console.log('beforeRouteEnter')
    })
  }
}
</script>

<style lang="less">
  .salesEdit-wrap{
    .salesEdit-cont{
      margin-top: 15px;
    }
    .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>
