<template>
  <a-modal
    centered
    class="promotionRules-rule-modal"
    :footer="null"
    :maskClosable="false"
    :title="itemSn ? '编辑':'新增'"
    v-model="isShow"
    @cancel="isShow = false"
    :width="960">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        id="promotionRules-rule-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
      >
        <a-form-model-item label="促销类型" prop="promoRuleType" :extra="extra">
          <v-select
            code="PROMO_RULE_TYPE"
            id="promotionRules-rule-promoRuleType"
            v-model="form.promoRuleType"
            allowClear
            @change="changeType"
            placeholder="请选择促销类型"
          ></v-select>
        </a-form-model-item>
        <!-- 买产品送产品 -->
        <div v-if="form.promoRuleType == 'BUY_PROD_GIVE_PROD'">
          <a-form-model-item label="促销设置" required>
            购买满
            <a-form-model-item prop="orderGoodsQty" :label-col="{span: 0}" style="display: inline-block;">
              <a-input-number
                id="promotionRules-rule-orderGoodsQty"
                v-model="form.orderGoodsQty"
                :precision="0"
                :min="1"
                :max="99999999"
                placeholder="请输入数量"
                style="width: 100%;" />
            </a-form-model-item>
            个正价产品，送
            <a-form-model-item prop="promoQty" :label-col="{span: 0}" style="display: inline-block;">
              <a-input-number
                id="promotionRules-rule-promoQty"
                v-model="form.promoQty"
                :precision="0"
                :min="1"
                :max="99999999"
                placeholder="请输入数量"
                style="width: 100%;" />
            </a-form-model-item>
            个促销品
          </a-form-model-item>
          <a-form-model-item label="正价产品" prop="normalGoodsList">
            <a-button id="promotionRules-rule-normalGoodsList" type="primary" class="button-success" @click="chooseProduct('normal')">选择</a-button>
          </a-form-model-item>
          <a-form-model-item label="促销品" prop="promoGoodsList">
            <a-button id="promotionRules-rule-promoGoodsList" type="primary" class="button-success" @click="chooseProduct('promo')">选择</a-button>
          </a-form-model-item>
        </div>
        <!-- 买产品送采购额 -->
        <div v-if="form.promoRuleType == 'BUY_PROD_GIVE_MONEY'">
          <a-form-model-item label="促销设置" prop="promoType">
            <a-radio-group v-model="form.promoType" @change="radioChange">
              <a-radio value="promo_amount" style="margin-bottom: 10px;">
                购买满
                <a-form-model-item prop="orderAmounts" :label-col="{span: 0}" style="display: inline-block;">
                  <a-input-number
                    id="promotionRules-rule-orderAmounts"
                    v-model="form.orderAmounts"
                    :precision="2"
                    :min="0.1"
                    :max="99999999"
                    placeholder="请输入金额"
                    style="width: 100%;" />
                </a-form-model-item>
                元正价产品，送
                <a-form-model-item prop="promoAmount" :label-col="{span: 0}" style="display: inline-block;">
                  <a-input-number
                    id="promotionRules-rule-promoAmount"
                    v-model="form.promoAmount"
                    :precision="2"
                    :min="0.1"
                    :max="99999999"
                    placeholder="请输入金额"
                    style="width: 100%;" />
                </a-form-model-item>
                元采购额可用于购买促销品
              </a-radio>
              <a-radio value="promo_amount_per">
                购买满
                <a-form-model-item prop="orderAmount" :label-col="{span: 0}" style="display: inline-block;">
                  <a-input-number
                    id="promotionRules-rule-orderAmount"
                    v-model="form.orderAmount"
                    :precision="2"
                    :min="0.1"
                    :max="99999999"
                    placeholder="请输入金额"
                    style="width: 100%;" />
                </a-form-model-item>
                元正价产品可以返正价产品采购额的
                <a-form-model-item prop="promoAmountPer" :label-col="{span: 0}" style="display: inline-block;">
                  <a-input-number
                    id="promotionRules-rule-promoAmountPer"
                    v-model="form.promoAmountPer"
                    :precision="2"
                    :min="0.1"
                    :max="100"
                    placeholder="请输入比例"
                    style="width: 100%;" />
                </a-form-model-item>
                %用于购买促销品
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="正价产品" prop="normalGoodsList">
            <a-button id="promotionRules-rule-normalGoodsList" type="primary" class="button-success" @click="chooseProduct('normal')">选择</a-button>
          </a-form-model-item>
          <a-form-model-item label="促销品" prop="promoGoodsList">
            <a-button id="promotionRules-rule-promoGoodsList" type="primary" class="button-success" @click="chooseProduct('promo')">选择</a-button>
          </a-form-model-item>
        </div>
        <!-- 特价产品销售 -->
        <div v-if="form.promoRuleType == 'PROMO_PROD'">
          <a-form-model-item label="特价产品" prop="promoGoodsList">
            <a-button id="promotionRules-rule-promoGoodsList" type="primary" class="button-success" @click="chooseProduct('promo')">选择</a-button>
          </a-form-model-item>
        </div>
        <!-- 加价换购 -->
        <div v-if="form.promoRuleType == 'ADD_PRICE_PURCH'">
          <a-form-model-item label="加价规则" prop="orderGoodsQty">
            购买满
            <a-input-number
              id="promotionRules-rule-orderGoodsQty"
              v-model="form.orderGoodsQty"
              :precision="0"
              :min="1"
              :max="99999999"
              placeholder="请输入数量"
              style="width: 30%;" />
            个正价产品，可以以换购价购买任意1个换购产品
          </a-form-model-item>
          <a-form-model-item label="正价产品" prop="normalGoodsList">
            <a-button id="promotionRules-rule-normalGoodsList" type="primary" class="button-success" @click="chooseProduct('normal')">选择</a-button>
          </a-form-model-item>
          <a-form-model-item label="换购产品" prop="promoGoodsList">
            <a-button id="promotionRules-rule-promoGoodsList" type="primary" class="button-success" @click="chooseProduct('promo')">选择</a-button>
          </a-form-model-item>
        </div>
      </a-form-model>
      <div class="btn-cont">
        <a-button type="primary" id="promotionRules-rule-modal-save" @click="handleSave">保存</a-button>
        <a-button id="promotionRules-rule-modal-back" @click="isShow = false" style="margin-left: 15px;">取消</a-button>
      </div>
    </a-spin>
    <!-- 选择产品 -->
    <choose-price-products-modal
      :openModal="openPriceProductsModal"
      :nowData="nowData"
      :ruleType="form.promoRuleType"
      :goodsType="nowChooseGoodsType"
      @ok="handleOk"
      @close="closePriceProducts" />
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { VSelect } from '@/components'
import ChoosePriceProductsModal from './choosePriceProductsModal.vue'
import { promoRuleSave, promoRuleDetailD } from '@/api/promoRule'
export default {
  name: 'EditRuleModalModal',
  mixins: [commonMixin],
  components: { VSelect, ChoosePriceProductsModal },
  props: {
    openModal: {
      //  弹框显示状态
      type: Boolean,
      default: false
    },
    itemSn: {
      type: String || Number,
      default: ''
    }
  },
  data () {
    return {
      isShow: this.openModal, //  是否打开弹框
      formItemLayout: {
        labelCol: { span: 3 },
        wrapperCol: { span: 21 }
      },
      form: {
        promoRuleType: undefined, //  促销类型
        orderGoodsQty: '', //  正价品数量
        promoQty: '', //  促销品数量
        promoType: undefined, //  促销设置（买产品送采购额(定额)、买产品送采购额(定比例)）
        orderAmounts: '', //  正价品金额   金额
        orderAmount: '', //  正价品金额  百分比
        promoAmount: '', // 采购额
        promoAmountPer: '', // 百分比
        normalGoodsList: '', //  已选正价品
        promoGoodsList: '' //  已选促销品
      },
      rules: {
        promoRuleType: [{ required: true, message: '请选择促销类型', trigger: 'change' }],
        orderGoodsQty: [{ required: true, message: '请输入正价品数量', trigger: 'blur' }],
        promoQty: [{ required: true, message: '请输入促销品数量', trigger: 'blur' }],
        promoType: [{ required: true, message: '请选择促销方式', trigger: 'change' }],
        orderAmounts: [ { validator: this.orderAmountsValidator } ],
        orderAmount: [ { validator: this.orderAmountValidator } ],
        promoAmount: [ { validator: this.promoAmountValidator } ],
        promoAmountPer: [ { validator: this.promoAmountPerValidator } ],
        normalGoodsList: [{ required: true, message: '请选择正价品', trigger: 'change' }],
        promoGoodsList: [{ required: true, message: '请选择促销品', trigger: 'change' }]
      },
      openPriceProductsModal: false,
      normalGoodsList: [], //  当前已选正价产品
      promoGoodsList: [], //  当前已选促销品
      nowChooseGoodsType: '', //  当前选择产品的类型(正价产品/促销品)
      nowData: [], //  选择产品
      spinning: false
    }
  },
  computed: {
    extra () {
      let str = ''
      if (this.form.promoRuleType == 'BUY_PROD_GIVE_PROD') { //  买产品送产品
        str = '（即买正价产品送促销品，例如买刹车片送滤芯）'
      } else if (this.form.promoRuleType == 'BUY_PROD_GIVE_MONEY') { //  买产品送采购额
        str = '（即买正价产品送对应促销品的采购额，例如买1000元刹车片送200元滤清器采购额）'
      } else if (this.form.promoRuleType == 'PROMO_PROD') { //  特价产品销售
        str = '（即将产品按设置的特惠价格进行促销）'
      } else if (this.form.promoRuleType == 'ADD_PRICE_PURCH') { //  加价换购
        str = '（即购买其它产品时，以设置的金额可购买换购产品）'
      }
      return str
    }
  },
  methods: {
    // 详情
    getDetail () {
      promoRuleDetailD({ sn: this.itemSn }).then(res => {
        if (res.status == 200) {
          const data = res.data
          this.form = Object.assign(this.form, data)
          if (data.normalGoodsList) {
            data.normalGoodsList.map(item => {
              delete item.id
              item.name = item.goodsName
            })
          }
          if (data.promoGoodsList) {
            data.promoGoodsList.map(item => {
              delete item.id
              item.name = item.goodsName
            })
          }
          if (data.promoRuleType == 'BUY_PROD_GIVE_MONEY' && data.promoType == 'promo_amount') { //  买产品送采购额  金额
            this.form.orderAmounts = data.orderAmount ? data.orderAmount : null
            this.form.promoAmount = data.promoAmount ? data.promoAmount : null
            this.form.promoAmountPer = ''
            this.form.orderAmount = ''
          } else if (data.promoRuleType == 'BUY_PROD_GIVE_MONEY' && data.promoType == 'promo_amount_per') { //  买产品送采购额  百分比
            this.form.orderAmount = data.orderAmount ? data.orderAmount : null
            this.form.promoAmountPer = Number(data.promoAmountPer) * 100
            this.form.orderAmounts = ''
            this.form.promoAmount = ''
          }
          this.normalGoodsList = data.normalGoodsList || []
          this.promoGoodsList = data.promoGoodsList || []
        }
      })
    },
    // 采购金额自定义校验  金额
    orderAmountsValidator (rule, value, callback) {
      if (this.form.promoType == 'promo_amount' && !value) {
        callback(new Error('请输入正价品金额'))
      } else {
        callback()
      }
    },
    // 采购金额自定义校验  百分比
    orderAmountValidator (rule, value, callback) {
      if (this.form.promoType == 'promo_amount_per' && !value) {
        callback(new Error('请输入正价品金额'))
      } else {
        callback()
      }
    },
    //  采购额百分比自定义校验
    promoAmountValidator (rule, value, callback) {
      if (this.form.promoType == 'promo_amount' && !value) {
        callback(new Error('请输入采购额'))
      } else {
        callback()
      }
    },
    //  采购额百分比自定义校验
    promoAmountPerValidator (rule, value, callback) {
      if (this.form.promoType == 'promo_amount_per' && !value) {
        callback(new Error('请输入百分比'))
      } else {
        callback()
      }
    },
    //  保存
    handleSave () {
      const _this = this
      //  处理表单校验
      _this.form.normalGoodsList = this.normalGoodsList.length > 0 ? 'a' : ''
      _this.form.promoGoodsList = this.promoGoodsList.length > 0 ? 'a' : ''
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          form.normalGoodsList = this.normalGoodsList
          form.promoGoodsList = this.promoGoodsList
          form.promoActiveSn = this.$route.params.sn
          if (form.promoRuleType == 'BUY_PROD_GIVE_MONEY' && form.promoType == 'promo_amount_per') { //  买产品送采购额  百分比
            form.promoAmountPer = Number(form.promoAmountPer) / 100
            form.orderAmounts = ''
            form.promoAmount = ''
          } else if (form.promoRuleType == 'BUY_PROD_GIVE_MONEY' && form.promoType == 'promo_amount') { //  买产品送采购额  金额
            form.orderAmount = form.orderAmounts
            form.promoAmountPer = ''
          }
          if (!_this.itemSn) { delete form.id }
          _this.spinning = true
          promoRuleSave(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(() => {
                _this.$emit('ok')
                _this.isShow = false
                _this.spinning = false
              }, 1000)
            } else {
              _this.spinning = false
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleOk (obj) {
      if (this.nowChooseGoodsType == 'normal') { // 正价品
        this.normalGoodsList = obj
      } else if (this.nowChooseGoodsType == 'promo') { // 促销品
        this.promoGoodsList = obj
      }
    },
    // 选择产品
    chooseProduct (type) {
      this.nowChooseGoodsType = type
      if (type == 'normal') { // 正价品
        this.nowData = this.normalGoodsList || []
      } else if (type == 'promo') { // 促销品
        this.nowData = this.promoGoodsList || []
      }
      this.openPriceProductsModal = true
    },
    // 关闭选择产品弹框
    closePriceProducts () {
      this.openPriceProductsModal = false
    },
    radioChange (e) {
      if (e.target.value == 'promo_amount') {
        this.form.orderAmount = null
        this.form.promoAmountPer = null
      } else if (e.target.value == 'promo_amount_per') {
        this.form.orderAmounts = null
        this.form.promoAmount = null
      }
    },
    //  促销类型  change
    changeType (val) {
      this.form.promoRuleType = val
      this.form.orderGoodsQty = ''
      this.form.promoQty = ''
      this.form.promoType = undefined
      this.form.orderAmounts = ''
      this.form.orderAmount = ''
      this.form.promoAmount = ''
      this.form.promoAmountPer = ''
      this.form.normalGoodsList = ''
      this.form.promoGoodsList = ''
      this.normalGoodsList = []
      this.promoGoodsList = []
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.$refs.ruleForm.resetFields()
      }
    },
    itemSn (newValue, oldValue) {
      if (this.isShow && newValue) {
        this.getDetail()
      }
    }
  }
}
</script>

<style lang="less">
.promotionRules-rule-modal {
	.ant-modal-body {
		padding: 40px 40px 24px;
	}
	.btn-cont {
		text-align: center;
		margin: 35px 0 10px;
	}
  .ant-radio + span{
    line-height: 40px;
  }
}
</style>
