<template>
  <div class="game-order-container">
    <el-card shadow="hover" header="兑换码生成">
      <div class="game-order-search mb15">
        <el-form :inline="true">
          <!--          <div class="flex-warp">-->
          <el-form-item label="类型" prop="Type">
            <el-select v-model="queryParams.keyType" class="m-2" placeholder="选择类型" style="width: 200px">
              <el-option label="全部" :value="0"/>
              <el-option label="一码多用" :value="1"/>
              <el-option label="多码单用" :value="2"/>
            </el-select>
          </el-form-item>
          <el-form-item label="选择渠道" prop="channel">
            <el-select v-model="queryParams.channel" class="m-2" placeholder="选择渠道" style="width: 200px">
              <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">
            <el-input v-model="queryParams.name" placeholder="请输入名称" style="width: 200px"/>
          </el-form-item>
          <el-form-item label="一码多用口令" prop="pass" label-width="100px">
            <el-input v-model="queryParams.pass" placeholder="请输入口令" style="width: 200px"/>
          </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"/>
          </el-form-item>
          <el-form-item label="状态" prop="states">
            <el-select v-model="queryParams.states" class="m-2" placeholder="选择类型" style="width: 200px">
              <el-option label="全部" :value="0"/>
              <el-option label="未生效" :value="1"/>
              <el-option label="已生效" :value="2"/>
              <el-option label="已失效" :value="3"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="ml10" @click="getList">
              <el-icon>
                <ele-Search/>
              </el-icon>
              查询
            </el-button>
          </el-form-item>
          <!--          </div>-->
        </el-form>
      </div>
      <el-table :data="tableData.data" border style="width: 100%">
        <el-table-column prop="id" label="ID" show-overflow-tooltip width="50px">
        </el-table-column>
        <el-table-column prop="type" label="类型" show-overflow-tooltip width="80px">
          <template #default="scope">
            <div v-if="scope.row.type==1">一码多用</div>
            <div v-else-if="scope.row.type==2">多码单用</div>
            <div v-else>{{ scope.row.type }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="channel" label="渠道" show-overflow-tooltip width="100px">
          <template #default="scope">
            <span v-for="channel in scope.row.channels" :key="channel">
              {{
                  channels.find(r => r.value == channel) ? channels.find(r => r.value == channel).label : channel
                }}；
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" show-overflow-tooltip width="100px"/>
        <el-table-column prop="password" label="口令" show-overflow-tooltip width="100px">
          <template #default="scope">
            <div v-if="!scope.row.password">/</div>
            <div v-else>{{ scope.row.password }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="数量" show-overflow-tooltip width="100px">
          <template #default="scope">
            <div v-if="!scope.row.num">/</div>
            <div v-else>
              <el-tooltip content="点击打开下载列表" placement="top">
                <el-button @click="open(scope.row)" type="text">{{ scope.row.num }}</el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="times" label="兑换次数" show-overflow-tooltip width="100px"/>
        <el-table-column prop="startTime" label="开始时间" show-overflow-tooltip width="180px"/>
        <el-table-column prop="stopTime" label="结束时间" show-overflow-tooltip width="180px"/>
        <el-table-column prop="rewards" label="奖励内容" show-overflow-tooltip>
          <template #default="scope">
            <span v-for="v in scope.row.rewards" :key="v.itemId">
              名称：{{
                itemConfig.find(r => r.Id === v.itemId) ? itemConfig.find(r => r.Id === v.itemId).Name : v.itemId
              }}，
              数量：{{ v.num }}；
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" show-overflow-tooltip width="80px">
          <template #default="scope">
            <div v-if="new Date(scope.row.startTime) > new Date()" style="color: #a5a5a5">未生效</div>
            <div v-else-if="new Date(scope.row.startTime) < new Date() && new Date(scope.row.stopTime) > new Date()"
                 style="color: #0099ff">
              已生效
            </div>
            <div v-else-if="new Date(scope.row.stopTime) < new Date()" style="color: #e60000">已失效</div>
            <div v-else style="color: #0099ff">已生效</div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" show-overflow-tooltip width="100px">
          <template #default="scope">
            <el-button link size="small" type="text" @click="onEdit(scope.row)">修改
            </el-button>
            <el-button link size="small" type="text" @click="onEnd(scope.row)" style="color: #e60000">停用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row justify="space-evenly">
        <el-pagination :hide-on-single-page="true" v-model:page-size="queryParams.pageSize"
                       v-model:current-page="queryParams.pageNum" :pager-count="5" :total="tableData.total"
                       @current-change="onHandleCurrentChange" layout="total, prev, pager, next"/>
      </el-row>
      <EditConfig ref="editDicRef" @countList="getList"/>
    </el-card>

    <el-dialog v-model="dialogVisible" title="下载列表" width="250px" center>
      <div v-for="k in filenames" :key="k">
        <a :href="baseURL+'download_file?filename='+k" :download="k" target="_blank">{{ k }}</a> <br/><br/>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import {reactive, toRefs, defineComponent, ref, onMounted} from 'vue';
import {gameGiftExchangeList, updateGiftExchange} from '/@/api/game/cdKey';
import AllItemConfigCategory from "/@/api/config/AllItemConfigCategory.json";
import {ElLoading, ElMessageBox} from "element-plus";
import {allChannelList} from "/@/utils/game";
import EditConfig from "/@/views/gameCdKey/list/editConfig.vue";

const baseURL: string | undefined | boolean = import.meta.env.VITE_API_URL

interface TableDataState {
  queryParams: {
    keyType: number,
    channel: string,
    name: string,
    pass: string,
    dates: string[],
    startTime: string,
    stopTime: string,
    states: number,
    pageSize: number,
    pageNum: number,
  }
  tableData: { data: object[], total: number };
  ItemConfig: object;
  channels: object;
  baseURL: string,
  dialogVisible: boolean,
  filenames: string[],
}

export default defineComponent({
  name: 'apiV1GameCdKeyList',
  components: {EditConfig},
  setup: function () {
    const editDicRef = ref();
    const state = reactive<TableDataState>({
      queryParams: {
        keyType: 0,
        channel: "",
        name: "",
        pass: "",
        dates: [],
        startTime: "",
        stopTime: "",
        states: 0,
        pageSize: 10,
        pageNum: 1,
      },
      tableData: {data: [], total: 0},
      itemConfig: AllItemConfigCategory,
      channels: [],
      baseURL: baseURL,
      dialogVisible: false,
      filenames: [],
    });

    onMounted(() => {
      allChannelList().then(res => {
        state.channels = res;
      })
    });
    var getList = () => {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });

      state.queryParams.startTime = state.queryParams.dates[0]
      state.queryParams.stopTime = state.queryParams.dates[1]
      gameGiftExchangeList(state.queryParams).then((res) => {
        if (!res || Number(res.code) != 0 || !res.data) {
          return;
        }
        console.log(res);
        state.tableData.total = res.data.total || 0;
        state.tableData.data = res.data.list;
        state.tableData.data.map(item => {
          item.filenames = item.filename.split(';');
          item.rewards = JSON.parse(item.rewards);
          item.channels = item.channel.split(';');
        })
        console.log(state.tableData);
      }).finally(function () {
        loading.close();
      });
    };
    var onEdit = (row: any) => {
      row.dates = [row.startTime, row.stopTime];
      console.log("onEdit: ", row);
      editDicRef.value.openDialog(row);
    }
    var onEnd = (row: any) => {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      ElMessageBox.confirm(`确定停用${row.name}？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        updateGiftExchange({channel: row.channel, configId: row.id}).then((res) => {
          getList();
          console.log(res);
        })
      }).finally(() => {
        loading.close();
      })
    }
    const open = (row: any) => {
      // console.log(row);
      state.filenames = row.filenames;
      // console.log(state.filenames);
      state.dialogVisible = true;
    }
    // 分页改变
    const onHandleCurrentChange = () => {
      console.log(`current page: ${state.queryParams.pageNum}`);
      getList();
    };
    return {
      editDicRef,
      getList, onEdit, onEnd, open, onHandleCurrentChange,
      ...toRefs(state),
    };
  },
});
</script>

<style scoped lang="scss">

.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;
  }
}

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

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

.table-item {
  margin-top: 10px;
  margin-bottom: -10px;
}

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

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

.warning-row {
  background: #ffffd5;
}

</style>
