<template>
  <a-modal
    centered
    class="setPrice-detail-modal"
    :footer="null"
    :maskClosable="false"
    v-model="isShow"
    :title="modalTit"
    :bodyStyle="{padding: modalTit?'25px 32px 20px':'50px 32px 15px'}"
    @cancel="isShow=false"
    width="80%">
    <a-spin :spinning="spinning" tip="Loading...">
      <div class="common-main">
        <div class="form-row">
          <div>
            退货单价：
            <a-radio-group v-model="form.grabFlag" @change="grabChange">
              <a-radio :value="0">
                不抓单
              </a-radio>
              <a-radio :value="1">
                抓单
              </a-radio>
            </a-radio-group>
          </div>
          <div v-if="form.grabFlag==0">
            是否打折：
            <a-radio-group v-model="form.discountFlag">
              <a-radio :value="0">
                不打折
              </a-radio>
              <a-radio :value="1">
                打折
              </a-radio>
            </a-radio-group>
            <div v-if="form.discountFlag==1">
              <a-input-number placeholder="请输入折扣" v-model="form.discount" :min="0" :max="10" :precision="2" />
              <span class="mleft">示例：7折表示使用当前售价×0.7作为退货单价（保留两位小数）</span>
              <a-button type="primary" :disabled="disabled" @click="handleSave" class="button-error">设置完成</a-button>
            </div>
            <div v-else>
              <a-button type="primary" :disabled="disabled" @click="handleSave" class="button-error">设置完成</a-button>
            </div>
          </div>
          <div v-else>
            销售单号：
            <a-input placeholder="请输入销售单号" v-model.trim="form.salesBillNo" :maxLength="50" @change="fetchUser"/>
            <span class="mleft">{{ buyerName }}</span>
            <a-button type="primary" :disabled="!salesBillFlag" @click="handleSave('salesBillNo')" class="button-error errorBtn">设置完成</a-button>
          </div>
        </div>
        <a-divider>请给以下产品设置新的退货单价</a-divider>
        <!-- 搜索条件 -->
        <div style="overflow: hidden;">
          <a-form layout="inline" style="margin-bottom:10px;float:left;" @keyup.enter.native="searchProduct">
            <a-form-item label="产品编码">
              <a-input id="setPrice-productCode" v-model.trim="queryParam.productCode" placeholder="请输入产品编码" allowClear />
            </a-form-item>
            <a-form-item label="产品名称">
              <a-input id="setPrice-productName" v-model.trim="queryParam.productName" placeholder="请输入产品名称" allowClear />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" class="button-info" @click="searchProduct" :disabled="disabled" id="setPrice-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="setPrice-reset">重置</a-button>
            </a-form-item>
          </a-form>
          <div style="float:right;color:#999;margin-top:10px;">说明：红色行表示收货时新增的产品；黄色行表示客服确认时新增的产品；退货原因文字显示红色表示退货原因和退货类别不一致；</div>
        </div>
        <!-- 表格数据 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :rowClassName="(record, index) => record.addFlag == '1' ? (record.addType == 'WAREHOUSE_RECEIVE'?'redBg-row':'orgBg-row'):''"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: 400 }"
          :showPagination="false"
          bordered>
          <!-- 退货原因 -->
          <template slot="returnReason" slot-scope="text, record">
            <span title="退货原因和退货类别不一致" :style="{color:record.needHandleFlag==1?'red':''}">{{ record.returnReason||'--' }}</span>
          </template>
        </s-table>
      </div>
      <grabOrderModal ref="grabOrder" :infoData="listInfo" :openModal="openGrabOrderModal" @ok="handleGrabOrderOk" @close="closeGrabOrder"></grabOrderModal>
    </a-spin>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import debounce from 'lodash/debounce'
import { STable, VSelect } from '@/components'
import { salesDetailByNo } from '@/api/salesNew'
import { setReturnPrice } from '@/api/salesReturnDetail'
import { grabSalesBill } from '@/api/salesReturn'
import grabOrderModal from './grabOrderModal.vue'
export default {
  name: 'SetPriceModal',
  mixins: [commonMixin],
  components: { STable, VSelect, grabOrderModal },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    modalTit: { // 弹框标题
      type: String,
      default: null
    },
    chooseData: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  data () {
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      isShow: this.openModal, //  是否打开弹框
      disabled: false,
      spinning: false,
      queryParam: {
        productName: '',
        productCode: ''
      },
      form: {
        grabFlag: 0, // 是否抓单
        discountFlag: 0, // 是否打折
        discount: '', // 折扣
        salesBillNo: '' // 销售单号
      },
      columns: [
        { title: '序号', dataIndex: 'no', width: '6%', align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', align: 'center', width: '13%', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '25%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productEntity.unit', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '申请退货数量', dataIndex: 'qty', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '仓库实收数量', dataIndex: 'receiveQty', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '坏件数量', dataIndex: 'badQty', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '良品数量', dataIndex: 'goodQty', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '返库数量', dataIndex: 'backStockQty', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '退货单价', dataIndex: 'price', align: 'right', width: '10%', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '退货单价说明', dataIndex: 'priceRemark', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货原因', dataIndex: 'returnReason', width: '15%', align: 'center', scopedSlots: { customRender: 'returnReason' } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return new Promise((res, rej) => {
          const chooseList = JSON.parse(JSON.stringify(this.chooseData))
          const ret = chooseList.filter(item => {
            return item.productEntity.code.indexOf(this.queryParam.productCode) >= 0 &&
            item.productEntity.name.indexOf(this.queryParam.productName) >= 0
          })
          const arr = ret.map(con => { return con.salesReturnDetailSn })
          if (arr && arr.length > 0) {
            if (this.salesBillSnList && this.salesBillSnList.length > 0) {
              this.salesBillSnList.forEach(item => {
                const pot = arr.indexOf(item.salesReturnDetailSn)
                if (pot != -1) {
                  if (item.price || item.price == 0) {
                    ret[pot].price = item.price
                  }
                  ret[pot].priceRemark = '抓单（' + this.form.salesBillNo + '）'
                }
              })
            }
          }

          res({
            list: ret,
            count: ret.length
          })
        })
      },
      buyerName: '',
      openGrabOrderModal: false,
      listInfo: null,
      noShowBillSnList: null,
      salesBillSnList: [],
      salesBillFlag: false // 抓单按钮
    }
  },
  methods: {
    fetchUser () {
      this.salesBillFlag = false
      this.form.salesBillNo = this.form.salesBillNo.replace(/\s+/g, '')
      if (!this.form.salesBillNo) {
        this.form.salesBillNo = ''
        this.buyerName = ''
        return
      }
      this.spinning = true
      salesDetailByNo({ salesBillNo: this.form.salesBillNo }).then(res => {
        this.spinning = false
        this.buyerName = res.data ? res.data.buyerName : ''
        this.handleBlur()
      })
    },
    // 打开抓单设置单价弹窗
    handleBlur () {
      if (!this.buyerName) {
        this.$message.warning('请输入正确的销售单号！')
        return
      }
      const productArr = this.chooseData.map(item => { return { productSn: item.productSn, code: item.productEntity.code, salesReturnDetailSn: item.salesReturnDetailSn } })
      const objInfo = {
        salesReturnBillSn: this.$route.params.sn,
        salesBillNo: this.form.salesBillNo,
        productList: productArr
      }
      grabSalesBill(objInfo).then(res => {
        if (res.status == 200) {
          const newList = res.data
          const _this = this
          _this.salesBillFlag = true
          if (newList && newList.length > 0) {
            const flag = newList.some(item => Object.keys(item).length > 2)
            if (flag) {
              _this.listInfo = newList.filter(con => Object.keys(con).length > 2)
              _this.openGrabOrderModal = !!_this.isShow
              const noShowList = newList.filter(con => Object.keys(con).length <= 2)
              _this.noShowBillSnList = _this.getNewSalesBillList(noShowList)
              _this.salesBillSnList = _this.noShowBillSnList ? _this.noShowBillSnList : []
            } else {
              const resultVal = _this.getNewSalesBillList(newList)
              this.salesBillSnList = resultVal
            }
          }
        }
      })
    },
    getNewSalesBillList (list) {
      const resultVal = list.map(item => {
        const nameArr = Object.getOwnPropertyNames(item)
        let newName = ''
        nameArr.forEach(con => {
          if (con != 'product') {
            newName = con
          }
        })
        const newobj = {
          salesReturnDetailSn: item.product.salesReturnDetailSn, salesBillDetailSn: item[newName].salesBillDetailSn
        }
        return newobj
      })
      return resultVal
    },
    handleGrabOrderOk (con) {
      if (this.noShowBillSnList && this.noShowBillSnList.length > 0) {
        this.salesBillSnList = this.noShowBillSnList.concat(con)
      } else {
        this.salesBillSnList = con
      }
      this.$refs.table.refresh(true)
    },
    closeGrabOrder () {
      this.listInfo = null
      this.openGrabOrderModal = false
    },
    // 设置价格
    handleSave (type) {
      if (type && type === 'salesBillNo') {
        if (!this.buyerName) {
          this.$message.warning('请输入正确的销售单号！')
          return
        }
      }
      // 不抓单且打折
      if (this.form.grabFlag == 0 && this.form.discountFlag == 1) {
        if (!this.form.discount) {
          this.$message.info('请输入折扣')
          return
        }
      }
      // 抓单
      if (this.form.grabFlag == 1) {
        if (!this.form.salesBillNo) {
          this.$message.info('请输入销售单号')
          return
        }
        this.form.discountFlag = undefined
        this.form.discount = undefined
        this.form.salesReturnBillDetailList = this.salesBillSnList
      } else {
        const snList = []
        this.form.salesBillNo = ''
        this.chooseData.map(item => {
          snList.push({ salesReturnDetailSn: item.salesReturnDetailSn })
        })
        this.form.salesReturnBillDetailList = snList
      }
      const params = Object.assign(this.form)
      this.disabled = true
      this.spinning = true
      setReturnPrice(params).then(res => {
        if (res.status == 200) {
          this.salesBillSnList = null
          this.$emit('setOk')
          this.$message.info(res.message)
        }
        this.disabled = false
        this.spinning = false
      })
    },
    grabChange (e) {
      this.buyerName = ''
      if (e.target.value == 1) {
        this.form.salesBillNo = ''
      } else {
        this.form.discountFlag = 0
        this.form.discount = ''
      }
    },
    // 取消
    handleCommonCancel () {
      this.salesBillFlag = false
      this.$emit('cancel')
    },
    // 查询
    searchProduct () {
      this.$refs.table.refresh(true)
    },
    // 重置
    resetSearchForm () {
      this.form = {
        grabFlag: 0, // 是否抓单
        discountFlag: 0, // 是否打折
        discount: '', // 折扣
        salesBillNo: '' // 销售单号
      }
      this.queryParam = {
        productName: '',
        productCode: ''
      }
      this.buyerName = ''
      if (this.$refs.table) {
        this.$refs.table.refresh(true)
      }
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.salesBillSnList = null
        this.handleCommonCancel()
      } else {
        this.resetSearchForm()
      }
    }
  }
}
</script>

<style lang="less">
  .setPrice-detail-modal{
    .form-row{
      > div{
        display: flex;
        align-items:center;
        padding: 10px 0;
        input[type='text']{
          width:250px;
        }
        .mleft{
          margin-left:10px;
        }
      }
    }
    .redBg-row{
      background-color: #f5beb4;
    }
    .errorBtn[disabled]{
     background: #ff6666;
     outline: none;
     color:rgba(255,255,255,.5);
    }
    .orgBg-row{
      background-color: #fffca2;
    }
  }
</style>
