<template>
  <el-form size="small" class="tableForm" :model="prizeForm" :rules="rules" ref="form" label-width="80px">
    <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" :disabled="isDisabled" @change="calculateRate">
        <template slot="append">%</template>
      </el-input>
    </el-form-item>
    <el-table :data="prizeForm.tableData" style="width:100%">
      <el-table-column min-width="136px" prop="prizeType">
        <template slot="header"> <span class="needCell">奖品类型</span> </template>
        <template slot-scope="{ row, $index }">
          <el-form-item label-width="0">
            <el-select v-model="row.prizeType" @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 == 1">
            <el-form-item :prop="'tableData.' + $index + '.' + 'prizeNumber'" :rules="rules.prizeNumber" label-width="0"> <el-input class="inputClass" v-model.number="row.prizeNumber" @change="val => handlePrizeNumChange(val, $index)" />积分 </el-form-item>
          </div>
          <el-form-item label-width="0" v-else-if="row.prizeType == 2">
            <el-button type="text" @click="selectCard($index)" v-show="!row.prizeRelationId">选择卡券</el-button>
            <div class="box" v-show="row.prizeRelationId">
              <i class="cardIcon iconfont-components3 icon-cp-close-circle-fill" @click="delCard($index)"></i>
              <div class="cardBox">
                {{ row.prizeName }}
              </div>
            </div>
          </el-form-item>
          <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="'tableData.' + $index + '.' + 'prizeName'" :rules="rules.prizeName" label-width="0">
              <el-input v-model="row.prizeName" maxlength="10" />
            </el-form-item>
          </div>
          <el-form-item label-width="0" v-else>
            - -
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column min-width="105px" 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="'tableData.' + $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" :model.sync="row.prizeImageUrl" tips="" @backImg="obj => handleImgback(obj, row)" :unused="row.isInfo"></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="optNum">
        <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="'tableData.' + $index + '.' + 'optNum'" :rules="rules.optNum" label-width="0"> <el-input class="w80" v-model.number="row.optNum" @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="60" placeholder="不超过60个字" />
            </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="74px" 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" type="text" v-show="row.prizeType != 0 || prizeForm.tableData.filter(item => item.prizeType == 0).length > 1">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-button @click="addPrize" class="mt16 mb10" size="small" style="border-style: dashed;"><i class="iconfont icon-Plus" /> 添加奖项</el-button>
    <el-form-item label="库存提醒" prop="winChance">
      <el-switch v-model="prizeForm.prizeNoticeFlag" :active-value="1" :inactive-value="0" />
    </el-form-item>
    <el-form-item label="库存低于" prop="prizeNoticeStock">
      <el-form-item prop="prizeNoticeStock" :rules="rules.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 type="primary" @click="submit">保存并下一步</el-button>
    </dm-form-bottom>
    <libCard :show.sync="show" @sendItem="sendItem" />
  </el-form>
</template>

<script>
import dmUploadAvatar from '@/components/upload/avatar';
import libCard from '@/views/sign/components/lib-card.vue';
export default {
  data() {
    return {
      rules: {
        winChance: { type: 'number', required: true, message: '请输入不超过100的数字', max: 100, min: 0 },
        prizeNumber: { type: 'number', required: true, message: '请输入不超过1000000的数字', max: 1000000, min: 0 },
        optNum: { type: 'number', required: true, message: '请输入不超过1000000的数字', max: 1000000, min: 0 },
        prizeNoticeStock: { type: 'number', message: '请输入不超过1000000的数字', max: 1000000, min: 0 },
        prizeName: { type: 'string', 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'
      },
      show: false,
      prizeForm: {
        winChance: 100,
        tableData: [
          {
            prizeType: 0,
            prizeRate: 100
          }
        ]
      },
      prizeTypeOptions: [
        {
          value: 0,
          label: '谢谢参与'
        },
        {
          value: 1,
          label: '积分'
        },
        {
          value: 2,
          label: '卡券'
        }
      ],
      index: 0
    };
  },
  components: {
    dmUploadAvatar,
    libCard
  },
  methods: {
    handleImgback(obj, row) {
      console.log(obj, row);
    },
    selectCard(index) {
      this.show = true;
      this.index = index;
    },
    sendItem(selectedData) {
      console.log(selectedData);
      const data = this.prizeForm.tableData[this.index];
      data.prizeRelationId = selectedData.coupCardId;
      data.prizeName = selectedData.cardName.length > 10 ? selectedData.cardName.slice(0, 10) : selectedData.cardName;
      data.prizeImageUrl = { imgUrl: this.imgeType[selectedData.cardType], code: this.imgeType[selectedData.cardType] };
      this.prizeForm.tableData = this.prizeForm.tableData.splice(0);
    },
    addPrize() {
      this.prizeForm.tableData.push({});
    },
    del(index) {
      this.prizeForm.tableData.splice(index, 1);
      this.calculateRate();
    },
    delCard(index) {
      console.log(index);
      const data = this.prizeForm.tableData[index];
      data.prizeName = '';
      data.prizeRelationId = '';
      data.prizeImageUrl = '';
      this.prizeForm.tableData = this.prizeForm.tableData.splice(0);
    },
    handleTypeChange(val, index) {
      console.log(val, index);
      if (val == 0) {
        this.calculateRate();
      } else if (val == 1) {
        this.prizeForm.tableData[index].prizeImageUrl = { imgUrl: this.imgeType[3], code: this.imgeType[3] };
        this.prizeForm.tableData = this.prizeForm.tableData.splice(0);
      }
    },
    handlePrizeNumChange(val, index) {
      console.log(val, index);
      const data = this.prizeForm.tableData[index];
      data.prizeName = val + '积分';
      this.prizeForm.tableData = this.prizeForm.tableData.splice(0);
    },
    calculateRate() {
      const prizeNumTotal = this.prizeForm.tableData.map(item => (item.prizeType != 0 ? item.optNum : 0)).reduce((pre, current) => pre + current);
      this.prizeForm.tableData.forEach(item => {
        if (item.prizeType != 0) {
          const prizeRate = this.prizeForm.winChance * (item.optNum / prizeNumTotal);
          item.prizeRate = prizeRate.toFixed(2);
        }
      });
      const rateTotal = this.prizeForm.tableData.map(item => (item.prizeType != 0 ? item.prizeRate : 0)).reduce((pre, current) => Number(pre) + Number(current));
      console.log(rateTotal);
      let prizeArr = this.prizeForm.tableData.filter(item => item.prizeType == 0);
      prizeArr.forEach(item => {
        console.log(item);
        const prizeRate = (100 - rateTotal) / prizeArr.length || 0;
        item.prizeRate = prizeRate.toFixed(2);
      });
      this.prizeForm.tableData = this.prizeForm.tableData.splice(0);
    },
    submit() {
      this.$refs.form.validate(val => {
        if (val) {
          this.$emit('nextStep', { data: this.prizeForm });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.footer {
  width: calc(100% - 520px) !important;
}
.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;
}
.cardIcon {
  position: absolute;
  top: -5px;
  right: -5px;
  cursor: pointer;
}
.inputClass {
  width: calc(100% - 32px);
}
.tableForm {
  /depp/ .has-gutter {
    .cell {
      &::before {
        content: '*';
        color: #f56c6c;
        margin-right: 4px;
      }
    }
  }
}
/depp/ .has-gutter {
  .cell {
    &::before {
      content: '*';
      color: #f56c6c;
      margin-right: 4px;
    }
  }
}
/depp/ .cell {
  &::before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
  }
}
.needCell {
  &::before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
  }
}
</style>
