<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="disabled" @click="handleSave" class="button-error">设置完成</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>
        </s-table>
      </div>
    </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/sales'
import { setReturnPrice } from '@/api/salesReturnDetail'
export default {
  name: 'SetPriceModal',
  mixins: [commonMixin],
  components: { STable, VSelect },
  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', customRender: function (text) { return text || '--' } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return new Promise((res, rej) => {
          const ret = this.chooseData.filter(item => {
            return item.productEntity.code.indexOf(this.queryParam.productCode) >= 0 &&
            item.productEntity.name.indexOf(this.queryParam.productName) >= 0
          })
          res({
            list: ret,
            count: ret.length
          })
        })
      },
      buyerName: ''
    }
  },
  methods: {
    fetchUser () {
      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 : ''
      })
    },
    // 设置价格
    handleSave () {
      // 不抓单且打折
      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
      }
      const snList = []
      this.chooseData.map(item => {
        snList.push(item.salesReturnDetailSn)
      })
      const params = Object.assign(this.form, { salesReturnBillDetailSnList: snList })
      console.log(params)
      this.disabled = true
      this.spinning = true
      setReturnPrice(params).then(res => {
        if (res.status == 200) {
          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.$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.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;
    }
    .orgBg-row{
      background-color: #fffca2;
    }
  }
</style>
