<template>
  <div class="salesEdit-wrap">
    <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">
      <!-- 查询配件列表 -->
      <queryPart :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: 1560, y: 300 }"
        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
            :text="record.price"
            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
            :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>
    <!-- 选择客户弹框 -->
    <choose-custom-modal ref="custModal" :show="openModal" @updateData="getOrderDetail" @cancel="openModal=false" />
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import queryPart from './queryPart.vue'
import chooseCustomModal from './chooseCustomModal.vue'
import { salesDetail, salesWriteSubmit, salesWriteDiscount } 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 {
      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: 140, align: 'center', sorter: true },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', align: 'center' },
        { title: '原厂编码', dataIndex: 'dealerProductEntity.origCode', width: 140, align: 'center' },
        { title: '品牌', dataIndex: 'dealerProductEntity.productBrandName', width: 100, align: 'center', sorter: true },
        { title: '仓库', dataIndex: 'warehouseEntity.name', width: 100, align: 'center', sorter: true },
        { title: '仓位', dataIndex: 'warehouseLocationEntity.name', width: 100, align: 'center' },
        { title: '售价', 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: 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
          }
          this.disabled = false
          this.dataSource = data.list
          return data
        })
      }
    }
  },
  methods: {
    onCellChange (id, key, value) {
      console.log(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') {
        salesDetailUpdatePrice({
          salesBillSn: row.salesBillSn,
          productSn: row.productSn,
          price: row.price
        }).then(res => {
          if (res.status == 200) {
            this.resetSearchForm(true)
          }
          this.$message.info(res.message)
        })
      }
      if (key == 'qty') {
        salesDetailUpdateQty({
          id: row.id,
          qty: row.qty
        }).then(res => {
          if (res.status == 200) {
            this.resetSearchForm(true)
          }
          this.$message.info(res.message)
        })
      }
    },
    // 编辑客户信息
    handleEdit () {
      this.openModal = true
      setTimeout(() => {
        this.$refs.custModal.editCust(this.detailData)
      }, 500)
    },
    //  重置
    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
      }
      console.log(this.detailData)
      salesWriteDiscount({
        discountAmount: this.detailData.discountAmount,
        salesBillSn: this.detailData.salesBillSn,
        id: this.detailData.id
      }).then(res => {
        if (res.status == 200) {
          this.resetSearchForm()
        }
      })
    },
    // 整单删除
    delSalerDetailAll () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要整单删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.delLoading = true
          salesDetailDelAll({ salesBillSn: _this.detailData.salesBillSn }).then(res => {
            if (res.status == 200) {
              _this.resetSearchForm()
            }
            _this.$message.info(res.message)
            _this.delLoading = false
          })
        }
      })
    },
    // 删除产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.delLoading = true
          salesDetailDel({ id: row.id }).then(res => {
            if (res.status == 200) {
              _this.resetSearchForm(true)
            }
            _this.$message.info(res.message)
            _this.delLoading = false
          })
        }
      })
    },
    // 添加产品
    insterProduct (row) {
      console.log(row)
      // 防止多次添加产品
      if (this.isInster) {
        return
      }
      const _this = this
      // 库存不足时
      if (row.currentQty < row.salesNums) {
        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
      salesDetailInsert({
        buyerSn: this.detailData.buyerSn,
        productSn: row.productSn,
        price: row.dealerProduct.cityPrice,
        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.$message.success('产品添加成功', 2.5)
        }
        this.isInster = false
      })
    },
    //  销售单详情
    getOrderDetail () {
      salesDetail({ id: this.$route.params.id }).then(res => {
        if (res.status == 200) {
          this.detailData = res.data
        }
      })
    },
    // 提交销售单
    handleSubmit () {
      salesWriteSubmit({ id: this.orderId }).then(res => {
        if (res.status == 200) {
          this.handleBack()
          this.$message.success(res.message)
        }
      })
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      // 获取销售单详情
      vm.getOrderDetail()
      vm.orderId = vm.$route.params.id
      vm.salesBillSn = vm.$route.params.sn
    })
  }
}
</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;
          }
        }
      }
    }
  }

</style>
