<template>
  <div class="salesReturnEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <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="3"
            type="default"
            class="button-info"
            id="salesReturnEdit-preview-btn"
            v-if="$hasPermissions('B_salesReturnPrint')"
            :disabled="chooseLoadData.length==0"
            @click="handlePrint('preview')">打印预览</a-button>
          <a-button
            key="2"
            type="primary"
            class="button-info"
            id="salesReturnEdit-print-btn"
            v-if="$hasPermissions('B_salesReturnPrint')"
            :disabled="chooseLoadData.length==0"
            @click="handlePrint('print')">快捷打印</a-button>
          <a-divider type="vertical" />
          <a-button
            key="1"
            type="primary"
            class="button-warning"
            id="salesReturnEdit-export-btn"
            v-if="$hasPermissions('B_salesReturnExport')"
            :disabled="chooseLoadData.length==0"
            @click="handlePrint('export')">导出Excel</a-button>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="salesReturnEdit-cont">
        <!-- 查询配件列表 -->
        <queryPart ref="partQuery" :returnReasonList="returnReasonList" :newLoading="isInster" @add="saveProduct"></queryPart>
      </a-card>
      <a-card size="small" :bordered="false" class="salesReturnEdit-cont">
        <a-alert style="margin-bottom: 10px;" type="info">
          <div slot="message" class="total-bar">
            <div>
              <span>申请退货数量：{{ ordeDetail&&(ordeDetail.totalQty || ordeDetail.totalQty==0) ? ordeDetail.totalQty : '--' }}；</span>
              <span v-if="$hasPermissions('B_isShowPrice')">参考退货金额：{{ ordeDetail&&(ordeDetail.totalAmount || ordeDetail.totalAmount==0) ? ordeDetail.totalAmount : '--' }}元；</span>
            </div>
          </div>
        </a-alert>
        <div class="table-page-search-wrapper" style="display:flex;align-items: center;justify-content: space-between;">
          <div style="width:80%;">
            <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
              <a-row :gutter="15">
                <a-col :md="6" :sm="24">
                  <a-form-item label="产品编码">
                    <a-input v-model.trim="productForm.productCode" allowClear placeholder="请输入产品编码"/>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="产品名称">
                    <a-input v-model.trim="productForm.productName" allowClear placeholder="请输入产品名称"/>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                  <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled">查询</a-button>
                  <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled">重置</a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <div>
            <a-button type="primary" class="button-info" id="salesReturnEdit-import-btn" @click="openGuideModal=true">导入产品</a-button>
          </div>
        </div>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          :scroll="{ y: 300 }"
          bordered>
          <!-- 本次退货数量 -->
          <template slot="qty" slot-scope="text, record">
            <a-input-number
              id="salesReturn-qty"
              size="small"
              v-model="record.qty"
              :precision="0"
              :min="0"
              :max="999999"
              placeholder="请输入"
              @blur="e => onCellBlur(e.target.value, record, 'qty')"
              style="width: 100%;" />
          </template>
          <!-- 退货原因 -->
          <template slot="returnReason" slot-scope="text, record">
            <a-select
              style="width:100%;"
              v-model="record.returnReason"
              @change="updateReason(record)"
              placeholder="请选择退货原因"
            >
              <a-select-option v-for="item in returnReasonList" :value="item.code">
                {{ item.dispName }}
              </a-select-option>
            </a-select>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              :loading="delLoading"
              class="button-error"
              @click="handleDel(record)"
              id="salesReturn-Del">删除</a-button>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        size="large"
        style="padding: 0 60px;"
        :disabled="spinning"
        type="primary"
        class="button-primary"
        @click="beforeSubmit()"
        id="salesReturn-handleSubmit">提交</a-button>
    </div>
    <!-- 选择审核人员 -->
    <chooseDepartUserModal :openModal="openDepartUserModal" @close="openDepartUserModal=false" @submit="handleSubmit"></chooseDepartUserModal>
    <!-- 导入产品 -->
    <importGuideModal :openModal="openGuideModal" :params="{salesReturnBillSn: $route.params.sn, grabFlag: ordeDetail.grabFlag}" @close="closeGuideModel" @ok="hanldeOk" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import { printFun, exportExcel } from '@/libs/JGPrint.js'
import ImportGuideModal from './importGuideModal.vue'
import queryPart from './queryPart.vue'
import EditableCell from '@/views/common/editInput.js'
import chooseDepartUserModal from './chooseDepartUserModal.vue'
import { salesReturnDetail, salesReturnSubmit, salesReturnBatchInsert, salesReturnPrint, salesReturnExport } from '@/api/salesReturn'
import {
  salesReturnDetailList,
  salesReturnDetailDel,
  salesReturnDetailInsert,
  salesReturnDetailUpdateQty,
  salesReturnDetailUpdateReason
} from '@/api/salesReturnDetail'
export default {
  name: 'SalesReturnEdit',
  mixins: [commonMixin],
  components: {
    STable,
    VSelect,
    queryPart,
    EditableCell,
    ImportGuideModal,
    chooseDepartUserModal
  },
  data () {
    return {
      spinning: false,
      orderId: null,
      orderSn: null,
      buyerSn: null,
      disabled: false,
      isInster: false, // 是否正在添加产品
      openDepartUserModal: false,
      ordeDetail: { discountAmount: 0 },
      delLoading: false,
      // 已选产品
      dataSource: [],
      productForm: {
        salesReturnBillSn: '',
        productName: '',
        productCode: ''
      },
      chooseLoadData: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        // 查询总计
        this.productForm.salesReturnBillSn = this.$route.params.sn
        return salesReturnDetailList(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.chooseLoadData = data.list
            this.total = res.data.count
          }
          return data
        })
      },
      openGuideModal: false, //  导入产品引导
      total: 0,
      returnReasonList: [] // 申请退货列表
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', align: 'center', width: '4%' },
        { title: '产品编码', dataIndex: 'productEntity.code', width: '18%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '25%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '单位', dataIndex: 'productEntity.unit', align: 'center', width: '6%', customRender: function (text) { return text || '--' } },
        { title: '申请退货数量', dataIndex: 'qty', align: 'center', width: '8%', scopedSlots: { customRender: 'qty' } },
        { title: '退货原因', dataIndex: 'returnReason', align: 'center', width: '13%', scopedSlots: { customRender: 'returnReason' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      if (this.$hasPermissions('B_isShowPrice')) { //  售价权限
        arr.splice(4, 0, { title: '参考退货单价', dataIndex: 'price', align: 'center', width: '8%', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
        arr.splice(7, 0, { title: '参考退货金额', align: 'center', dataIndex: 'totalAmount', width: '8%', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      }
      return arr
    }
  },
  methods: {
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesReturnList', query: { closeLastOldTab: true } })
    },
    // 已选产品  blur
    onCellBlur (val, record, type) {
      const valBackups = record.qtyBackups
      //  光标移出，值发生改变再调用编辑接口
      if (val && val != valBackups) {
        this.spinning = true
        salesReturnDetailUpdateQty({
          salesReturnDetailSn: record.salesReturnDetailSn,
          qty: record.qty,
          price: record.price
        }).then(res => {
          if (res.status == 200) {
            this.resetTable(false)
            this.$message.success(res.message)
            this.spinning = false
            record.qtyBackups = record.qty
          } else {
            this.spinning = false
            record.qty = valBackups
          }
        })
      } else {
        record.qty = valBackups
      }
    },
    // 修改退货原因
    updateReason (row) {
      this.spinning = true
      salesReturnDetailUpdateReason({
        salesReturnDetailSn: row.salesReturnDetailSn,
        returnReason: row.returnReason
      }).then(res => {
        if (res.status == 200) {
          this.resetTable(false)
          this.$message.success(res.message)
        }
        this.spinning = false
      })
    },
    // 获取单据详细
    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
          _this.spinning = true
          salesReturnDetailDel({ salesReturnDetailSn: row.salesReturnDetailSn }).then(res => {
            if (res.status == 200) {
              _this.resetTable(false)
            }
            _this.$message.info(res.message)
            _this.delLoading = false
            _this.spinning = false
          })
        }
      })
    },
    resetTable (flag) {
      this.$refs.table.refresh(flag)
      this.getOrderDetail()
    },
    //  重置
    resetSearchForm (flag) {
      this.productForm.productName = ''
      this.productForm.productCode = ''
      this.$refs.table.refresh(!!flag)
      this.getOrderDetail()
    },
    // 添加或修改产品
    saveProduct (row) {
      console.log(row)
      // 防止多次添加产品
      if (this.isInster) {
        return
      }
      if (!row.returnReason) {
        this.$message.info('请选择退货原因')
        return
      }
      this.isInster = true
      const params = {
        'salesReturnBillSn': this.orderSn,
        'salesReturnBillNo': this.ordeDetail.salesReturnBillNo,
        'price': row.productPrice,
        'cost': row.lastStockCost,
        'returnReason': row.returnReason,
        'productSn': row.productSn,
        'qty': row.qty
      }
      this.spinning = true
      salesReturnDetailInsert(params).then(res => {
        if (res.status == 200) {
          this.resetSearchForm(true)
          this.$message.success(res.message)
        }
        this.isInster = false
        this.spinning = false
      })
    },
    beforeSubmit () {
      if (this.total) {
        this.openDepartUserModal = true
      } else {
        this.$message.info('请添加产品')
      }
    },
    // 提交销售退货
    handleSubmit (data) {
      this.spinning = true
      salesReturnSubmit({ salesReturnBillSn: this.orderSn, ...data }).then(res => {
        if (res.status == 200) {
          this.handleBack()
          this.$message.success(res.message)
        }
        this.spinning = false
      })
    },
    closeGuideModel () {
      this.openGuideModal = false
    },
    // 导入产品
    hanldeOk (obj) {
      salesReturnBatchInsert(obj).then(res => {
        if (res.status == 200) {
          this.resetTable(true)
        }
      })
    },
    // 打印预览/快捷打印
    handlePrint (type) {
      const _this = this
      const a = ['WAIT_CUSTOMER_SERVICE_CONFIRM', 'WAIT_FINANCIAL_AUDIT', 'FINANCIAL_REJECT', 'FINISH'].find(item => item == this.detailData.billStatus)
      const status = a ? 'SALES_RETURN_AMOUNT' : 'SALES_RETURN_REASON'
      const params = { sn: this.$route.params.sn, status: status }
      _this.spinning = true
      // 导出
      if (type == 'export') {
        exportExcel(salesReturnExport, params, '销售退货', function () {
          _this.spinning = false
        })
      } else {
        // 打印或预览
        printFun(salesReturnPrint, params, type, '销售退货', () => {
          _this.spinning = false
        })
      }
    },
    pageInit () {
      this.orderSn = this.$route.params.sn
      this.buyerSn = this.$route.params.buyerSn
      this.resetSearchForm(true)
      this.$refs.partQuery.pageInit(this.buyerSn, 0)
      this.returnReasonList = this.$store.state.app.returnReason
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .salesReturnEdit-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
    .salesReturnEdit-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;
            }
          }
        }
      }
    }
  }
</style>
