<template>
  <a-modal
    class="CouponModal"
    :title="pageType == 'add' ? '新增' : pageType == 'edit' ? '编辑' : ''"
    :width="1030"
    :footer="null"
    :destroyOnClose="true"
    @cancel="isShow = false"
    v-model="isShow">
    <!-- 表单 -->
    <a-form-model ref="ruleForms" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-row>
        <a-col :span="24">
          <div class="c-title">
            基本信息
            <a-divider type="vertical" class="bold-divider" />
          </div>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="优惠券名称" prop="title"><a-input v-model="form.title" :maxLength="20" placeholder="请输入优惠券名称,20个字以内" /></a-form-model-item>
        </a-col>
        <a-col :span="12">
          <!-- 优惠券类型分为：FULLSUB 满减券、DISCOUNT 折扣券、VOUCHER 代金券和 SUB 实价券 -->
          <a-form-model-item label="优惠券类型" prop="couponType">
            <v-select
              ref="couponType"
              v-model="form.couponType"
              @change="selectChange('couponType')"
              showArrow
              placeholder="请选择优惠券类型"
              code="COUPON_TYPE"
              :disabled="takeCount > 0"></v-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12" v-if="form.couponType == 'VOUCHER'">
          <a-form-model-item label="优惠券面额" prop="subAmount">
            <a-input-number
              v-model="form.subAmount"
              :disabled="takeCount > 0"
              :min="1"
              :max="999999"
              placeholder="请输入优惠券面额"
              class="input-number-s" />
            <span class="unit">元</span>
          </a-form-model-item>
        </a-col>
        <a-col :span="12" v-if="form.couponType == 'VOUCHER'">
          <a-form-model-item label="是否限额使用" class="default-form-item form-item-required">
            <a-row :gutter="20">
              <a-col :span="9">
                <a-form-model-item prop="isLimit">
                  <v-select
                    ref="flag"
                    v-model="isLimit"
                    @change="selectChange('isLimitE')"
                    showArrow
                    placeholder="请选择"
                    code="FLAG"
                    :disabled="takeCount > 0"></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="15" v-if="isLimit == '1'">
                <a-form-model-item prop="limitAmount">
                  满<a-input-number
                    v-model="form.limitAmount"
                    :disabled="takeCount > 0"
                    :min="1"
                    :max="999999"
                    placeholder="限额数值"
                    class="input-number-ms" />元使用
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12" v-if="form.couponType == 'FULLSUB'">
          <a-form-model-item label="满" class="default-form-item form-item-required">
            <a-row>
              <a-col :span="12">
                <a-form-model-item prop="limitAmount">
                  <a-input-number
                    v-model="form.limitAmount"
                    :disabled="takeCount > 0"
                    :min="1"
                    :max="999999"
                    placeholder="限额数值"
                    class="input-number-ls" />
                  <span class="unit">减</span>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item prop="subAmount">
                  <a-input-number
                    v-model="form.subAmount"
                    :disabled="takeCount > 0"
                    :min="1"
                    :max="999999"
                    placeholder="减免金额"
                    class="input-number-ls" />
                  <span class="unit">元</span>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="发放总量" class="default-form-item form-item-required">
            <a-row :gutter="20">
              <a-col :span="9">
                <a-form-model-item label="" prop="quotaLimit">
                  <v-select
                    ref="limitFlag"
                    v-model="form.quotaLimit"
                    :disabled="takeCount > 0"
                    @change="selectChange('quotaLimit')"
                    showArrow
                    placeholder="请选择"
                    code="LIMIT_FLAG"></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="15" v-if="form.quotaLimit == '1'">
                <a-form-model-item label="" prop="quota">
                  <a-input-number
                    v-model="form.quota"
                    :disabled="takeCount > 0"
                    :min="1"
                    :max="999999"
                    placeholder="请输入限制发放总量"
                    class="input-number-s" />
                  <span class="unit">份</span>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="优惠券说明" prop="ruleDesc">
            <a-textarea v-model="form.ruleDesc" :maxLength="256" :auto-size="{ minRows: 3, maxRows: 5 }" placeholder="请输入优惠券说明,256个字以内" />
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <div class="c-title">
            领用规则
            <a-divider type="vertical" class="bold-divider" />
          </div>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="持卡会员" class="default-form-item form-item-required">
            <a-row :gutter="20">
              <a-col :span="9">
                <a-form-model-item prop="cardholderCouponLimit.isLimit">
                  <v-select
                    ref="limitFlag"
                    v-model="form.cardholderCouponLimit.isLimit"
                    @change="selectChange('isLimitC')"
                    showArrow
                    placeholder="请选择"
                    code="LIMIT_FLAG"></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="15" v-if="form.cardholderCouponLimit.isLimit == '1'">
                <a-row>
                  <a-col :span="11">
                    <a-form-model-item prop="cardholderCouponLimit.limitCount">
                      <a-input-number v-model="form.cardholderCouponLimit.limitCount" :min="1" :max="999999" placeholder="限领份数" class="input-number-s" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="4">份/每</a-col>
                  <a-col :span="9">
                    <a-form-model-item prop="cardholderCouponLimit.limitCondition">
                      <a-select v-model="form.cardholderCouponLimit.limitCondition" placeholder="请选择">
                        <a-select-option :value="item.code" v-for="(item, index) in isUnitList" :key="index">{{ item.dispName }}</a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="未持卡会员" class="default-form-item form-item-required">
            <a-row :gutter="20">
              <a-col :span="9">
                <a-form-model-item prop="normalCouponLimit.isLimit">
                  <v-select
                    ref="limitFlag"
                    v-model="form.normalCouponLimit.isLimit"
                    @change="selectChange('isLimitN')"
                    showArrow
                    placeholder="请选择"
                    code="LIMIT_FLAG"></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="15" v-if="form.normalCouponLimit.isLimit == '1'">
                <a-row>
                  <a-col :span="11">
                    <a-form-model-item prop="normalCouponLimit.limitCount">
                      <a-input-number v-model="form.normalCouponLimit.limitCount" :min="1" :max="999999" placeholder="限领份数" class="input-number-s" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="4">份/每</a-col>
                  <a-col :span="9">
                    <a-form-model-item prop="normalCouponLimit.limitCondition">
                      <a-select v-model="form.normalCouponLimit.limitCondition" placeholder="请选择">
                        <a-select-option :value="item.code" v-for="(item, index) in isUnitList" :key="index">{{ item.dispName }}</a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="有效期" class="default-form-item form-item-required">
            <a-row :gutter="20">
              <a-col :span="9">
                <a-form-model-item prop="validType">
                  <a-select v-model="form.validType" :disabled="takeCount > 0" @change="selectChange('validType')" placeholder="请选择">
                    <a-select-option :value="item.code" v-for="(item, index) in couponValidityList" :key="index">{{ item.dispName }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="15" v-if="form.validType == 'ABSOLUTE'">
                <a-form-model-item prop="timeRange">
                  <a-range-picker v-model="form.timeRange" :disabled="takeCount > 0" @change="validDateChange" :disabled-date="disabledDate" format="YYYY-MM-DD" />
                </a-form-model-item>
              </a-col>
              <a-col :span="15" v-if="form.validType == 'RELATIVE'">
                <a-row>
                  <a-col :span="16">
                    <a-form-model-item prop="validDate">
                      <a-input-number
                        v-model="form.validDate"
                        :disabled="takeCount > 0"
                        :min="1"
                        :max="999999"
                        placeholder="请输入"
                        class="input-number-s" />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">天内有效</a-col>
                </a-row>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="适用洗车类型" prop="couponScopeList">
            <a-select v-model="form.couponScopeList" placeholder="请选择适用洗车类型" showArrow mode="multiple">
              <a-select-option v-for="item in itemQueryList" :key="item.id" :value="item.id">{{ item.itemName }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item class="default-form-item form-item-required">
            <div slot="label" class="form-item-label">
              <a-tooltip
                placement="right"
                arrow-point-at-center
                title="已设置的适用洗车网点再次修改（尤其是减少使用网点）后，在【优惠券统计】中会保留原适用洗车网点的统计数据。"
              >
                适用洗车网点
                <a-icon :style="{ fontSize: '17px', color: '#1890ff', verticalAlign: 'sub' }" type="question-circle" />
              </a-tooltip>
            </div>
            <a-row :gutter="20">
              <a-col :span="9">
                <a-form-model-item prop="isStoreLimit">
                  <a-select v-model="form.isStoreLimit" @change="selectChange('isStoreLimit')" placeholder="请选择">
                    <a-select-option :value="item.code" v-for="(item, index) in isAllList" :key="index">{{ item.dispName }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="15" v-if="form.isStoreLimit == '1'">
                <a-form-model-item prop="couponStoreList">
                  <a-row :gutter="20">
                    <a-col :span="15">
                      已选
                      <strong>{{ form.couponStoreList.length }}</strong>
                      个
                    </a-col>
                    <a-col :span="9"><a-button type="primary" size="small" class="small-btn" @click="openOutletsModal = true">选择</a-button></a-col>
                  </a-row>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }" class="btn-cont">
            <a-button type="primary" @click="onSubmit">保存</a-button>
            <a-button class="resetForm" @click="onCancel">取消</a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>

    <!-- 选择网点 -->
    <choose-outlets :openOutletsModal="openOutletsModal" :storeList="form.couponStoreList" @close="closeChooseOutlets" />
  </a-modal>
</template>

<script>
import { VSelect } from '@/components'
import moment from 'moment'
import ChooseOutlets from './ChooseOutlets.vue'
import { itemQuery } from '@/api/car-wash'
import { couponCreate, couponToUpdate, couponUpdate } from '@/api/coupons'
export default {
  name: 'AddCouponModal',
  components: { VSelect, ChooseOutlets },
  props: {
    openModal: {
      //  弹框是否展示
      type: Boolean,
      default: false
    },
    pageType: {
      //  页面类型  add 新增 / edit 编辑
      type: String,
      default: ''
    },
    couponId: { //  优惠券id
      type: String,
      default: ''
    }
  },
  data () {
    return {
      isShow: this.openModal, //  弹框是否展示
      form: {
        title: '', //  优惠券名称
        quotaLimit: '0', //  是否限制发放数量（0否 1是）
        quota: '', //  发放数量
        couponType: 'VOUCHER', //  优惠券类型：FULLSUB满减/SUB立减/DISCOUNT折扣券/VOUCHER代金券/PROMOCODE优惠码
        limitAmount: '', //  限定金额
        subAmount: '', //  满减券 减免 / 代金券面额
        ruleDesc: '', //  规则说明
        normalCouponLimit: { //  非持卡会员
          isLimit: '0', //  是否限制0否1是
          limitCount: '', //  限制数量
          limitCondition: 'monthly', //  限制条件:none无条件;monthly每月;daily每日
          userType: 'normal' //  用户类型:normal普通用户;cardholder持卡用户;all所有用户
        },
        cardholderCouponLimit: { //  持卡会员
          isLimit: '0', //  是否限制0否1是
          limitCount: '', //  限制数量
          limitCondition: 'monthly', //  限制条件:none无条件;monthly每月;daily每日
          userType: 'cardholder' //  用户类型:normal普通用户;cardholder持卡用户;all所有用户
        },
        validType: 'NONE', //  有效期类型：ABSOLUTE绝对时效(时间区间)/RELATIVE相对时效(领取后多少天内有效)/NONE不限制
        timeRange: [], //  有效期  时间范围(为解决表单校验)
        startTime: '', //  开始时间
        endTime: '', //  结束时间
        validDate: '', //  有效时长
        isOverlay: '0', //  是否可叠加使用(0否，1是)
        scopeType: 'ITEM', //  适用范围类型：ITEM 部分服务/ITEM_ALL 全部服务/BUNDLE 部分套餐/BUNDLE_ALL 全部套餐
        couponScopeList: [], //  优惠券适用范围设置
        isStoreLimit: '0', //  是否有门店限制  (0否，1是)
        couponStoreList: [] //  优惠券使用范围设置
      },
      rules: {
        title: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
        quota: [{ required: true, message: '请输入限制发放总量', trigger: 'blur' }],
        couponType: [{ required: true, message: '请选择优惠券类型', trigger: 'blur' }],
        limitAmount: [{ required: true, message: '请输入限额数值', trigger: 'blur' }],
        subAmount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
        'normalCouponLimit.limitCount': [{ required: true, message: '请输入限领份数', trigger: 'blur' }],
        'cardholderCouponLimit.limitCount': [{ required: true, message: '请输入限领份数', trigger: 'blur' }],
        timeRange: [{ required: true, message: '请选择日期范围', trigger: 'blur' }],
        validDate: [{ required: true, message: '请输入有效时长', trigger: 'blur' }],
        couponScopeList: [{ required: true, message: '请选择适用洗车类型', trigger: 'blur' }],
        couponStoreList: [{ required: true, message: '请选择适用洗车网点', trigger: 'blur' }]
      },
      isLimit: '0', //  代金券  是否限额使用(0否，1是)
      isUnitList: [
        //  限领份数单位  下拉数据列表
        { dispName: '自然月', code: 'monthly' }
      ],
      couponValidityList: [
        //  有效期  下拉数据列表
        { dispName: '不限', code: 'NONE' },
        { dispName: '固定日期', code: 'ABSOLUTE' },
        { dispName: '领取后', code: 'RELATIVE' }
      ],
      isAllList: [
        //  适用洗车网点  全部 部分 下拉数据列表
        { dispName: '全部', code: '0' },
        { dispName: '部分', code: '1' }
      ],
      itemQueryList: [], //  适用洗车类型
      openOutletsModal: false, //  选择网点  弹框展示状态
      takeCount: '' //  发放数量（指客户已领取但未使用的数量）  usedCount（指客户已领取并已使用的数量）
    }
  },
  methods: {
    moment,
    range (start, end) {
      const result = []
      for (let i = start; i < end; i++) {
        result.push(i)
      }
      return result
    },
    //  有效期  固定日期  禁用范围
    disabledDate (current) {
      // 不能选择今天之前的日期
      return current && current < moment().subtract(1, 'days')
    },
    //  有效期  固定日期  change
    validDateChange (date, dateString) {
      this.form.startTime = dateString[0]
      this.form.endTime = dateString[1]
    },
    //  保存
    onSubmit () {
      this.$refs.ruleForms.validate(valid => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(this.form))
          delete formData.timeRange
          // 适用洗车类型
          const couponScopeArr = []
          formData.couponScopeList.map(item => { couponScopeArr.push({ scopeType: 'ITEM', scopeValue: item }) })
          formData.couponScopeList = couponScopeArr
          if (this.pageType == 'add') { //  新增
            formData.id = null
            this.couponCreate(formData)
          } else if (this.pageType == 'edit') { //  编辑
            formData.id = String(this.couponId)
            this.couponUpdate(formData)
          }
        } else {
          return false
        }
      })
    },
    // 创建优惠券
    couponCreate (formData) {
      couponCreate(formData).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$emit('success')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 编辑优惠券
    couponUpdate (formData) {
      couponUpdate(formData).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$emit('success')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 取消
    onCancel () {
      this.resetForm()
      this.isShow = false
    },
    //  选择网点
    closeChooseOutlets (val) {
      this.form.couponStoreList = []
      if (val) {
        val.map(item => {
          this.form.couponStoreList.push({ storeId: item })
        })
      }
      this.openOutletsModal = false
    },
    // 获取优惠券详情
    getCouponInfo (id) {
      couponToUpdate({ id: id }).then(res => {
        if (res.status == 200) {
          this.setVal(res.data)
          this.takeCount = res.data.takeCount //  发放数量
        }
      })
    },
    // 表单赋值
    setVal (data) {
      const arr = [ 'title', 'couponType', 'quotaLimit', 'quota', 'ruleDesc', 'validType', 'isStoreLimit' ]
      arr.map(k => { this.form[k] = data[k] })
      if (data.couponType === 'FULLSUB') { //  满减券
        this.form.limitAmount = data.limitAmount
        this.form.subAmount = data.subAmount
      } else if (data.couponType === 'VOUCHER') { //  代金券
        this.form.subAmount = data.subAmount
        this.isLimit = Number(data.limitAmount) > 0 ? '1' : '0'
        this.form.limitAmount = data.limitAmount
      }
      // 持卡与非持卡会员
      this.form.cardholderCouponLimit = { isLimit: data.cardholderCouponLimit.isLimit, limitCount: data.cardholderCouponLimit.limitCount, limitCondition: data.cardholderCouponLimit.limitCondition, userType: data.cardholderCouponLimit.userType }
      this.form.normalCouponLimit = { isLimit: data.normalCouponLimit.isLimit, limitCount: data.normalCouponLimit.limitCount, limitCondition: data.normalCouponLimit.limitCondition, userType: data.normalCouponLimit.userType }
      if (data.validType === 'ABSOLUTE') { //  绝对时效(时间区间)
        this.form.timeRange = [moment(data.startTimeGmt8Ymd, 'YYYY-MM-DD'), moment(data.endTimeGmt8Ymd, 'YYYY-MM-DD')]
        this.form.startTime = data.startTimeGmt8Ymd
        this.form.endTime = data.endTimeGmt8Ymd
      } else if (data.validType === 'RELATIVE') { //  RELATIVE相对时效(领取后多少天内有效)
        this.form.validDate = data.validDate
      }
      this.form.couponScopeList = data.scopeValueList //  适用洗车类型
      this.form.couponStoreList = data.couponStoreList //  适用洗车网点
    },
    // 获取适用洗车类型列表
    getItemQuery () {
      itemQuery({
        pageNo: 1,
        pageSize: 1000
      }).then(res => {
        if (res.status == 200) {
          this.itemQueryList = res.data.list || []
        } else {
          this.itemQueryList = []
        }
      })
    },
    //  select  change 关联数据清空处理
    selectChange (type) {
      if (type == 'couponType') { //  优惠券类型
        this.form.subAmount = ''
        this.form.limitAmount = ''
        this.isLimit = '0' //  代金券  是否限额使用(0否，1是)
      } else if (type === 'isLimitE') { //  是否限额使用
        this.form.limitAmount = ''
      } else if (type === 'quotaLimit') { //  发放总量
        this.form.quota = ''
      } else if (type === 'isLimitC') { //  持卡会员  是否限领
        this.form.cardholderCouponLimit.limitCount = ''
      } else if (type === 'isLimitN') { //  非持卡会员  是否限领
        this.form.normalCouponLimit.limitCount = ''
      } else if (type === 'validType') { //  有效期
        this.form.timeRange = []
        this.form.startTime = ''
        this.form.endTime = ''
        this.form.validDate = ''
      } else if (type === 'isStoreLimit') { //  适用洗车网点
        this.form.couponStoreList = []
      }
    },
    // 重置表单数据
    resetForm () {
      const emptyArr = [ 'title', 'quota', 'limitAmount', 'subAmount', 'ruleDesc', 'startTime', 'endTime', 'validDate' ]
      const zeroArr = [ 'quotaLimit', 'isOverlay', 'isStoreLimit' ]
      const array = [ 'timeRange', 'couponScopeList', 'couponStoreList' ]
      emptyArr.map(item => { this.form[item] = '' })
      zeroArr.map(item => { this.form[item] = '0' })
      array.map(item => { this.form[item] = [] })
      this.form.couponType = 'VOUCHER'
      this.form.cardholderCouponLimit = { isLimit: '0', limitCount: '', limitCondition: 'monthly', userType: 'cardholder' }
      this.form.normalCouponLimit = { isLimit: '0', limitCount: '', limitCondition: 'monthly', userType: 'normal' }
      this.form.validType = 'NONE'
      this.form.scopeType = 'ITEM'
      this.isLimit = '0'
      this.takeCount = ''
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (val) {
      if (!val) {
        this.$emit('close')
      } else {
        this.resetForm() //  重置表单数据
        this.getItemQuery() //  获取适用洗车类型列表
      }
    },
    couponId (newValue, oldValue) {
      if (newValue && this.isShow) {
        this.getCouponInfo(newValue)
      }
    }
  }
}
</script>

<style lang="less">
.CouponModal {
  .c-title {
    padding: 0 0 10px;
    margin-bottom: 20px;
    border-bottom: 1px solid #e8e8e8;
    .bold-divider {
      width: 3px;
      background-color: #1890ff;
    }
  }
  .input-number-s {
    width: 90%;
  }
  .input-number-ms{
    width: 66%;
    margin: 0 5px;
  }
  .input-number-ls{
    width: 80%;
    margin-right: 8px;
  }
  .input-number-mj{
    width: 40%;
  }
  .unit {
    display: inline-block;
    width: 10%;
    text-align: center;
  }
  .btn-cont {
    text-align: center;
    .resetForm {
      margin-left: 10px;
    }
  }
  .default-form-item {
    margin-bottom: 0;
  }
  .form-item-label {
  	display: inline-block;
  	cursor: pointer;
  }
  .form-item-required {
    .ant-form-item-label {
      label:before {
        display: inline-block;
        margin-right: 4px;
        color: #f5222d;
        font-size: 14px;
        font-family: SimSun, sans-serif;
        line-height: 1;
        content: '*';
      }
    }
  }
}
</style>
