<template>
  <el-form size="small" class="tableForm" :model="prizeForm" :rules="rules" ref="prizeForm" label-width="100px">
    <dm-sub-title type="line" class="mb20">奖项配置</dm-sub-title>
    <el-form-item label="总中奖率" prop="winChance">
      <el-input class="w180" v-model.number="prizeForm.winChance" @change="calculateRate">
        <template slot="append">%</template>
      </el-input>
    </el-form-item>

    <el-table :data="prizeForm.gamePrizeList" style="width: 100%" row-key="sort" ref="sortTable" row-class-name="table-row">
      <el-table-column width="40" label-class-name="tag-head">
        <template>
          <el-tooltip placement="top" content="拖动排序" trigger="hover" effect="dark" popper-class="drag-tooltip">
            <i class="iconfont-components3 icon-cp-tuozhuaipaixu deactive" />
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column min-width="136px" prop="prizeType">
        <template slot="header"> <span class="needCell">奖品类型</span> </template>
        <template slot-scope="{ row, $index }">
          <el-form-item :prop="'gamePrizeList.' + $index + '.' + 'prizeType'" :rules="rules.prizeType" label-width="0">
            <el-select v-model="row.prizeType" :disabled="isDisabled && row.isOld" @change="val => handleTypeChange(val, $index)">
              <el-option v-for="(v, i) in prizeTypeOptions" :key="i" :label="v.label" :value="v.value"></el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column min-width="132px">
        <template slot="header"> <span class="needCell">奖项设置</span> </template>
        <template slot-scope="{ row, $index }">
          <div v-if="row.prizeType == 2">
            <el-form-item label-width="0" :prop="'gamePrizeList.' + $index + '.' + 'prizeNameStr'" :rules="rules.prizeNameStr">
              <el-button type="text" @click="selectCard($index)" v-show="!row.prizeRelationId">选择卡券</el-button>
              <div class="box" v-show="row.prizeRelationId">
                <i v-show="!isDisabled || !row.isOld" class="cardIcon iconfont-components3 icon-cp-close-circle-fill" @click="delCard($index)"></i>
                <div :class="['cardBox', row.status == 1 || row.status == 2 ? 'redBorder' : '']">
                  <el-tag v-show="row.status == 1" size="mini" type="danger" class="tagIcon">删除</el-tag>
                  <el-tag v-show="row.status == 2" size="mini" type="danger" class="tagIcon">失效</el-tag>
                  {{ row.prizeNameStr }}
                </div>
              </div>
            </el-form-item>
          </div>
          <div v-else-if="row.prizeType == 1">
            <el-form-item :prop="'gamePrizeList.' + $index + '.' + 'prizeNumber'" :rules="rules.prizeNumber" label-width="0"> <el-input class="inputClass-32" :disabled="isDisabled && row.isOld" v-model.number="row.prizeNumber" @change="val => handlePrizeNumChange(val, $index)" />积分 </el-form-item>
          </div>
          <el-form-item label-width="0" v-else> - - </el-form-item>
        </template>
      </el-table-column>
      <el-table-column min-width="120px" prop="prizeName">
        <template slot="header"> <span class="needCell">奖品名称</span> </template>
        <template slot-scope="{ row, $index }">
          <div v-if="row.prizeType == 1 || row.prizeType == 2">
            <el-form-item :prop="'gamePrizeList.' + $index + '.' + 'prizeName'" :rules="rules.prizeName" label-width="0">
              <el-input v-model="row.prizeName" maxlength="30" placeholder="不超过30个字" :disabled="isDisabled && row.isOld" />
            </el-form-item>
          </div>
          <el-form-item label-width="0" v-else> - - </el-form-item>
        </template>
      </el-table-column>
      <el-table-column min-width="115px" prop="prizeImageUrl">
        <template slot="header">
          <span class="needCell">
            奖品图片
            <el-tooltip content="未上传图片取奖品默认图片" placement="top">
              <i class="iconfont icon-QuestionCircleOutlined"></i>
            </el-tooltip>
          </span>
        </template>
        <template slot-scope="{ row, $index }">
          <div v-if="row.prizeType == 1 || row.prizeType == 2" style="width: 60px; height: 62px">
            <el-form-item :prop="'gamePrizeList.' + $index + '.' + 'prizeImageUrl'" :rules="rules.prizeImageUrl" label-width="0">
              <dm-upload-avatar class="upload-avatar" width="60" height="60" :limit="{ type: false, maxSize: 1 }" fileType="img" imgType="jpg/jpeg/png" :model.sync="row.prizeImageUrl" tips="" :unused="isDisabled && row.isOld ? true : false"></dm-upload-avatar>
            </el-form-item>
          </div>
          <el-form-item label-width="0" v-else> - - </el-form-item>
        </template>
      </el-table-column>
      <el-table-column min-width="118px" prop="prizeStock">
        <template slot="header"> <span class="needCell">奖品数量</span> </template>
        <template slot-scope="{ row, $index }">
          <div v-if="row.prizeType == 1 || row.prizeType == 2">
            <el-form-item :prop="'gamePrizeList.' + $index + '.' + 'prizeStock'" :rules="{ validator: prizeStockRule(row) }" label-width="0"> <el-input class="inputClass-12" v-model.number="row.prizeStock" placeholder="请输入" @change="calculateRate" /> 件 </el-form-item>
          </div>
          <el-form-item label-width="0" v-else> - - </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="奖品说明" min-width="140px" prop="prizeDesc">
        <template slot-scope="{ row }">
          <div v-if="row.prizeType == 1 || row.prizeType == 2">
            <el-form-item label-width="0">
              <el-input v-model="row.prizeDesc" maxlength="30" placeholder="不超过30个字" />
            </el-form-item>
          </div>
          <el-form-item label-width="0" v-else> - - </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="中奖率" min-width="84px" prop="prizeRate">
        <template slot="header">
          中奖率
          <el-tooltip placement="top">
            <div slot="content">
              1、奖品中奖率之和不可大于100%；<br />
              2、某一奖项库存为0后，该奖项中奖率置为0；<br />
              3、奖项中最少有一项为【谢谢参与】预防所有奖品无库存；
            </div>
            <i class="iconfont icon-QuestionCircleOutlined"></i>
          </el-tooltip>
        </template>
        <template slot-scope="{ row }">
          <el-form-item label-width="0"> {{ !isNaN(row.prizeRate) ? row.prizeRate + '%' : '' }} </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right">
        <template slot-scope="{ row, $index }">
          <el-popconfirm icon="el-icon-info" title="确认删除吗？" @confirm="del($index)">
            <el-button slot="reference" :disabled="isDisabled && row.isOld" type="text" v-show="row.prizeType != 0 || prizeForm.gamePrizeList.filter(item => item.prizeType == 0).length > 1">删除 </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-button @click="addPrize" class="mb20 mt16" size="small" style="border-style: dashed" v-show="this.prizeForm.gamePrizeList.length < prizeMax"> <i class="iconfont icon-Plus" /> 添加奖项({{ this.prizeForm.gamePrizeList.length }}/{{ prizeMax }}) </el-button>
    <el-form-item label="奖品数量提醒">
      <el-switch v-model="prizeForm.prizeNoticeFlag" :active-value="1" :inactive-value="0" />
    </el-form-item>
    <el-form-item label="奖品数量低于" v-show="prizeForm.prizeNoticeFlag == 1">
      <el-form-item prop="prizeNoticeStock">
        <el-input class="w180" v-model.number="prizeForm.prizeNoticeStock" placeholder="请输入" />
        <span class="ml10">件发送短信提醒</span>
        <el-popover placement="right" width="200" trigger="hover" content="您创建的游戏（游戏名称）中（奖品名称）的奖品数量已低于（奖品数量）件，请及时关注并补充！">
          <el-button slot="reference" type="text" class="ml16">查看短信内容 </el-button>
        </el-popover>
      </el-form-item>
    </el-form-item>
    <dm-form-bottom class="footer">
      <el-button @click="prevStep">上一步</el-button>
      <el-button type="primary" @click="nextStep()">保存并下一步</el-button>
    </dm-form-bottom>
    <libCard :show.sync="show" @sendItem="sendItem" :cardLimitType="-1" :cardLimit="1" />
  </el-form>
</template>

<script>
import dmUploadAvatar from '@/components/upload/avatar';
import libCard from '@/views/sign/components/lib-card.vue';
import Sortable from 'sortablejs';
import { cardView } from '@/service/api/gameApi.js';
export default {
  data() {
    const prizeNoticeStockVal = (rule, value, callback) => {
      if (this.prizeForm.prizeNoticeFlag == 1) {
        if (!new RegExp('([1-9]{1}\\d{0,9})|(0{1})').test(value)) {
          callback(new Error('请输入奖品数量'));
          return;
        }
        if (value <= 0 || value > 1000000) {
          callback(new Error('最大值1000000'));
          return;
        }
      }
      callback();
    };

    return {
      rules: {
        winChance: { type: 'number', required: true, message: '最大值100', max: 100, min: 0 },
        prizeNumber: { type: 'number', required: true, message: '最大值1000000', max: 1000000, min: 1 },
        prizeNameStr: { type: 'string', required: true, message: '请选择卡券' },
        prizeStock: { type: 'number', required: true, message: '最大值1000000', max: 1000000, min: 0 },
        prizeNoticeStock: { validator: prizeNoticeStockVal },
        prizeName: { type: 'string', required: true, message: '请输入奖品名称' },
        prizeType: { required: true, message: '请选择奖品类型' }
      },
      imgeType: {
        // 0 抵金券1 折扣券2 兑换券3：积分
        0: 'https://pic01-10001430.image.myqcloud.com/522b7c1e-dea4-4068-b0a3-0e07bc229b0d',
        1: 'https://pic01-10001430.image.myqcloud.com/32fa9132-5aed-4f7f-8be1-a3f81f2e58f7',
        2: 'https://pic01-10001430.image.myqcloud.com/029abce4-660c-4115-a70f-55ba8f626832',
        // 3: 'https://pic01-10001430.image.myqcloud.com/7fbc9e9b-4115-4795-aea3-cd2c1ec8da63'
        3: 'https://pic01-10001430.image.myqcloud.com/522b7c1e-dea4-4068-b0a3-0e07bc229b0d'
      },
      show: false,
      prizeForm: {
        winChance: 100,
        prizeNoticeStock: '',
        gamePrizeList: [
          {
            prizeType: 0,
            prizeRate: 100,
            sort: 0,
            prizeName: '谢谢参与',
            prizeImageUrl: { imgUrl: '', code: '' },
            prizeNumber: 1,
            exchangeType: 0
          }
        ]
      },
      prizeTypeOptions: [
        {
          value: 0,
          label: '谢谢参与'
        },
        {
          value: 1,
          label: '积分'
        },
        {
          value: 2,
          label: '卡券'
        }
      ],
      index: 0,
      isEdit: this.$route.meta.type === 'edit',
      boolVal: true
    };
  },
  props: {
    prizeMax: 0,
    prizeMin: 0,
    gameStatus: 0,
    imageType: {
      type: Object,
      default: () => {}
    },
    echoData: {
      type: Object,
      default: () => {}
    },
    invalidCard: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    dmUploadAvatar,
    libCard
  },
  computed: {
    isDisabled() {
      return this.gameStatus == 1;
    }
  },
  mounted() {
    this.drag();
    document.addEventListener('visibilitychange', () => {
      if (!document.hidden) {
        this.cardView();
      }
    });
  },
  watch: {
    echoData(val) {
      this.prizeForm = Object.assign(this.prizeForm, val);
      this.prizeForm.gamePrizeList.forEach(item => {
        if (item.prizeImageUrl) {
          item.prizeImageUrl = { imgUrl: item.prizeImageUrl, code: item.prizeImageUrl };
        }
        if (this.isEdit) {
          item.prizeStockOriginal = item.prizeStock;
        } else {
          item.prizeStock = '';
        }
      });
      this.calculateRate();
      this.prizeForm.gamePrizeList = this.prizeForm.gamePrizeList.splice(0);
      console.log(this.prizeForm);
    },
    invalidCard(val) {
      console.log('invalidCard====>');
      this.handleInvalidCard(val);
    }
  },
  methods: {
    async cardView() {
      let cardIdArr = this.prizeForm.gamePrizeList.filter(item => item.prizeRelationId && item.prizeType == 2);
      if (cardIdArr.length) {
        cardIdArr = cardIdArr.map(item => item.prizeRelationId);
        const { result } = await cardView({ ids: cardIdArr.join(',') });
        this.handleInvalidCard(result);
      }
    },
    handleInvalidCard(val) {
      this.prizeForm.gamePrizeList.forEach(item => {
        if (item.prizeType == 2 && val[item.prizeRelationId]) {
          item.status = val[item.prizeRelationId].invalid;
          item.prizeNameStr = val[item.prizeRelationId].name;
          if (this.isEdit && item.isOld) {
            item.max = item.prizeStock + val[item.prizeRelationId].stock;
          } else {
            item.max = val[item.prizeRelationId].stock;
          }
        }
      });
      this.$nextTick(() => {
        this.$refs.prizeForm.clearValidate();
      });
    },

    prizeStockRule(row) {
      return (rule, value, callback) => {
        if (row.prizeType == 1) {
          if (!new RegExp('([1-9]{1}\\d{0,9})|(0{1})').test(value)) {
            callback(new Error('最大值1000000'));
            return;
          }
          if (value < 0 || value > 1000000) {
            callback(new Error('最大值1000000'));
            return;
          }
        }
        if (row.prizeType == 2) {
          if (isNaN(row.max)) {
            callback(new Error(`请选择卡券`));
            return;
          }
          if (!new RegExp('([1-9]{1}\\d{0,9})|(0{1})').test(value)) {
            callback(new Error('请输入'));
            return;
          }
          if (value > row.max || value < 0) {
            callback(new Error(`大于奖品关联库存${row.max}`));
            return;
          }
        }
        callback();
      };
    },
    //  拖拽
    drag() {
      let that = this;
      const tbody = this.$refs.sortTable.$el.querySelector('.el-table__body tbody');
      const sort = Sortable.create(tbody, {
        onChoose(e) {
          // 针对icon触发事件
          const isSortIcon = e.originalEvent.target.classList.contains('icon-cp-tuozhuaipaixu');
          sort.option('sort', isSortIcon);
        },
        onEnd({ newIndex, oldIndex }) {
          const currRow = that.prizeForm.gamePrizeList.splice(oldIndex, 1)[0];
          that.prizeForm.gamePrizeList.splice(newIndex, 0, currRow);
        }
      });
    },
    selectCard(index) {
      this.show = true;
      this.index = index;
    },
    sendItem(selectedData) {
      const data = this.prizeForm.gamePrizeList[this.index];
      data.prizeRelationId = selectedData.coupCardId;
      data.prizeName = selectedData.cardName.length > 30 ? selectedData.cardName.slice(0, 30) : selectedData.cardName;
      data.prizeNameStr = data.prizeName;
      data.prizeImageUrl = { imgUrl: this.imageType[selectedData.cardType], code: this.imageType[selectedData.cardType] };
      data.prizeNumber = 1;
      data.status = 0;
      data.max = selectedData.couponStock;
      this.prizeForm.gamePrizeList = this.prizeForm.gamePrizeList.splice(0);
      this.$refs.prizeForm.validateField(`gamePrizeList.${this.index}.prizeNameStr`);
    },
    addPrize() {
      this.prizeForm.gamePrizeList.push({ sort: this.prizeForm.gamePrizeList.length, exchangeType: 0, isOld: 0, prizeName: '', prizeNameStr: '' });
    },
    del(index) {
      this.prizeForm.gamePrizeList.splice(index, 1);
      this.calculateRate();
    },
    delCard(index) {
      const data = this.prizeForm.gamePrizeList[index];
      data.prizeName = '';
      data.prizeRelationId = '';
      data.prizeImageUrl = { imgUrl: '', code: '' };
      data.prizeNameStr = '';
      this.prizeForm.gamePrizeList = this.prizeForm.gamePrizeList.splice(0);
      this.$refs.prizeForm.validateField(`gamePrizeList.${index}.prizeStock`);
    },
    handleTypeChange(val, index) {
      if (val == 0) {
        this.prizeForm.gamePrizeList[index].prizeImageUrl = { imgUrl: '', code: '' };
        this.prizeForm.gamePrizeList[index].prizeName = '谢谢参与';
        this.prizeForm.gamePrizeList[index].prizeNumber = 1;
        this.prizeForm.gamePrizeList[index].optNum = -1;
        this.prizeForm.gamePrizeList[index].prizeNameStr = '';
        delete this.prizeForm.gamePrizeList[index].prizeRelationId;
      } else if (val == 1) {
        this.prizeForm.gamePrizeList[index].prizeImageUrl = { imgUrl: this.imageType[3], code: this.imageType[3] };
        this.prizeForm.gamePrizeList[index].prizeName = '';
        this.prizeForm.gamePrizeList[index].prizeNameStr = '';
        delete this.prizeForm.gamePrizeList[index].prizeNumber;
        this.prizeForm.gamePrizeList[index].optNum = '';
        delete this.prizeForm.gamePrizeList[index].prizeRelationId;
      } else if (val == 2) {
        this.prizeForm.gamePrizeList[index].prizeImageUrl = { imgUrl: '', code: '' };
        this.prizeForm.gamePrizeList[index].prizeName = '';
        this.prizeForm.gamePrizeList[index].prizeNameStr = '';
        this.prizeForm.gamePrizeList[index].prizeNumber = '';
        this.prizeForm.gamePrizeList[index].optNum = '';
        delete this.prizeForm.gamePrizeList[index].prizeRelationId;
      }
      this.$refs.prizeForm.clearValidate(`gamePrizeList.${index}.prizeStock`);
      this.calculateRate();
      this.prizeForm.gamePrizeList = this.prizeForm.gamePrizeList.splice(0);
    },
    handlePrizeNumChange(val, index) {
      console.log(val, index);
      const data = this.prizeForm.gamePrizeList[index];
      data.prizeName = val + '积分';
      this.prizeForm.gamePrizeList = this.prizeForm.gamePrizeList.splice(0);
    },
    calculateRate() {
      const prizeNumTotal = this.prizeForm.gamePrizeList.map(item => (item.prizeType != 0 ? item.prizeStock : 0)).reduce((pre, current) => pre + current);
      console.log(prizeNumTotal);
      this.prizeForm.gamePrizeList.forEach(item => {
        if (item.prizeType != 0) {
          const prizeRate = prizeNumTotal ? this.prizeForm.winChance * (item.prizeStock / prizeNumTotal) : 0;
          item.prizeRate = prizeRate.toFixed(2) || 0;
        }
      });
      let prizeArr = this.prizeForm.gamePrizeList.filter(item => item.prizeType == 0);

      if (!prizeNumTotal) {
        prizeArr.forEach(item => {
          const prizeRate = 100 / prizeArr.length || 0;
          item.prizeRate = prizeRate.toFixed(2);
        });
      } else {
        prizeArr.forEach(item => {
          const prizeRate = (100 - this.prizeForm.winChance) / prizeArr.length || 0;
          item.prizeRate = prizeRate.toFixed(2);
        });
      }

      this.prizeForm.gamePrizeList = this.prizeForm.gamePrizeList.splice(0);
    },
    prevStep() {
      this.$emit('prevStep');
    },
    validateData() {
      let invalid = false;
      let arr = [];
      this.$refs.prizeForm.validate((val, obj) => {
        this.boolVal = val;
        console.log(obj);
        if (!val) {
          this.scrollToError(this);
        }
      });
      if (!this.boolVal) {
        this.$message.error('请确认奖品配置的必填字段都已填写且通过校验');
        return false;
      }
      this.prizeForm.gamePrizeList.forEach(item => {
        if (item.prizeType == 2 && item.status != 0 && !item.isOld) {
          invalid = true;
          this.$message.error(`${item.prizeName}已${item.status == 1 ? '删除' : '失效'}，请重新关联奖品`);
          return false;
        }
        if (item.prizeType == 0) {
          arr.push(item);
        }
      });
      if (!arr.length) {
        this.$message.error('请至少包含一个谢谢参与的奖项');
        return false;
      }
      if (invalid) return false;
      if (this.prizeForm.gamePrizeList.length < this.prizeMin) {
        this.$message.error(`请配置至少${this.prizeMin}个奖项`);
        return false;
      }
      if (this.prizeForm.gamePrizeList.length > this.prizeMax) {
        this.$message.error(`请配置最多${this.prizeMax}个奖项`);
        return false;
      }
      return true;
    },
    nextStep(noNext) {
      return new Promise(resolve => {
        const val = this.validateData();
        if (val) {
          let data = { ...this.prizeForm };
          data = JSON.parse(JSON.stringify(data));
          data.gamePrizeList.forEach((item, index) => {
            item.prizeImageUrl = item.prizeImageUrl.imgUrl || '';
            item.sort = index;

            if (item.prizeType == 0) {
              item.prizeStock = -1;
            }
            if (item.prizeType != 0) {
              if (this.isEdit && item.isOld) {
                let num = item.prizeStock - item.prizeStockOriginal;
                item.optNum = num;
              } else {
                item.optNum = item.prizeStock;
              }
            } else {
              item.optNum = -1;
            }
          });
          this.$emit('nextStep', data, noNext);
        }
        resolve(val);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.footer {
  width: calc(100% - 520px) !important;
}

.table-row:hover {
  .deactive {
    color: #606266;
    display: block;
    cursor: grabbing;
  }
}

.box {
  position: relative;
  height: 48px;
  padding: 10px 0;
  width: 100%;
}

.cardBox {
  width: 100%;
  height: 32px;
  border-radius: 2px;
  border: 1px dashed #c4c6cf;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding-left: 10px;
}

.redBorder {
  border-color: red;
}

.cardIcon {
  position: absolute;
  top: -5px;
  right: -5px;
  cursor: pointer;
}

.needCell {
  color: #303133;

  &::before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
  }
}

.inputClass-32 {
  width: calc(100% - 32px);
}

.inputClass-12 {
  width: calc(100% - 24px);
}
</style>
