<template>
  <div class="custConfirm-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="custConfirm-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="custConfirm-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;">客户名称：{{ ordeDetail&&ordeDetail.buyerName || '--' }}</span>
          <span style="margin: 0 10px;color: #666;">
            退货类别：{{ ordeDetail&&ordeDetail.goodFlagDictValue }}
          </span>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="custConfirm-cont">
        <a-form layout="inline" style="margin-bottom:10px;" @keyup.enter.native="searchForm">
          <a-form-item label="产品编码">
            <a-input id="custConfirm-productCode" v-model.trim="queryParam.productCode" placeholder="请输入产品编码" allowClear />
          </a-form-item>
          <a-form-item label="产品名称">
            <a-input id="custConfirm-productName" v-model.trim="queryParam.productName" placeholder="请输入产品名称" allowClear />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="searchForm" :disabled="disabled" id="custConfirm-refresh">查询</a-button>
            <a-button style="margin-left: 10px" @click="resetSearchForm" :disabled="disabled" id="custConfirm-reset">重置</a-button>
          </a-form-item>
        </a-form>
        <div style="border-top:1px solid #eee;padding-top:10px;">
          <a-button type="primary" :loading="loading" @click="openProductModal=true">新增产品</a-button>
          <a-button type="primary" :loading="loading" class="button-info" @click="setNewSalesRetrunOrder">生成新销退单</a-button>
          <a-button type="primary" ghost :loading="loading" @click="handlePlss">批量设置退货单价</a-button>
          <a-button
            type="primary"
            ghost
            style="margin-left:5px;"
            class="button-info"
            :loading="loading"
            @click="openPlSetReason">批量设置退货原因</a-button>
          <span style="margin-left:10px;" v-if="selNums">已选{{ selNums }}项</span>
          <a-button
            style="margin-left:10px;"
            ghost
            v-if="$hasPermissions('B_batchImportReturnPrice')"
            type="primary"
            @click="openGuideModal=true"
            class="button-error"
            :loading="loading">批量导入退货单价</a-button>
          <div style="float:right;color:#999;margin-top:8px;">说明：红色行表示收货时新增的产品；黄色行表示客服确认时新增的产品；退货原因文字显示红色表示退货原因和退货类别不一致；</div>
        </div>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          :style="{ height: tableHeight+84.5+'px' }"
          :rowClassName="(record, index) => record.addFlag == '1' ? (record.addType == 'WAREHOUSE_RECEIVE'?'redBg-row':'orgBg-row'):''"
          size="small"
          :rowKey="(record) => record.id"
          :row-selection="{ columnWidth: 40 }"
          :pagination="{pageSizeOptions: ['50','100','200','300','400']}"
          :pageSize="50"
          @rowSelection="rowSelectionFun"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 退货数量 -->
          <template slot="qty" slot-scope="text, record">
            <a-input-number
              v-if="record.isEdit"
              size="small"
              v-model="record.initialQty"
              :precision="0"
              :min="0"
              placeholder="请输入"
              style="width: 100%;" />
            <span v-else>
              {{ record.initialQty }}
            </span>
          </template>
          <!-- 仓库实收数量 -->
          <template slot="receiveQty" slot-scope="text, record">
            <a-input-number
              v-if="record.isEdit"
              size="small"
              v-model="record.receiveQty"
              :precision="0"
              :min="0"
              placeholder="请输入"
              style="width: 100%;" />
            <span v-else>
              {{ record.receiveQty }}
            </span>
          </template>
          <!-- 坏件数量 -->
          <template slot="badQty" slot-scope="text, record">
            <a-input-number
              v-if="record.isEdit"
              size="small"
              v-model="record.badQty"
              :precision="0"
              :min="0"
              placeholder="请输入"
              style="width: 100%;" />
            <span v-else>
              {{ record.badQty }}
            </span>
          </template>
          <!-- 良品数量 -->
          <template slot="goodQty" slot-scope="text, record">
            <a-input-number
              v-if="record.isEdit"
              size="small"
              v-model="record.goodQty"
              :precision="0"
              :min="0"
              placeholder="请输入"
              style="width: 100%;" />
            <span v-else>
              {{ record.goodQty }}
            </span>
          </template>
          <!-- 返库数量 -->
          <template slot="backStockQty" slot-scope="text, record">
            <a-input-number
              v-if="record.isEdit"
              size="small"
              v-model="record.backStockQty"
              :precision="0"
              :min="0"
              placeholder="请输入"
              style="width: 100%;" />
            <span v-else>
              {{ record.backStockQty }}
            </span>
          </template>
          <!-- 退货原因 -->
          <template slot="returnReason" slot-scope="text, record">
            <returnReason v-if="record.isEdit" v-model="record.returnReasonCode"></returnReason>
            <span v-else title="退货原因和退货类别不一致" :style="{color:record.needHandleFlag==1?'red':''}">{{ record.returnReason||'--' }}</span>
          </template>
          <!-- 备注 -->
          <template slot="remarks" slot-scope="text, record">
            <a-input
              v-if="record.isEdit"
              size="small"
              :maxLength="50"
              v-model.trim="record.returnReasonRemarks"
              allowClear
              placeholder="请输入备注信息(最多50字符)"/>
            <span v-else>{{ record.returnReasonRemarks||'--' }}</span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <div v-if="record.isEdit">
              <a-button
                size="small"
                type="link"
                class="button-warning"
                :loading="loading"
                @click="handleSave(record)"
              >保存</a-button>
              <a-button
                size="small"
                type="link"
                class="button-warning"
                @click="handleCancel(record)"
              >取消</a-button>
            </div>
            <div v-else>
              <a-button
                size="small"
                type="link"
                class="button-warning"
                @click="handleSetPrice(record)"
              >设置退货单价</a-button>
              <a-button
                size="small"
                type="link"
                class="button-warning"
                @click="handleEdit(record)"
              >编辑</a-button>
              <a-button
                :loading="loading"
                size="small"
                type="link"
                class="button-error"
                @click="handleDel(record)"
              >删除</a-button>
            </div>
          </template>
        </s-table>
        <div class="footer-btn">
          <a-button
            size="large"
            style="padding: 0 60px;"
            :disabled="spinning"
            type="primary"
            class="button-primary"
            @click="handleSubmit()"
            id="salesReturn-handleSubmit">审核通过</a-button>
        </div>
      </a-card>
    </a-spin>
    <!-- 设置退货单价 -->
    <setPriceModal
      v-drag
      ref="setPriceModal"
      modalTit="设置退货单价"
      :chooseData="chooseData"
      :openModal="showSetPriceModal"
      @setOk="setPriceOk"
      @cancel="cancelPriceModal"></setPriceModal>
    <!-- 添加产品 -->
    <chooseProductsModal
      ref="chooseProduct"
      :openModal="openProductModal"
      :buyerSn="$route.params.buyerSn"
      :warehouseSn="ordeDetail?ordeDetail.warehouseSn:''"
      @close="openProductModal=false"
      @addProduct="addProduct"></chooseProductsModal>
    <!-- 批量设置退货原因 -->
    <commonModal modalTit="批量设置退货原因" :openModal="showPlModal" @cancel="showPlModal=false" @ok="setPlReturnReason">
      <div style="text-align: left;">
        <div style="line-height: 24px;">
          <div><span style="color:red;">*</span>退货原因</div>
          <div><returnReason size="large" v-model="plReturnReason"></returnReason></div>
        </div>
        <div style="line-height: 24px;margin-top:10px;">
          <a-checkbox :checked="showEditRemarks" @change="e => showEditRemarks=!showEditRemarks">是否设置备注</a-checkbox>
        </div>
        <div style="line-height: 24px;margin-top:10px;" v-if="showEditRemarks">
          <div>备注</div>
          <div><a-input size="large" :maxLength="50" placeholder="请输入备注(最多50字符)" v-model="plReturnRemark"></a-input></div>
        </div>
      </div>
    </commonModal>
    <!-- 批量导入修改价格 -->
    <importGuideModal :params="{salesReturnBillSn: $route.params.sn}" :openModal="openGuideModal" @close="openGuideModal=false" @ok="importOk" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import setPriceModal from './setPriceModal.vue'
import commonModal from '@/views/common/commonModal.vue'
import returnReason from '@/views/common/returnReason'
import chooseProductsModal from '../receiveCheck/chooseProductsModal.vue'
import importGuideModal from './importGuideModal.vue'
import { salesReturnDetail, customerServiceConfirm } from '@/api/salesReturn'
import { salesReturnDetailList, updateByCustomerService, deleteByCustomerService, insertByCustomerService, salesReturnDetailSetReason, salesReturnAgainCreate, updateBatchUpdatePrice } from '@/api/salesReturnDetail'
export default {
  name: 'CustConfirm',
  mixins: [commonMixin],
  components: {
    STable,
    VSelect,
    setPriceModal,
    chooseProductsModal,
    returnReason,
    commonModal,
    importGuideModal
  },
  data () {
    return {
      spinning: false,
      tableHeight: 0, // 表格高度
      openGuideModal: false,
      orderSn: null,
      disabled: false,
      showEditRemarks: false,
      ordeDetail: null,
      loading: false,
      queryParam: {
        salesReturnBillSn: '',
        productName: '',
        productCode: ''
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        // 查询总计
        this.queryParam.salesReturnBillSn = this.$route.params.sn
        return salesReturnDetailList(Object.assign(parameter, this.queryParam)).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].isEdit = false
            }
            this.disabled = false
          }
          return data
        })
      },
      rowSelectionInfo: null,
      showSetPriceModal: false,
      chooseData: [],
      returnReasonList: [],
      openProductModal: false,
      plReturnReason: undefined,
      plReturnRemark: undefined,
      showPlModal: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 14 }
    }
  },
  watch: {
    showPlModal (newValue, oldValue) {
      if (!newValue) {
        this.plReturnReason = undefined
        this.plReturnRemark = undefined
        this.showEditRemarks = false
      }
    }
  },
  computed: {
    goodFlag () {
      return this.ordeDetail && this.ordeDetail.goodFlag || ''
    },
    selNums () {
      return this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length || 0
    },
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', align: 'center', width: '13%', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '20%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productEntity.unit', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '申请退货数量', dataIndex: 'initialQty', align: 'center', width: '10%', scopedSlots: { customRender: 'qty' } },
        { title: '仓库实收数量', dataIndex: 'receiveQty', align: 'center', width: '10%', scopedSlots: { customRender: 'receiveQty' } },
        { title: '坏件数量', dataIndex: 'badQty', align: 'center', width: '10%', scopedSlots: { customRender: 'badQty' } },
        { title: '良品数量', dataIndex: 'goodQty', align: 'center', width: '10%', scopedSlots: { customRender: 'goodQty' } },
        { title: '返库数量', dataIndex: 'backStockQty', align: 'center', width: '10%', scopedSlots: { customRender: 'backStockQty' } },
        // { title: '实际退货单价', dataIndex: 'price', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '实际退货金额', dataIndex: 'totalAmount', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '退货单价说明', dataIndex: 'priceRemark', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货原因', dataIndex: 'returnReason', width: '15%', align: 'center', scopedSlots: { customRender: 'returnReason' } },
        { title: '备注', dataIndex: 'remarks', width: '15%', align: 'center', scopedSlots: { customRender: 'remarks' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '20%', align: 'center' }
      ]
      if (this.$hasPermissions('B_salesReturnConfirm_salesPrice')) { //  售价权限
        arr.splice(9, 0, { title: '实际退货单价', dataIndex: 'price', align: 'right', width: '10%', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
        arr.splice(10, 0, { title: '实际退货金额', dataIndex: 'totalAmount', align: 'right', width: '10%', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      return arr
    }
  },
  methods: {
    // 确认批量修改价格
    importOk (data) {
      this.spinning = true
      updateBatchUpdatePrice(data).then(res => {
        if (res.status == 200) {
          this.resetSearchForm(false)
          this.$message.info(res.message)
        }
        this.spinning = false
      })
    },
    // 生成新销退单
    setNewSalesRetrunOrder () {
      if (!this.selNums) {
        this.$message.warning('请先选择产品！')
        return
      }
      const _this = this
      this.$confirm({
        title: '提示',
        content: '选择的产品将生成新的销退单，并且从当前列表中删除！是否确认生成？',
        centered: true,
        closable: true,
        onOk () {
          _this.loading = true
          _this.spinning = true
          const snList = []
          const arr = _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRows || []
          arr.map(item => {
            snList.push(item.salesReturnDetailSn)
          })
          salesReturnAgainCreate({ sourceBillSn: _this.orderSn, salesReturnBillDetailSnList: snList }).then(res => {
            if (res.status == 200) {
              _this.resetSearchForm(false)
            }
            _this.$message.info(res.message)
            _this.loading = false
            _this.spinning = false
          })
        }
      })
    },
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesReturnList', query: { closeLastOldTab: true } })
    },
    // 关闭批量设置退货单价弹窗
    cancelPriceModal () {
      this.$refs.setPriceModal.closeGrabOrder()
      this.showSetPriceModal = false
    },
    // 添加产品
    addProduct (data) {
      const a = this.$store.state.app.goodReturnReason.find(item => item.code == data.returnReasonCode)
      const b = this.$store.state.app.defectiveReturnReason.find(item => item.code == data.returnReasonCode)
      const goodFlag = a ? a.lookupCode : b.lookupCode

      const params = {
        'salesReturnBillSn': this.orderSn,
        'salesReturnBillNo': this.ordeDetail.salesReturnBillNo,
        'goodFlag': goodFlag,
        ...data
      }
      insertByCustomerService(params).then(res => {
        if (res.status == 200) {
          this.resetSearchForm(true)
          this.$message.info(res.message)
        }
        this.$refs.chooseProduct.resetLoading()
      })
    },
    // 设置价格
    handleSetPrice (record) {
      this.chooseData = [record]
      this.showSetPriceModal = true
    },
    // 批量设置退货单价
    handlePlss () {
      if (!this.selNums) {
        this.$message.warning('请先选择产品！')
        return
      }
      this.chooseData = this.rowSelectionInfo.selectedRows
      this.showSetPriceModal = true
    },
    // 设置价格成功
    setPriceOk () {
      this.showSetPriceModal = false
      this.$refs.table.clearSelected()
      this.resetSearchForm(false)
    },
    // 批量设置退货原因
    openPlSetReason () {
      if (this.selNums) {
        this.showPlModal = true
      } else {
        this.$message.warning('请先选择产品！')
      }
    },
    setPlReturnReason () {
      if (!this.plReturnReason) {
        this.$message.warning('请选择退货原因！')
      } else {
        this.spinning = true
        const snList = []
        const arr = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
        const rows = this.returnReasonlist.find(item => item.code == this.plReturnReason)
        arr.map(item => {
          snList.push(item.salesReturnDetailSn)
        })
        salesReturnDetailSetReason({
          salesReturnBillDetailSnList: snList,
          salesReturnBillSn: this.orderSn,
          returnReason: rows ? rows.dispName : '',
          returnReasonCode: this.plReturnReason,
          returnReasonRemarks: this.showEditRemarks ? this.plReturnRemark || '' : undefined,
          goodFlag: rows.lookupCode
        }).then(res => {
          if (res.status == 200) {
            this.showPlModal = false
            this.$refs.table.clearSelected()
            this.resetSearchForm(false)
          }
          this.spinning = false
        })
      }
    },
    // 保存
    handleSave (record) {
      if (!record.returnReasonCode) {
        this.$message.warning('请先选择退货原因！')
        return
      }
      if (record.receiveQty != record.badQty + record.goodQty) {
        this.$message.warning('仓库实收数量必需等于良品数量和坏件数量之和！')
        return
      }
      const rows = this.returnReasonlist.find(item => item.code == record.returnReasonCode)
      record.returnReason = rows ? rows.dispName : ''
      record.goodFlag = rows.lookupCode
      this.spinning = true
      updateByCustomerService(record).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.handleCancel(record)
          this.getOrderDetail()
        }
        this.spinning = false
      })
    },
    // 删除产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.loading = true
          _this.spinning = true
          deleteByCustomerService({ salesReturnDetailSn: row.salesReturnDetailSn, salesReturnBillSn: _this.orderSn }).then(res => {
            if (res.status == 200) {
              _this.resetSearchForm(false)
            }
            _this.$message.info(res.message)
            _this.loading = false
            _this.spinning = false
          })
        }
      })
    },
    // 编辑
    handleEdit (record) {
      record.isEdit = true
    },
    // 取消
    handleCancel (record) {
      record.isEdit = false
      this.$refs.table.refresh()
    },
    // 获取单据详细
    getOrderDetail () {
      salesReturnDetail({ sn: this.orderSn }).then(res => {
        this.ordeDetail = res.data || null
        if (res.data) {
          this.returnReasonlist = [...this.$store.state.app.goodReturnReason, ...this.$store.state.app.defectiveReturnReason]
        }
      })
    },
    // 审核销售单
    handleSubmit () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认审核通过吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          customerServiceConfirm({ salesReturnBillSn: _this.orderSn }).then(res => {
            if (res.status == 200) {
              _this.handleBack()
              _this.$message.success(res.message)
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  重置
    resetSearchForm (flag) {
      if (flag) {
        this.queryParam.productName = ''
        this.queryParam.productCode = ''
        this.rowSelectionInfo = null
        this.$refs.table.clearSelected()
      }
      this.$refs.table.refresh(flag)
      this.getOrderDetail()
    },
    searchForm () {
      this.$refs.table.refresh(true)
      this.$refs.table.clearSelected()
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.orderSn = this.$route.params.sn
      this.getOrderDetail()
    },
    setTableH () {
      this.tableHeight = window.innerHeight - 390
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.$refs.table.refresh()
      this.pageInit()
    }
  },
  activated () {
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.$refs.table.refresh()
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .custConfirm-wrap{
    position: relative;
    height: 100%;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      height: 100%;
    }
    .footer-btn{
      text-align: center;
    }
    .custConfirm-cont{
      margin-top: 6px;
      .sTable{
        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;
            }
          }
        }
      }
    }
    .redBg-row{
      background-color: #f5beb4;
    }
    .orgBg-row{
      background-color: #fffca2;
    }
  }
</style>
