<template>
  <div>
    <a-page-header :ghost="false" :backIcon="false" class="salesReturnEdit-back" >
      <!-- 自定义的二级文字标题 -->
      <template slot="subTitle">
        <a id="salesReturnEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
        <span style="margin: 0 15px;color: #666;">客户名称：{{ ordeDetail&&ordeDetail.buyerName }}</span>
      </template>
      <!-- 操作区，位于 title 行的行尾 -->
      <template slot="extra">
        <a-button key="2" id="salesReturnEdit-preview-btn">打印预览</a-button>
        <a-button key="1" type="primary" id="salesReturnEdit-print-btn">快速打印</a-button>
      </template>
    </a-page-header>

    <a-card size="small" :bordered="false" class="pages-wrap" v-if="ordeDetail&&ordeDetail.salesReturnBillSource=='SALES'">
      <!-- 查询配件列表 -->
      <queryPart :buyerSn="$route.params.buyerSn" grabFlag="1" :newLoading="isInster" @add="saveProduct"></queryPart>
    </a-card>
    <a-card size="small" :bordered="false" class="pages-wrap">
      <!-- alert -->
      <a-alert style="margin-bottom: 10px;" type="info">
        <div slot="message" class="total-bar">
          <div>
            <span>退货总金额：{{ ordeDetail&&ordeDetail.totalAmount }}元；</span>
            <span>退货总数量：{{ ordeDetail&&ordeDetail.totalQty }}；</span>
          </div>
          <div>
          </div>
        </div>
      </a-alert>
      <!-- 已选配件列表 -->
      <s-table
        class="sTable"
        ref="table"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ x: 1500, y: 300 }"
        bordered>
        <!-- 本次退货数量 -->
        <template slot="qty" slot-scope="text, record">
          <editable-cell
            size="small"
            :text="record.qty"
            :max="999999"
            :min="0"
            :precision="0"
            @change="onCellChange(record.id, 'qty', $event)" />
        </template>
        <!-- 退货原因 -->
        <template slot="remark" slot-scope="text, record">
          <a-input placeholder="30个字符内" maxlength="30" v-model="record.remark" @blur="updateRemark(record)"></a-input>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="primary"
            :loading="delLoading"
            class="button-error"
            @click="handleDel(record)"
            id="salesReturn-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="salesReturn-handleSubmit">提交</a-button>
      </div>
    </a-affix>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import queryPart from './queryPart.vue'
import EditableCell from '@/views/common/editInput.js'
import { salesReturnDetail, salesReturnSubmit } from '@/api/salesReturn'
import {
  salesReturnDetailList,
  salesReturnDetailDel,
  salesReturnDetailInsert,
  salesReturnDetailUpdateQty,
  salesReturnDetailUpdateReason
} from '@/api/salesReturnDetail'
export default {
  name: 'SalesReturnGrabEdit',
  components: {
    STable,
    VSelect,
    queryPart,
    EditableCell
  },
  data () {
    return {
      orderId: null,
      orderSn: null,
      buyerSn: null,
      disabled: false,
      isInster: false, // 是否正在添加产品
      ordeDetail: { discountAmount: 0 },
      delLoading: false,
      // 已选产品
      dataSource: [],
      productForm: {
        salesReturnBillSn: ''
      },
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', align: 'center', width: 80 },
        { title: '采购单号', dataIndex: 'purchaseBillNo', align: 'center', width: 200 },
        { title: '产品编码', dataIndex: 'productEntity.code', align: 'center' },
        { title: '产品名称', dataIndex: 'productEntity.name', align: 'center' },
        { title: '剩余可退数量', dataIndex: 'refundableQty', align: 'center', width: 120, customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '本次退货数量', dataIndex: 'qty', align: 'center', width: 150, scopedSlots: { customRender: 'qty' } },
        { title: '退货单价', dataIndex: 'price', align: 'center', width: 150, customRender: function (text) { return '￥' + (text || 0) } },
        { title: '单位', dataIndex: 'productEntity.unit', align: 'center', width: 100 },
        { title: '退货小计', align: 'center', width: 100, dataIndex: 'totalAmount', customRender: function (text) { return '￥' + (text || 0) } },
        { title: '退货原因', dataIndex: 'remark', align: 'center', width: 150, scopedSlots: { customRender: 'remark' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 100, align: 'center', fixed: 'right' }
      ],
      chooseLoadData: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        // 查询总计
        this.productForm.salesReturnBillSn = this.$route.params.sn
        return salesReturnDetailList(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.chooseLoadData = data.list
          return data
        })
      }
    }
  },
  methods: {
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesReturnList' })
    },
    // 修改退货数量
    onCellChange (id, key, value) {
      const chooseLoadData = [...this.chooseLoadData]
      const row = chooseLoadData.find(item => item.id === id)
      if (row) {
        row[key] = Number(value)
        if (row.qty > row.refundableQty) {
          this.$message.info('本次退货数量不可大于剩余可退数量')
          this.$refs.table.refresh(true)
        } else {
          salesReturnDetailUpdateQty({
            salesReturnDetailSn: row.salesReturnDetailSn,
            qty: row.qty
          }).then(res => {
            if (res.status == 200) {
              this.resetSearchForm(true)
              this.$message.success(res.message)
            }
          })
        }
      }
    },
    // 修改退货原因
    updateRemark (row) {
      salesReturnDetailUpdateReason({
        salesReturnDetailSn: row.salesReturnDetailSn,
        remark: row.remark
      }).then(res => {
        if (res.status == 200) {
          this.resetSearchForm(true)
          this.$message.success(res.message)
        }
      })
    },
    // 重置列表
    resetForm () {
      this.$refs.table.refresh(true)
    },
    // 获取单据详细
    getOrderDetail () {
      salesReturnDetail({ sn: this.orderSn }).then(res => {
        this.ordeDetail = res.data || null
      })
    },
    // 删除产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.delLoading = true
          salesReturnDetailDel({ salesReturnDetailSn: row.salesReturnDetailSn }).then(res => {
            if (res.status == 200) {
              _this.resetSearchForm(true)
            }
            _this.$message.info(res.message)
            _this.delLoading = false
          })
        }
      })
    },
    //  重置
    resetSearchForm (flag) {
      this.$refs.table.refresh(!!flag)
      this.getOrderDetail()
    },
    // 添加或修改产品
    saveProduct (row) {
      console.log(row)
      // 防止多次添加产品
      if (this.isInster) {
        return
      }
      this.isInster = true
      const params = {
        'salesReturnBillSn': this.orderSn,
        'salesReturnBillNo': this.ordeDetail.salesReturnBillNo,
        'salesBillSn': row.salesBillSn,
        'salesBillNo': row.salesBillNo,
        'refundableQty': row.refundableQty,
        'salesBillDetailSn': row.salesBillDetailSn,
        'price': row.price,
        'cost': row.showCost,
        'productSn': row.productSn,
        'qty': row.qty
      }
      salesReturnDetailInsert(params).then(res => {
        if (res.status == 200) {
          this.resetSearchForm(true)
          this.$message.success(res.message)
        }
        this.isInster = false
      })
    },
    // 提交销售单
    handleSubmit () {
      salesReturnSubmit({ salesReturnBillSn: this.orderSn }).then(res => {
        if (res.status == 200) {
          this.handleBack()
          this.$message.success(res.message)
        }
      })
    }
  },
  mounted () {
    this.orderSn = this.$route.params.sn
    this.buyerSn = this.$route.params.buyerSn
    this.getOrderDetail()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      console.log('beforeRouteEnter')
    })
  }
}
</script>

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