<template>
  <a-modal
    centered
    class="promotionList-basicInfo-modal"
    :footer="null"
    :maskClosable="false"
    title="规则设置"
    v-model="isShow"
    @cancel="isShow=false"
    width="83%">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        id="promotionList-basicInfo-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol" >
        <a-form-model-item label="规则简称" prop="description">
          <a-input
            size="small"
            id="promotionList-description"
            v-model.trim="form.description"
            allowClear
            placeholder="请输入规则简称（最多20个字符）"
            :maxLength="20"></a-input>
        </a-form-model-item>
        <a-form-model-item label="规则门槛" prop="gateFlag">
          <a-radio-group v-model="form.gateFlag" button-style="solid" size="small" @change="handleChange">
            <a-radio-button value="1">
              有
            </a-radio-button>
            <a-radio-button value="0">
              无
            </a-radio-button>
          </a-radio-group>
          <div v-if="form.gateFlag && form.gateFlag === '1'">
            <v-select
              size="small"
              style="width:60%;"
              v-model="form.gateType"
              id="promotionList-gateType"
              code="PROMOTION_GATE_TYPE"
              placeholder="请选择"
              @change="changeGateTypeFlag"
              allowClear></v-select>
            <div v-if="form.gateType==='RATIO_AMOUNT'">
              购买门槛产品金额 <a-input-number v-model="form.gateAmount" :min="0" :max="999999" :precision="2" size="small"/> %作为配额
              <a-tooltip title="如：填写100%，则购买10000元门槛产品，可享受10000配额购买特价产品，根据门槛金额动态调整配额">
                <a-icon type="question-circle" theme="filled" :style="{ fontSize: '14px', color: 'gray' }"/>
              </a-tooltip>
            </div>
            <div v-if="form.gateType==='MIN_AMOUNT'">
              购买门槛产品满最低金额 <a-input-number v-model="form.gateAmount" :min="0" :max="999999" :precision="2" size="small"/>元，不限制配额。
            </div>
            <div class="ruleDescList" v-if="form.gateType==='FIXED_AMOUNT'">
              购买满
              <a-input-number v-model="form.gateAmount" :max="999999" :min="0" :precision="2" size="small"/>
              元门槛产品，可使用
              <a-input-number v-model="form.quotaAmount" :max="999999" :min="0" :precision="2" size="small"/>
              元配额，采购规则中的特价商品（配额算销售额)
            </div>
          </div>
        </a-form-model-item>
        <a-form-model-item prop="minOrderFlag" label="订单起订金额">
          <a-select default-value="1" v-model="form.minOrderFlag" style="width: 160px" size="small">
            <a-select-option value="0">
              不限
            </a-select-option>
            <a-select-option value="1">
              限制
            </a-select-option>
          </a-select>
          <a-input-number
            v-show="form.minOrderFlag && form.minOrderFlag=='1'"
            size="small"
            style="margin-left:10px;width:300px;"
            v-model="form.minOrderAmount"
            :min="0"
            :step="1"
            :max="999999"
            :precision="2"
            placeholder="请输入金额"/>
        </a-form-model-item>
        <a-form-model-item prop="upperLimitFlag" label="活动经费上限">
          <a-select default-value="1" v-model="form.upperLimitFlag" style="width: 160px" size="small">
            <a-select-option value="0">
              不限
            </a-select-option>
            <a-select-option value="1">
              限制
            </a-select-option>
          </a-select>
          <a-input-number
            v-show="form.upperLimitFlag&&form.upperLimitFlag=='1'"
            size="small"
            style="margin-left:10px;width:300px;"
            v-model="form.upperLimitAmount"
            :min="0"
            :step="1"
            :max="999999"
            :precision="2"
            placeholder="请输入金额"/>
        </a-form-model-item>
      </a-form-model>
      <a-card size="small" :bordered="false" class="pages-wrap">
        <div class="flex">
          <a-radio-group v-model="chooseVal" button-style="solid" size="small">
            <a-radio-button value="a" v-show="form.gateFlag==='1'">
              门槛产品
            </a-radio-button>
            <a-radio-button value="d">
              特价产品
            </a-radio-button>
          </a-radio-group>
          <div>
            <a-button
              size="small"
              type="link"
              class="button-info"
              id="promotionList-edit-btn"
              @click="openGuideModal=true"
            >+导入产品</a-button>
            <a-button
              v-show="chooseVal==='d'"
              style="margin-left:10px;"
              size="small"
              type="link"
              class="button-error"
              id="promotionList-edit-btn"
              @click="addProducts">+新增产品</a-button>
          </div>
        </div>
        <div v-show="chooseVal=='a'"><tableType1 ref="cillProduct"></tableType1></div>
        <div v-show="chooseVal=='d'"><tableType3 ref="specialProduct"></tableType3></div>
      </a-card>
      <div class="btn-cont">
        <a-button id="promotionList-basicInfo-modal-back" @click="isShow = false">取消</a-button>
        <a-button style="margin-left: 15px;" type="primary" id="promotionList-modal-save" @click="handleSave">确定</a-button>
      </div>
    </a-spin>
    <!-- 选择产品 -->
    <chooseProductsModal
      type="dealership"
      ref="productBox"
      :openModal="openProductsModal"
      :chooseData="chooseProducts"
      @close="openProductsModal=false"
      @ok="handleProductsAdd" />
    <!-- 导入产品 -->
    <importGuideModal :goodFlag="chooseVal=='a'?'1':'0'" :openModal="openGuideModal" @close="closeGuideModel" @ok="hanldeOk" />
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { VSelect } from '@/components'
import tableType1 from './tableType1.vue'
import tableType3 from './tableType3.vue'
import { promotionSave, getRuleDetail, getNewScopeSn } from '@/api/promotion'
import chooseProductsModal from './chooseProductsModal.vue'
import ImportGuideModal from './importGuideModal.vue'
export default {
  name: 'PromotionListBasicInfoModal',
  mixins: [commonMixin],
  components: { VSelect, tableType1, tableType3, chooseProductsModal, ImportGuideModal },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    promotionSn: {
      type: [Number, String],
      default: ''
    },
    itemSn: {
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      isShow: this.openModal, //  是否打开弹框
      spinning: false,
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 17 }
      },
      form: {
        promotionRuleType: 'PROMO_PROD', // 特价产品
        description: '',
        gateFlag: '0', // 门槛
        gateType: undefined,
        gateAmount: undefined,
        quotaAmount: undefined,
        minOrderFlag: '0', // 起订金额
        minOrderAmount: undefined,
        upperLimitFlag: '0', // 活动经费上限
        upperLimitAmount: undefined
      },
      rules: {
        description: [ { required: true, message: '请输入规则简称', trigger: 'blur' } ],
        gateFlag: [ { required: true, message: '请选择规则门槛', trigger: 'change' } ],
        minOrderFlag: [{ required: true, message: '请选择订单起订金额', trigger: 'change' }],
        upperLimitFlag: [{ required: true, message: '请选择活动经费上限', trigger: 'change' }]
      },
      chooseVal: 'a',
      openProductsModal: false,
      chooseProducts: [],
      openGuideModal: false// 导入弹窗
    }
  },
  methods: {
    // 导入
    closeGuideModel () {
      this.openGuideModal = false
    },
    // 门槛产品
    handleChange (e) {
      if (e.target.value == '1') {
        this.chooseVal = 'a'
      } else {
        this.chooseVal = 'd'
        this.form.gateType = undefined
        this.form.gateAmount = undefined
        this.form.quotaAmount = undefined
      }
    },
    changeGateTypeFlag (val) {
      this.form.gateType = val
      this.form.gateAmount = undefined
      this.form.quotaAmount = undefined
    },
    //  保存
    handleSave () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 验证必填
          if (_this.form.gateFlag == '1') {
            if (!_this.form.gateType) {
              _this.$message.warning('请选择规则门槛设置类型！')
              return
            }
            if (!_this.form.gateAmount) {
              _this.$message.warning('规则门槛条件不能为空！')
              return
            }
            if (_this.form.gateType === 'FIXED_AMOUNT' && !_this.form.quotaAmount) {
              _this.$message.warning('规则门槛条件不能为空！')
              return
            }
          }
          if (_this.form.minOrderFlag == 1 && !_this.form.minOrderAmount) {
            _this.$message.warning('请输入订单起订限制金额数！')
            return
          }
          if (_this.form.upperLimitFlag == 1 && !_this.form.upperLimitAmount) {
            _this.$message.warning('请输入活动经费上限金额！')
            return
          }

          const form = JSON.parse(JSON.stringify(_this.form))
          if (form.gateFlag == '1') {
            form.gateProductList = _this.$refs.cillProduct.getResultVal()
            form.gateAmount = form.gateType === 'RATIO_AMOUNT' ? form.gateAmount / 100 : form.gateAmount
            if (form.gateProductList.length == 0) {
              _this.$message.warning('请添加门槛产品！')
              return
            } else {
              const qtyFlag = form.gateProductList.some(newCon => { return (!newCon.unitType || !newCon.unitQty) })
              if (qtyFlag) {
                _this.$message.warning('订单起订量设置不能为空！')
                return
              }
              const rowFlag = _this.isJudge(form.gateProductList)
              if (rowFlag) {
                _this.$message.warning('请选择产品分类、品牌或产品！')
                return
              }
            }
          } else {
            form.gateProductList = []
            form.gateAmount = ''
            form.quotaAmount = ''
            form.gateType = undefined
          }
          form.specialProductList = _this.$refs.specialProduct.getResultVal()
          if (form.specialProductList.length == 0) {
            _this.$message.warning('请添加特价产品！')
            return
          } else {
            // 为空判断
            const isTypeEmpty = form.specialProductList.some(item => (item.productTypeList && item.productTypeList.length == 0) && (item.productBrandList && item.productBrandList.length == 0))
            if (isTypeEmpty) {
              _this.$message.warning('产品分类或品牌不能为空！')
              return
            }
            const isNumEmpty = form.specialProductList.some(item => (!item.unitType || !item.unitQty))
            if (isNumEmpty) {
              _this.$message.warning('订单起订量设置不能为空！')
              return
            }
            const isCountEmpty = _this.isNumEmpty(form.specialProductList)
            const isMoneyEmpty = _this.isNumEmpty(form.specialProductList)
            if (isCountEmpty.flag) {
              _this.$message.warning('折扣不能为空！')
              return
            }
            if (isCountEmpty.flag1) {
              _this.$message.warning('折扣金额不能为空！')
              return
            }
          }
          form.promotionSn = _this.promotionSn
          _this.spinning = true
          promotionSave(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(() => {
                _this.isShow = false
                _this.$emit('ok')
                _this.spinning = false
              }, 1000)
            } else {
              _this.spinning = false
            }
          })
        } else {
          return false
        }
      })
    },
    isNumEmpty (dataList) {
      const arr = []
      const arr1 = []
      dataList.forEach(item => {
        if (item.dataSourceOrigin === '0') { // 判断分类品牌
          if (!item.provinceDiscountRate || !item.cityDiscountRate || !item.specialDiscountRate) {
            arr.push(item.productScopeSn)
          }
        } else {
          if (!item.cityDiscountPrice || !item.provinceDiscountPrice || !item.specialDiscountPrice) {
            arr1.push(item.productScopeSn)
          }
        }
      })
      return { flag: arr.length > 0, flag1: arr1.length > 0 }
    },
    // 判断门槛产品中品牌，分类，产品其中一个必填
    isJudge (list) {
      const flag = list.some(con => {
        if (con.productThisList) {
          if (con.productThisList.length > 0) {
            return false
          } else {
            if ((con.productTypeList && con.productTypeList.length > 0) || (con.productBrandList && con.productBrandList.length > 0)) {
              return false
            } else {
              return true
            }
          }
        } else {
          if ((con.productTypeList && con.productTypeList.length > 0) || (con.productBrandList && con.productBrandList.length > 0)) {
            return false
          } else {
            return true
          }
        }
      })
      return flag
    },
    // 重置表格
    resetSearchForm () {
      this.form = {
        promotionRuleType: 'PROMO_PROD', // 特价产品
        description: '',
        gateFlag: '0', // 门槛
        gateType: undefined,
        gateAmount: undefined,
        quotaAmount: undefined,
        minOrderFlag: '1', // 起订金额
        minOrderAmount: undefined,
        upperLimitFlag: '1', // 活动经费上限
        upperLimitAmount: undefined,
        gateProductList: undefined,
        specialProductList: undefined
      }
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields()
        this.$refs.cillProduct.reSetTableData()
        this.$refs.specialProduct.reSetTableData()
      })
    },
    // 获取编辑详情
    getDetail () {
      const _this = this
      getRuleDetail({ sn: this.itemSn }).then(res => {
        if (res.status == 200) {
          this.chooseVal = res.data.gateFlag == '0' ? 'd' : 'a'
          const resultObj = res.data
          if (resultObj.gateFlag === '1') {
            resultObj.gateAmount = resultObj.gateType === 'RATIO_AMOUNT' ? resultObj.gateAmount * 100 : resultObj.gateAmount
          }
          // 重新组成保存数据
          if (resultObj.gateProductList && resultObj.gateProductList.length > 0) {
            resultObj.gateProductList = _this.newData(resultObj.gateProductList)
            this.$refs.cillProduct.setTabVal(resultObj.gateProductList)
          }
          if (resultObj.specialProductList && resultObj.specialProductList.length > 0) {
            resultObj.specialProductList = _this.newData(resultObj.specialProductList)
            this.$refs.specialProduct.setSourceData(resultObj.specialProductList)
          }
          this.form = { ...this.form, ...resultObj }
        }
      })
    },
    newData (list) {
      list.forEach(con => {
        // 品牌
        if (con.productBrandList) {
          const brandList = []
          con.productBrandList.forEach(item => {
            item.brandName = item.productBrandName
            const brandObj = {
              productBrandSn: item.productBrandSn
            }
            brandList.push(brandObj)
          })
          con.productBrandArr = con.productBrandList
          con.productBrandList = brandList
        }
        // 分类
        if (con.productTypeList) {
          const typeList = []
          con.productTypeList.forEach(item => {
            const typeObj = {}
            item.title = ''
            const num = 3
            for (var i = 0; i < num; i++) {
              if (item['productTypeName' + (i + 1)]) {
                // item.title += item['productTypeName' + (i + 1)] + (item['productTypeName' + (i + 1)] ? '/' : '')
                typeObj['productTypeSn' + (i + 1)] = item['productTypeSn' + (i + 1)] ? item['productTypeSn' + (i + 1)] : ''
              }
            }
            // item.title = item.title.slice(0, item.title.length - 1)
            if (item.productTypeName3) {
              item.title = item.productTypeName2 + '/' + item.productTypeName3
            } else if (!item.productTypeName3 && item.productTypeName2) {
              item.title = item.productTypeName2
            } else {
              item.title = item.productTypeName1
            }
            item.id = item.productTypeSn3 ? item.productTypeSn3 : item.productTypeSn2 ? item.productTypeSn2 : item.productTypeSn1
            typeList.push(typeObj)
          })
          con.productTypeArr = con.productTypeList
          con.productTypeList = typeList
        }
        // 产品
        if (con.productThisList) {
          const productList = []
          con.productThisList.forEach(item => {
            const productObj = {
              productCode: item.productCode,
              productSn: item.productSn
            }
            productList.push(productObj)
          })
          con.productThisList = productList
        }
      })
      return list
    },
    // 导入
    hanldeOk (arr) {
      // 门槛产品导入
      const resultArr = []
      if (this.chooseVal == 'a') {
        arr.forEach(item => {
          const obj = {
            productCode: item.productCode,
            productSn: item.product.productSn
          }
          resultArr.push(obj)
        })
        const name = this.chooseVal == 'a' ? 'cill' : this.chooseVal == 'b' ? 'normalPrice' : 'offer'
        this.$refs[name + 'Product'].importRow(resultArr)
      } else {
        // 特价产品导入
        const dataList = this.setShowData('This')
        arr.forEach(item => {
          item = { ...item, ...item.product }
          item.code = item.productCode
          if (item.provincePrice) {
            item.provinceDiscountRate = Math.floor(((item.provinceDiscountPriceText / item.provincePrice) * 100).toFixed(2))
          }
          if (item.cityPrice) {
            item.cityDiscountRate = Math.floor(((item.cityDiscountPriceText / item.cityPrice) * 100).toFixed(2))
          }
          if (item.specialPrice) {
            item.specialDiscountRate = Math.floor(((item.specialDiscountPriceText / item.specialPrice) * 100).toFixed(2))
          }
          const flag = dataList.includes(item.productSn)
          if (!flag) {
            resultArr.push(item)
          }
        })
        if (resultArr.length > 0) {
          this.handleProductsOk(resultArr)
        } else {
          this.$message.warning('请勿添加重复数据！')
        }
      }
    },
    // 打开新增产品弹窗（禁用已选）
    addProducts () {
      this.chooseProducts = []
      this.openProductsModal = true
      const dataList = this.setShowData('This')
      this.$refs.productBox.handleDisabled(dataList)
    },
    // 获取回显禁用数据
    setShowData (name) {
      const _this = this
      const snArr = []
      const valList = _this.$refs.specialProduct.getResultVal()
      valList.forEach(item => {
        if (item['product' + name + 'List'] && item['product' + name + 'List'].length > 0) {
          item['product' + name + 'List'].forEach(con => {
            const newName = name === 'This' ? '' : name
            snArr.push(con['product' + newName + 'Sn'])
          })
        }
      })
      return snArr
    },
    handleProductsAdd (con) {
      debugger
      const newArr = []
      con.forEach(newCon => {
        if (!newCon.provincePrice || !newCon.cityPrice || !newCon.specialPrice) {
          newArr.push(newCon.code)
        }
      })
      con.map((list, pos) => {
        if (!list.provincePrice || !list.cityPrice || !list.specialPrice) {
          con.splice(pos, 1)
        }
      })
      const _this = this
      if (newArr && newArr.length > 0) {
        _this.$info({
          title: '提示',
          content: newArr.toString() + '（产品编码），没有定价，不可添加',
          closable: true,
          centered: true,
          onOk () {
            _this.handleProductsOk(con)
          }
        })
      } else {
        _this.handleProductsOk(con)
      }
    },
    // +新增产品
    handleProductsOk (con) {
      const _this = this
      con.forEach(async (item) => {
        const chooseProductsList = []
        const getSn = await getNewScopeSn({})
        if (getSn.status == 200) {
          const newData = {
            productScopeSn: getSn.data,
            dataSourceOrigin: '1',
            productTypeArr: [],
            productTypeList: [],
            productBrandArr: [{ productBrandSn: item.productBrandSn, brandName: item.productBrandName }],
            productBrandList: [{ productBrandSn: item.productBrandSn }],
            productThisList: [{
              productSn: item.productSn,
              productCode: item.code
            }],
            provincePrice: item.provincePrice,
            cityPrice: item.cityPrice,
            specialPrice: item.specialPrice,
            provinceDiscountPrice: item.provinceDiscountPriceText,
            cityDiscountPrice: item.cityDiscountPriceText,
            specialDiscountPrice: item.specialDiscountPriceText,
            unitType: 'SL',
            unitQty: 1,
            provinceDiscountRate: item.provinceDiscountRate ? item.provinceDiscountRate : undefined,
            cityDiscountRate: item.cityDiscountRate ? item.cityDiscountRate : undefined,
            specialDiscountRate: item.specialDiscountRate ? item.specialDiscountRate : undefined
          }
          const obj = {}
          if (item.productTypeSn1) {
            obj.productTypeSn1 = item.productTypeSn1
          }
          if (item.productTypeSn2) {
            obj.productTypeSn2 = item.productTypeSn2
          }
          if (item.productTypeSn3) {
            obj.productTypeSn3 = item.productTypeSn3
          }
          const newObj = { ...obj, ...{} }
          if (Object.keys(obj).length == 1) {
            newObj.title = item.productTypeName1
            newObj.id = item.productTypeSn1
          } else if (Object.keys(obj).length == 2) {
            newObj.title = item.productTypeName2
            newObj.id = item.productTypeSn2
          } else {
            newObj.title = item.productTypeName2 + '/' + item.productTypeName3
            newObj.id = item.productTypeSn3
          }
          newData.productTypeList[0] = obj
          newData.productTypeArr[0] = newObj
          chooseProductsList.push(newData)
        }
        _this.$refs.specialProduct.setSourceData(chooseProductsList)
      })
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.resetSearchForm()
      } else {
        if (this.itemSn) {
          this.getDetail()
        } else {
          this.chooseVal = this.form.gateFlag == '0' ? 'd' : 'a'
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .promotionList-basicInfo-modal{
    /deep/.ant-modal-body {
      padding: 40px 40px 24px;
      max-height: 745px !important;
      overflow-y: scroll !important;
    }
    .ant-radio-button-wrapper{
      width:80px;
      text-align: center;
    }
    .ant-form-item{
      margin-bottom:5px;
    }
    .buyerBox{
      border:1px solid #d9d9d9;margin-top:10px;border-radius:4px;padding:4px 10px;background:#f2f2f2;max-height:130px;overflow-y:scroll;
    }
    .btn-cont {
      text-align: center;
      margin: 35px 0 10px;
    }
    .flex{
      display:flex;
      align-items:center;
      justify-content:space-between;
    }
  }

</style>
