<template>
  <div>
    <!-- 奖品类型 -->
    <v-select
      ref="jpType"
      code="LUCKY_DRAW_PRIZE_TYPE"
      v-show="false"
    >
    </v-select>
    <!-- 中奖限制 -->
    <v-select
      ref="zjXzType"
      code="LUCKY_DRAW_WIN_LIMIT_RULE"
      v-show="false"
    >
    </v-select>
    <!-- 赠送规则 -->
    <v-select
      ref="zsGzType"
      code="LUCKY_DRAW_GIVE_TIMES_RULE"
      v-show="false"
    >
    </v-select>

    <a-modal
      v-model="isShow"
      @cancel="cansel"
      :footer="null"
      width="80%"
      :centered="true"
      wrapClassName="addLottery-modal"
      :title="titleText">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :layout="formLayout"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <h3 class="form-titles">基础设置</h3>
        <a-row :gutter="48">
          <a-col :span="6">
            <!-- participantsNum>0 有参与人数时不可编辑 -->
            <a-form-model-item ref="activeName" label="活动名称" prop="activeName">
              <a-input
                id="addLottery-time"
                :disabled="participantsNum>0||state==1"
                v-model="form.activeName"
                allowClear
                :maxLength="15"
                placeholder="15个字以内"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item ref="time" label="活动时间" prop="time">
              <a-range-picker
                :disabled="participantsNum>0||state==1"
                id="addLottery-time"
                v-model="form.time"
                :disabledDate="disabledDate"
                allowClear
                format="YYYY-MM-DD"
                :placeholder="['开始时间','结束时间']"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              ref="peopleLimitCount"
              label="抽奖人次"
              prop="peopleLimitCount"
              :rules="{
                required: !(state==1) && !form.isPeopleLimit,
                message: '请输入抽奖人次',
                trigger: ['blur','change'],
              }"
            >
              <a-input-number
                id="addLottery-cjRc"
                style="width: 50%;margin-right: 20px;"
                v-model="form.peopleLimitCount"
                :disabled="form.isPeopleLimit==1||state==1"
                :min="0"
                :max="999999"
                :precision="0"
                placeholder="请输入抽奖人次(0~999999)"
                allowClear />
              <a-checkbox :disabled="state==1" @change="bxCjRcChange" v-model="form.isPeopleLimit">
                不限
              </a-checkbox>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item ref="purchaseTimesGold" label="付费抽奖规则" prop="purchaseTimesGold">
              每次抽奖需要支付
              <a-input-number
                id="addLottery-cjgz"
                :disabled="state==1"
                style="width: 30%;margin-right: 5px;"
                v-model="form.purchaseTimesGold"
                :min="1"
                :max="999999"
                :precision="0"
                placeholder="请输入乐豆数(0~999999)"
                allowClear />
              乐豆
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="48">
          <a-col :span="8">
            <a-form-model-item ref="prizeDesc" label="奖品说明" prop="prizeDesc">
              <a-input
                :disabled="state==1"
                v-model="form.prizeDesc"
                allowClear
                :maxLength="100"
                placeholder="请输入奖品说明,100字以内"
                type="textarea" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item ref="activeLimitDesc" label="抽奖条件" prop="activeLimitDesc">
              <a-input
                :disabled="state==1"
                v-model="form.activeLimitDesc"
                allowClear
                :maxLength="100"
                placeholder="请输入抽奖条件,100字以内"
                type="textarea" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item ref="activeDesc" label="抽奖说明" prop="activeDesc">
              <a-input
                :disabled="state==1"
                v-model="form.activeDesc"
                allowClear
                :maxLength="100"
                placeholder="请输入抽奖说明,100字以内"
                type="textarea" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <h3 class="form-titles">奖品设置</h3>
        <div class="form-item">
          <a-form-model-item style="margin: 0;" ref="prizeClsNum" label="请选择转盘类型" prop="prizeClsNum">
            <a-select style="width: 300px;" :disabled="participantsNum>0||state==1" @change="zpTypeChange" v-model="form.prizeClsNum" placeholder="请选择转盘类型">
              <a-select-option :key="6" :value="6">
                六等分
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </div>
        <a-row
          type="flex"
          align="middle"
          :gutter="10"
        >
          <a-col span="1">
            序号
          </a-col>
          <a-col span="3">
            奖品类型
          </a-col>
          <a-col span="3">
            奖品描述
          </a-col>
          <a-col span="3">
            是否限制中奖
          </a-col>
          <a-col span="3">
            概率
          </a-col>
          <a-col span="3">
            数量
          </a-col>
          <a-col span="8">
            奖品图片
          </a-col>
        </a-row>
        <a-row
          type="flex"
          align="middle"
          v-for="(item, index) in form.luckyDrawPrizeList"
          :key="index"
          v-if="form.luckyDrawPrizeList.length"
          :gutter="10"
        >
          <a-col span="1">
            <a-form-model-item>
              <span class="red" v-if="state==0">*</span> 奖品{{ index+1 }}
            </a-form-model-item>
          </a-col>
          <a-col span="3">
            <a-form-model-item
              :label="''"
              :required="true"
              :label-col=" { span: 0 }"
              :wrapper-col=" { span: 24 }"
              :prop="'luckyDrawPrizeList.' + index + '.prizeType'"
              :rules="{
                required: true,
                message: '请选择奖品类型',
                trigger: ['blur','change'],
              }"
            >
              <a-select
                :disabled="participantsNum>0||state==1"
                :id="'jpList-prizeType'+index"
                style="width: 100%;"
                v-model="item.prizeType"
                @change="res => {
                  item.prizeDesc = ''
                  item.isPrizeLimit = item.prizeType == 'NONE' ? 1 : undefined
                }"
                placeholder="请选择奖品类型">
                <a-select-option
                  v-for="item in $refs.jpType.getOptionDatas()"
                  :key="item.code"
                  :value="item.code">{{ item.dispName }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col span="3">
            <a-form-model-item
              :label="''"
              :required="true"
              :label-col=" { span: 0 }"
              :wrapper-col=" { span: 24 }"
              :prop="'luckyDrawPrizeList.' + index + '.prizeDesc'"
              :rules="{
                required: true,
                message: '请输入奖品名称',
                trigger: ['blur','change'],
              }"
            >
              <a-input
                :disabled="participantsNum>0||state==1"
                v-if="item.prizeType !== 'GOLD'"
                :id="'jpList-name'+index"
                style="width: 100%;"
                v-model="item.prizeDesc"
                :maxLength="10"
                placeholder="请输入奖品名称,10个字以内"/>

              <a-input-number
                v-else
                :disabled="participantsNum>0||state==1"
                style="width: 100%;"
                :id="'jpList-name'+index"
                v-model="item.prizeDesc"
                :min="0"
                :max="999999"
                :precision="0"
                placeholder="请输入乐豆数量"
                allowClear />
            </a-form-model-item>
          </a-col>
          <a-col span="3">
            <a-form-model-item
              :label="''"
              :required="true"
              :label-col=" { span: 0 }"
              :wrapper-col=" { span: 24 }"
              :prop="'luckyDrawPrizeList.' + index + '.isPrizeLimit'"
              :rules="{
                required: true,
                message: '请选择是否限制中奖',
                trigger: ['blur','change'],
              }"
            >
              <a-select
                :id="'jpList-isPrizeLimit'+index"
                style="width: 100%;"
                :disabled="participantsNum>0||state==1||item.prizeType == 'NONE'"
                v-model="item.isPrizeLimit"
                @change="res => {
                  item.prizeRate = ''
                  item.prizeNum = ''
                }"
                placeholder="是否限制中奖">
                <a-select-option :key="0" :value="0">
                  是
                </a-select-option>
                <a-select-option :key="1" :value="1">
                  否
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col span="3" v-if="item.isPrizeLimit == 1">
            <a-form-model-item
              :label="''"
              :required="true"
              :label-col=" { span: 0 }"
              :wrapper-col=" { span: 24 }"
              :prop="'luckyDrawPrizeList.' + index + '.prizeRate'"
              :rules="{
                required: true,
                message: '请输入中奖概率',
                trigger: ['blur','change'],
              }"
            >
              <a-input-number
                style="width: 100%;"
                :disabled="participantsNum>0||state==1"
                :id="'jpList-prizeRate'+index"
                v-model="item.prizeRate"
                :min="0"
                :max="100"
                :precision="2"
                placeholder="请输入中奖概率(%)"
                allowClear />
            </a-form-model-item>
          </a-col>
          <a-col span="3" v-if="item.isPrizeLimit == 1&&item.prizeType!='NONE'">
            <a-form-model-item
              :label="''"
              :required="true"
              :label-col=" { span: 0 }"
              :wrapper-col=" { span: 24 }"
              :prop="'luckyDrawPrizeList.' + index + '.prizeNum'"
              :rules="{
                required: true,
                message: '请输入奖品数量',
                trigger: ['blur','change'],
              }"
            >
              <a-input-number
                style="width: 100%;"
                :disabled="participantsNum>0||state==1"
                :id="'jpList-prizeNum'+index"
                v-model="item.prizeNum"
                :min="1"
                :max="999999"
                :precision="0"
                placeholder="请输入奖品数量"
                allowClear />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item
              :label="''"
              :label-col=" { span: 0 }"
              :wrapper-col=" { span: 24 }"
              :prop="'luckyDrawPrizeList.' + index + '.prizeImage'"
            >
              <Upload
                :ref="'prizeImage'+index"
                :disabled="participantsNum>0||state==1"
                :id="'jpList-prizeImage'+index"
                v-model="item.prizeImage"
                :fileSize="0.25"
                listType="picture-card">
              </Upload>
              <span class="upload-desc">请上传奖品图片，300*300px，0.25MB 以内。</span>
            </a-form-model-item>
          </a-col>
        </a-row>
        <div v-if="form.luckyDrawPrizeList.length" style="height: 1px;background-color: #eee;margin-bottom: 20px;" ></div>
        <a-row :gutter="48" v-if="form.luckyDrawPrizeList.length">
          <a-col :span="12">
            <div class="form-item">
              <div style="margin-right: 10px;">中奖限制：</div>
              <a-select
                mode="multiple"
                :disabled="state==1"
                style="width: 80%;"
                @change="zjxzChange"
                v-model="form.zjXz"
                placeholder="请选择中奖限制">
                <a-select-option
                  v-for="item in zjXz"
                  :key="item.code"
                  :value="item.code">{{ item.dispName }}</a-select-option>
              </a-select>
            </div>
            <div class="form-item" v-for="(item,index) in form.luckyDrawWinPrizeLimitList" :key="index">
              <a-form-model-item
                style="margin: 0;"
                :label="''"
                :required="true"
                :label-col=" { span: 0 }"
                :wrapper-col=" { span: 24 }"
                :prop="'luckyDrawWinPrizeLimitList.' + index + '.limitTimes'"
                :rules="{
                  required: true,
                  message: '请输入次数',
                  trigger: ['blur','change'],
                }"
              >
                {{ index+1 }}.
                {{ item.winPrizeLimitCodeDictValue.split('XXX')[0] }}
                <a-input-number
                  :disabled="state==1"
                  style="width: 100px;"
                  :id="'luckyDrawWinPrizeLimitList-limitTimes'+index"
                  v-model="item.limitTimes"
                  :min="1"
                  :max="100"
                  :precision="0"
                  placeholder="请输入次数"
                  allowClear />
                {{ item.winPrizeLimitCodeDictValue.split('XXX')[1] }}
              </a-form-model-item>
            </div>
          </a-col>
          <a-col :span="12">
            <div class="form-item">
              <div style="margin-right: 10px;">赠送抽奖次数规则：</div>
              <a-select
                mode="multiple"
                :disabled="state==1"
                style="width: 70%;"
                @change="cjGzChange"
                v-model="form.cjGz"
                placeholder="请选择">
                <a-select-option
                  v-for="item in cjGz"
                  :key="item.code"
                  :value="item.code">{{ item.dispName }}</a-select-option>
              </a-select>
            </div>
            <div class="form-item" v-for="(item,index) in form.luckyDrawTaskList" :key="index">
              <a-form-model-item
                style="margin: 0;"
                :label="''"
                :required="true"
                :label-col=" { span: 0 }"
                :wrapper-col=" { span: 24 }"
                :prop="'luckyDrawTaskList.' + index + '.giveTimes'"
                :rules="{
                  required: true,
                  message: '请输入次数',
                  trigger: ['blur','change'],
                }"
              >
                {{ index+1 }}.
                {{ item.taskCodeDictValue }}, 赠送
                <a-input-number
                  :disabled="state==1"
                  style="width: 100px;"
                  :id="'luckyDrawTaskList-giveTimes'+index"
                  v-model="item.giveTimes"
                  :min="1"
                  :max="100"
                  :precision="0"
                  placeholder="请输入次数"
                  allowClear />
                次
              </a-form-model-item>
            </div>
          </a-col>
        </a-row>

        <div class="form-item" style="justify-content:center;padding: 50px 20px 20px;">
          <a-button type="primary" :loading="loading" @click="onSubmit" v-if="state==0">
            保存
          </a-button>
          <a-button style="margin-left: 10px;" @click="cansel">
            {{ state==1?'关闭':'取消' }}
          </a-button>
        </div>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { VSelect, Upload } from '@/components'
import { saveLuckyDrawConfig, getLuckyDrawDetail } from '@/api/luckyDraw.js'
import moment from 'moment'
export default {
  name: 'AddlotterySetModal',
  components: {
    VSelect,
    Upload
  },
  props: {
    showEditModal: {
      type: Boolean,
      default: false
    },
    itemId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      loading: false,
      isShow: this.showEditModal,
      titleText: '活动',
      formLayout: 'vertical',
      labelCol: {},
      wrapperCol: {},
	    state: 0, // 活动状态
      participantsNum: 0, // 抽奖参与人数
      form: {
        activeName: '', // 活动名称
        time: [],
        activeStartTime: '', // 活动开始时间
        activeEndTime: '', // 活动结束时间
        peopleLimitCount: '', // 活动人数限制
        isPeopleLimit: false, // 不限人数
        purchaseTimesGold: '', // 购买抽奖次数金币数
        prizeDesc: '', // 奖品说明
        activeLimitDesc: '', // 活动条件说明
        activeDesc: '', // 抽奖说明
        prizeClsNum: undefined, // 转盘类型
        luckyDrawPrizeList: [], // 奖品列表
        zjXz: undefined,
        luckyDrawWinPrizeLimitList: [], // 中奖限制
        cjGz: undefined,
        luckyDrawTaskList: [] // 赠送抽奖规则
      },
      zjXz: [], // 中奖限制列表
      cjGz: [], // 赠送规则列表
      rules: {
        activeName: [{ required: !this.state, message: '请输入活动名称', trigger: ['blur', 'change'] }],
        time: [{ required: !this.state, message: '请选择活动时间', trigger: ['blur', 'change'] }],
        purchaseTimesGold: [{ required: !this.state, message: '请输入付费抽奖规则', trigger: ['blur', 'change'] }],
        prizeDesc: [{ required: !this.state, message: '请输入奖品说明', trigger: ['blur', 'change'] }],
        activeLimitDesc: [{ required: !this.state, message: '请输入抽奖条件', trigger: ['blur', 'change'] }],
        activeDesc: [{ required: !this.state, message: '请输入抽奖说明', trigger: ['blur', 'change'] }],
        prizeClsNum: [{ required: !this.state, message: '请选择转盘类型', trigger: ['blur', 'change'] }]
      }
    }
  },
  methods: {
    // 不可选日期
    disabledDate (current, dateStrings) {
      return current && current < moment().subtract(1, 'days').endOf('day')
    },
    // 不限人次
    bxCjRcChange (e) {
      console.log(e)
      if (e.target.checked) {
        this.form.peopleLimitCount = ''
        this.$refs.ruleForm.clearValidate('peopleLimitCount')
      }
    },
    // 选择转盘类型
    zpTypeChange (val) {
      console.log(val)
      this.form.luckyDrawPrizeList = []
      for (let i = 0; i < val; i++) {
        this.form.luckyDrawPrizeList.push({
          prizeType: undefined,
          prizeDesc: '',
          isPrizeLimit: undefined,
          prizeRate: '',
          prizeNum: '',
          prizeImage: ''
        })
      }
      this.$refs.ruleForm.clearValidate()
    },
    // 中奖限制
    zjxzChange (val) {
      console.log(val)
      this.form.luckyDrawWinPrizeLimitList = []
      this.form.zjXz && this.form.zjXz.map(item => {
        const row = this.zjXz.find(k => k.code == item)
        this.form.luckyDrawWinPrizeLimitList.push({
          winPrizeLimitCode: item,
          winPrizeLimitCodeDictValue: row.dispName,
          limitTimes: ''
        })
      })
    },
    // 抽奖规则
    cjGzChange (val) {
      console.log(val)
      this.form.luckyDrawTaskList = []
      this.form.cjGz && this.form.cjGz.map(item => {
        const row = this.cjGz.find(k => k.code == item)
        this.form.luckyDrawTaskList.push({
          taskCode: item,
          taskCodeDictValue: row.dispName,
          giveTimes: ''
        })
      })
    },
    // 保存
    onSubmit () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          console.log('valid submit!!')
          // 至少有一个未中奖的奖品
          const hasNoPrize = this.form.luckyDrawPrizeList.find(item => item.prizeType == 'NONE')
          console.log(hasNoPrize)
          if (!hasNoPrize) {
            this.$message.warning('至少有一个未中奖类型的奖品')
            return
          }

          const formData = JSON.parse(JSON.stringify(this.form))
          formData.activeStartTime = moment(this.form.time[0]).format('YYYY-MM-DD') + ' 00:00:00'
          formData.activeEndTime = moment(this.form.time[1]).format('YYYY-MM-DD') + ' 00:00:00'
          formData.isPeopleLimit = this.form.isPeopleLimit ? 1 : 0

          // 中奖概率之和必需是100
          let gv = 0
          formData.luckyDrawPrizeList.map(item => {
            gv = gv + Number(item.prizeRate)
            if (item.isPrizeLimit == 0) {
              item.prizeNum = item.prizeNum || 0
              item.prizeRate = item.prizeRate || 0
            }
            if (item.prizeType == 'NONE') {
              item.prizeNum = 1
            }
          })
          if (gv != 100) {
            this.$message.warning('奖品概率之和必需是100')
            return
          }
          // 提交数据
          this.submitFormData(formData)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitFormData (formData) {
      this.loading = true
      saveLuckyDrawConfig(formData).then(res => {
        console.log(res, 'submitFormData')
        if (res.status == 200) {
          this.$message.info(res.message)
          this.cansel()
        } else {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    // 获取明细数据
    getDetail (id) {
      getLuckyDrawDetail({ id: id }).then(res => {
        if (res.status == 200) {
          this.participantsNum = res.data.participantsNum
		      this.state = res.data.state
          this.titleText = this.state == 1 ? '查看活动' : '编辑活动'
          res.data.luckyDrawPrizeList.map((item, index) => {
            if (!item.hasOwnProperty('prizeRate')) {
              item.prizeRate = ''
            }
            if (!item.hasOwnProperty('prizeNum')) {
              item.prizeNum = ''
            }
            delete item.id
            delete item.createDate
            delete item.luckyDrawNo
          })
          this.form = Object.assign({}, this.form, res.data)
          this.form.isPeopleLimit = this.form.isPeopleLimit == 1
          this.form.time = [moment(this.form.activeStartTime), moment(this.form.activeEndTime)]
          this.form.zjXz = this.getGzVal(this.form.luckyDrawWinPrizeLimitList, 0)
          this.form.cjGz = this.getGzVal(this.form.luckyDrawTaskList, 1)
          console.log(this.form.luckyDrawPrizeList)
          // 回显图片
          const _this = this
          setTimeout(() => {
            _this.form.luckyDrawPrizeList.map((item, index) => {
              _this.$refs[`prizeImage${index}`][0].setFileList(item.prizeImage)
              item.isPrizeLimit = Number(item.isPrizeLimit)
            })
          }, 500)
        }
      })
    },
    getGzVal (data, type) {
      const arr = []
      data.map(item => {
        arr.push(type == 1 ? item.taskCode : item.winPrizeLimitCode)
        delete item.id
        delete item.createDate
        delete item.luckyDrawNo
      })
      return arr
    },
    // 取消
    cansel () {
      this.isShow = false
      this.participantsNum = 0
      this.state = 0
      this.form.isPeopleLimit = false
      this.form.luckyDrawPrizeList = []
      this.form.luckyDrawTaskList = []
      this.form.luckyDrawWinPrizeLimitList = []
      this.form.zjXz = []
      this.form.cjGz = []
    }
  },
  created () {
    this.$nextTick(() => {
      setTimeout(() => {
        this.zjXz = this.$refs.zjXzType.getOptionDatas()
        this.cjGz = this.$refs.zsGzType.getOptionDatas()
      }, 500)
    })
  },
  watch: {
    showEditModal (newValue, oldValue) {
      this.isShow = newValue
    },
    isShow (val) {
      if (!val) {
        this.$emit('close')
      } else {
        this.$nextTick(() => {
          this.$refs.ruleForm.resetFields()
        })
      }
    },
    itemId (newValue, oldValue) {
      if (newValue && this.isShow) {
        this.getDetail(newValue)
      } else {
        this.titleText = '新增活动'
      }
    }
  }
}
</script>

<style lang="less">
  .addLottery-modal{
    .ant-input[disabled]{
      background: #fff;
      color: #666;
    }
    .ant-input-disabled,.ant-select-disabled .ant-select-selection,.ant-input-number-disabled{
      background: #fff;
      color: #666;
    }
    .form-titles{
      border-bottom: 1px solid #eee;
      padding-bottom: 10px;
      margin-bottom: 20px;
    }
    .form-item{
      display: flex;
      align-items: center;
      padding: 5px;
    }
    .upload-desc{
      font-size: 12px;
      margin-left: 10px;
    }
    .red{
      color: red;
    }
  }
</style>
