<template>
  <div class="system-edit-post-container">
    <el-form ref="formRef" :model="queryParams" size="default" label-width="100px">
      <el-card shadow="hover">
        <el-form-item label="类型" prop="Type">
          <el-radio-group v-model="queryParams.keyType" @change="showType">
            <el-radio :label="1">一码多用</el-radio>
            <el-radio :label="2">多码单用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择渠道" prop="serverId">
          <el-select v-model="queryParams.channels" multiple class="m-2" placeholder="选择渠道" size="large"
                     style="width: 220px" clearable>
            <el-option v-for="item in channels" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <div class="flex-warp">
            <el-input v-model="queryParams.name" placeholder="请输入名称" size="large" style="width: 220px"/>
          </div>
          <span v-show="check&&!queryParams.name" style="color: red">*</span>
        </el-form-item>
        <div v-show="queryParams.keyType==1">
          <el-form-item label="口令" prop="pass">
            <div class="flex-warp">
              <el-input v-model="queryParams.pass" placeholder="请输入口令" size="large" style="width: 220px"/>
            </div>
            <span v-show="check&&!queryParams.pass" style="color: red">*</span>
          </el-form-item>
        </div>
        <div v-show="queryParams.keyType==2">
          <el-form-item label="数量" prop="num">
            <div class="flex-warp">
              <el-input-number v-model="queryParams.num" placeholder="请输入数量" size="large" controls-position="right"
                               :min="1" style="width: 220px"/>
            </div>
            <span v-show="check&&!queryParams.num" style="color: red">*</span>
          </el-form-item>
        </div>
        <el-form-item label="兑换次数" prop="times" label-width="100px">
          <div class="flex-warp">
            <el-input-number v-model="queryParams.times" placeholder="请输入兑换次数" size="large"
                             controls-position="right" :min="1" style="width: 220px"/>
          </div>
          <span v-show="check&&!queryParams.times" style="color: red">*</span>
        </el-form-item>
        <el-form-item label="有效时间" prop="dates">
          <el-date-picker style="width: 400px" range-separator="-" type="datetimerange" v-model="queryParams.dates"
                          start-placeholder="开始" end-placeholder="结束" value-format="YYYY-MM-DD HH:mm:ss"
                          size="large"/>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="奖励内容"/>
        <el-table :data="queryParams.awards" :inline="true" :cell-style="{padding:'2'}" table-layout="fixed">
          <el-table-column width="30">
            <template #default="scope">
              <div class="flex-warp">
                <el-button size="small" type="text" @click="delItem(scope.$index)">
                  <el-icon>
                    <ele-Minus/>
                  </el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="60" label="序号">
            <template #default="scope">
              <div class="flex-warp">{{ scope.$index + 1 }}</div>
            </template>
          </el-table-column>
          <el-table-column label="物品">
            <template #default="scope">
              <div class="flex-warp">
                <el-select v-model="scope.row.itemId" filterable placeholder="请选择物品">
                  <el-option v-for="item in ItemConfig" :key="item.Id" :label="item.Id+' '+item.Name" :value="item.Id"/>
                </el-select>
              </div>
              <span v-show="check&&!scope.row.itemId" style="color: red">*</span>
            </template>
          </el-table-column>
          <el-table-column label="数量">
            <template #default="scope">
              <div class="flex-warp">
                <el-input-number v-model="scope.row.num" placeholder="请输入数量" style="width: 220px" :min="1"
                                 onkeyup="this.value=this.value.replace(/\D/g,'');" controls-position="right"
                                 onafterpaste="this.value=this.value.replace(/\D/g,'')"/>
              </div>
              <span v-show="check&&!scope.row.num" style="color: red">*</span>
            </template>
          </el-table-column>
        </el-table>
        <el-button size="default" type="primary" style="margin: 10px 0" @click="addItem()">
          <el-icon>
            <ele-Plus/>
          </el-icon>
          添加奖励
        </el-button>
        <el-divider></el-divider>
        <div class="flex-warp">
          <el-form-item>
            <el-button size="default" type="primary" @click="onSubmit">
              <el-icon>
                <ele-Select/>
              </el-icon>
              保存配置
              <div v-if="queryParams.keyType==2">并生成兑换码</div>
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button size="default" type="primary" @click="onDownload" v-if="queryParams.keyType==2&&!disabled"
                       :loading="loading">
              <div v-if="loading">正在生成兑换码</div>
              <div v-else>下载兑换码</div>
            </el-button>
          </el-form-item>
        </div>
      </el-card>
    </el-form>
  </div>
</template>
<script lang="ts">
import {reactive, toRefs, defineComponent, ref, unref, onMounted} from 'vue';
import {gameRandomGenerateCode, giftExchangeExists} from '/@/api/game';
import AllItemConfigCategory from "/@/api/config/AllItemConfigCategory.json";
import {ElMessage, ElLoading} from "element-plus";
import {allChannelList, channelList} from "/@/utils/game";

interface Award {
  itemId: number;
  num: number;
}

interface TableDataState {
  queryParams: {
    keyType: number,
    channels: string[],
    channel: string,
    name: string,
    pass: string,
    num: number,
    times: number,
    dates: [],
    startTime: string,
    stopTime: string,
    awards: Array<Award>,
  }
  tableData: {};
  ItemConfig: object;
  channels: object[];
  check: boolean;
  disabled: boolean
  loading: boolean
}

var timeInterval;

const baseURL: string | undefined | boolean = import.meta.env.VITE_API_URL
export default defineComponent({
  name: 'apiV1GameCdKeySet',
  setup: function () {
    const formRef = ref<HTMLElement | null>(null);
    const state = reactive<TableDataState>({
      queryParams: {
        keyType: 1,
        channels: [],
        channel: "",
        name: "",
        pass: "",
        num: 1,
        times: 1,
        dates: [],
        startTime: "",
        stopTime: "",
        awards: [],
      },
      tableData: {},
      ItemConfig: AllItemConfigCategory,
      channels: [],
      check: false,
      disabled: true,
      loading: false,
    });

    const onSubmit = () => {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      state.check = true;
      const formWrap = unref(formRef) as any;
      if (!formWrap) return;
      formWrap.validate((valid: boolean) => {
        console.log(valid);
        // if (!valid) {
        //   ElMessage.error('还有配置未填写');
        //   loading.close();
        //   return;
        // }


        let msg = stateAward();
        if (msg) {
          ElMessage.error(msg);
          loading.close();
          return;
        }
        state.queryParams.startTime = state.queryParams.dates[0]
        state.queryParams.stopTime = state.queryParams.dates[1]
        if (!state.queryParams.startTime || !state.queryParams.stopTime) {
          ElMessage.error("时间未设置");
          loading.close();
          return;
        }
        if (state.queryParams.times <= 0) {
          ElMessage.error("兑换次数无效");
          loading.close();
          return;
        }
        if (state.queryParams.name == "") {
          ElMessage.error("名称未配置");
          loading.close();
          return;
        }
        if (state.queryParams.keyType == 2 && !state.queryParams.num) {
          ElMessage.error("名称未配置");
          loading.close();
          return;
        }
        if (state.queryParams.keyType == 1 && !state.queryParams.pass) {
          ElMessage.error("名称未配置");
          loading.close();
          return;
        }
        state.queryParams.channel = "";
        for (let i = 0; i < state.queryParams.channels.length; i++) {
          if (state.queryParams.channel.length > 0) {
            state.queryParams.channel += ";"
          }
          state.queryParams.channel += state.queryParams.channels[i]
        }

        console.log(state.queryParams);
        gameRandomGenerateCode(state.queryParams).then((res) => {
          if (!res || Number(res.code) != 0) {
            ElMessage.success('兑换码配置保存失败');
            return;
          }
          ElMessage.success('兑换码配置保存成功');
          if (res.data.filename != "") {
            state.filename = res.data.filename;
            state.loading = true
            state.disabled = false
            console.log("gameRandomGenerateCode: ", res, state.filename);
            timeInterval = setInterval(function () {
              checkGiftExchangeExists();
            }, 10000);
          }

        }).finally(() => {
          state.check = false;
          loading.close();
        });
        return;
      });
    };
    let stateAward = () => {
      console.log(state.queryParams);
      if (state.queryParams.awards.length == 0 || !state.queryParams.awards) {
        console.log("1", state.queryParams);
        return "奖励配置未填写";
      }
      for (let i in state.queryParams.awards) {
        state.queryParams.awards[i].itemId = Number(state.queryParams.awards[i].itemId);
        state.queryParams.awards[i].num = Number(state.queryParams.awards[i].num);
        if (!state.queryParams.awards[i].itemId || !state.queryParams.awards[i].num) {
          console.log("4", state.queryParams.awards[i]);
          return "奖励配置未填写";
        }
      }
      // state.queryParams.rewards = JSON.stringify(state.queryParams.awards);
      return ""
    };
    onMounted(() => {
      channelList().then(response => {
        state.channels = response;
      })
    });
    const delItem = (index: number) => {
      console.log("delItem: ", index)
      state.queryParams.awards.splice(index, 1);
    };
    const addItem = () => {
      let item = {};
      if (!state.queryParams.awards) {
        state.queryParams.awards = [];
      }
      state.queryParams.awards.push(item);
    };
    const checkGiftExchangeExists = () => {
      giftExchangeExists({"file": state.filename}).then(response => {
        console.log("checkGiftExchangeExists", state.filename, response);
        if (response.data.state == 1) {
          clearInterval(timeInterval);
          state.loading = false
        }
      })
    };
    const onDownload = () => {
      if (state.filename) {
        window.open(baseURL + 'upload_file?filename=' + state.filename);
      }
      // state.disabled = true;
    }
    const showType = () => {
      if (state.queryParams.keyType == 2) {
        state.disabled = true;
        state.loading = false;
      }
    }
    return {
      onSubmit,
      onDownload,
      formRef,
      delItem,
      addItem,
      checkGiftExchangeExists,
      showType,
      ...toRefs(state),
    };
  },
});
</script>

<style scoped lang="scss">
.el-table {
  --el-table-border-color: var(--el-border-color-lighter);
  --el-table-border: 0px solid var(--el-table-border-color);
}

::v-deep .el-table .el-table__cell {
  padding: 0;
  margin-left: -20px;
  min-width: 0;
  box-sizing: border-box;
  text-overflow: ellipsis;
  vertical-align: middle;
  position: relative;
  text-align: left;
  z-index: 1;
}

.tree-border {
  margin-top: 5px;
  border: 1px solid #e5e6e7 !important;
  background: #fff none !important;
  border-radius: 4px;
}

.system-edit-post-container {
  .menu-data-tree {
    border: var(--el-input-border, var(--el-border-base));
    border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
    padding: 5px;
  }
}

.editable-cell__input {
  display: inline;
  width: 10%;

  .el-input__inner {
    padding: 0 8px;
    font-size: 12px;
  }
}

.left-block {
  margin-left: -20px;
}

.table-num-left {
  margin-left: -85px;
}

.num-left {
  margin-left: -30px;
}

.title-label-block {
  margin-left: -20px;
}

.label-block {
  padding-left: 10px;
}

::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #ffffd5;
}

.warning-row {
  background: #ffffd5;
}

::v-deep .warning-row .el-table__body tr {
  background-color: #ffffd5;
}

::v-deep .warning-row .el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: inherit;
}

::v-deep .warning-row .el-table__cell {
  background-color: #ffffd5;
}

::v-deep .tableCell {
  margin-left: -15px;
}
</style>
