<template>
    <v-app>
        <v-data-table :loading="loading" :headers="headers" :items="seasons" item-key="id" :search="search" :items-per-page="5">
            <template v-slot:top>
                <v-toolbar flat>
                    <v-toolbar-title>赛季管理</v-toolbar-title>
                    <v-divider class="mx-3" inset vertical></v-divider>
                    <v-spacer></v-spacer>
                    <v-text-field v-model="search" append-icon="mdi-magnify" label="搜索" single-line
                        hide-details></v-text-field>
                </v-toolbar>
            </template>
            <template v-slot:item.season_id="{ item }">
                <p v-if="item.season_id" style="width:50px">{{ item.season_id }}</p>
            </template>
            <template v-slot:item.season_name="{ item }">
                <p v-if="item.season_name" style="width:50px">{{ item.season_name }}</p>
            </template>
            <template v-slot:item.start_date="{ item }">
                <p v-if="item.start_date" style="width:50px">{{ formatDate(item.start_date) }}</p>
            </template>
            <template v-slot:item.end_date="{ item }">
                <p v-if="item.end_date" style="width:50px">{{ formatDate(item.end_date) }}</p>
            </template>
            <template v-slot:item.season_enable="{ item }">
                <p v-if="item.season_enable" style="width:50px">{{ item.season_enable }}</p>
            </template>
            <template v-slot:item.actions="{ item }">
                <v-btn v-if="item.season_enable" :loading="endLoading" @click="season_end(item)" style="width:50px" variant="text"
                    color="indigo" text="结束赛季"></v-btn>
                <v-btn v-if="!item.season_enable" :loading="restartLoading" @click="season_restart(item)" style="width:50px" variant="text"
                    color="indigo" text="重启赛季"></v-btn>
            </template>
        </v-data-table>
        <div><v-btn style="width: 100px;margin-right: 10px;" class="float-right" variant="text" color="indigo"
                prepend-icon="mdi-scoreboard" @click="dialog = true" text="开启赛季"></v-btn></div>
    </v-app>
    <v-dialog v-model="dialog" width="auto">
        <v-card width="300px">
            <v-card-title>
                开启赛季
            </v-card-title>
            <v-card-text>
                <v-form v-model="isValid">
                    <v-text-field v-model="new_season_name" variant="filled" color="indigo" label="赛季名" :rules="[rules.season]"></v-text-field>
                    <v-btn block @click="date_dialog = true" class="text-none mb-4" color="indigo" size="large"
                        variant="outlined">
                        <template v-slot:default>
                            选择赛季开始日期：{{ selectedDate.toLocaleDateString() }}
                        </template>
                    </v-btn>
                </v-form>
            </v-card-text>
            <template v-slot:actions>
                <v-btn :disabled="!isValid" :loading="startLoading" class="ms-auto" variant="flat" color="indigo" text="确定" @click="season_start"></v-btn>
            </template>
        </v-card>
    </v-dialog>
    <v-dialog v-model="date_dialog" width="auto">
        <v-card>
            <v-locale-provider locale="zhHans">
                <v-date-picker v-model="selectedDate" header="日期" title="选择赛季开始日期" color="indigo"
                    width="100%"></v-date-picker>
            </v-locale-provider>
            <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn variant="flat" text="确定" color="indigo" @click="date_dialog = false"></v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
    <v-dialog v-model="dialog1" width="auto">
        <v-card width="300px">
            <v-card-title>
                {{ cardtitle }}
            </v-card-title>
            <v-card-text>
                {{ cardtext }}
            </v-card-text>
            <template v-slot:actions>
                <v-btn class="ms-auto" variant="flat" color="indigo" text="确认" @click="dialog = false"></v-btn>
            </template>
        </v-card>
    </v-dialog>
</template>

<script setup>
import { ref } from 'vue';
import { reactive } from 'vue';
import axios from 'axios';

const search = ref('');
// const actions_text = ref('');
const headers = reactive([
    { title: 'ID', key: 'season_id' },
    { title: '赛季', key: 'season_name' },
    { title: '开始日期', key: 'start_date' },
    { title: '结束时间', key: 'end_date' },
    { title: '进行中', key: 'season_enable' },
    // { title: '管理员', key: 'is_su' },
    { title: '操作', key: 'actions' },
]);

const rules = reactive({
    email: v => !!(v || '').match(/@/) || 'Please enter a valid email',
    length: len => v => (v || '').length >= len || `Invalid character length, required ${len}`,
    usrname: v => !!v || '用户名不能为空',
    realname: v => !!v || '姓名不能为空',
    confirmpassword: v => v === password.value || '密码不匹配',
    password: v => !!v || '密码不能为空',
    su: v => !!v || '管理员不能为空',
    member: v => !!v || '会员不能为空',
    season: v => !!v || '赛季名不能为空',
    // password: v => !!(v || '').match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/) ||
    //   'Password must contain an upper case letter, a numeric character, and a special character',
    required: v => !!v || 'This field is required',
});
const isValid = ref(false);

const seasons = ref(new Array());
const dialog = ref(false);
const new_season_name = ref('');
const selectedDate = ref(new Date());
const date_dialog = ref(false);
const loading = ref(true);
const endLoading = ref(false);
const restartLoading = ref(false);
const startLoading = ref(false);

const cardtitle = ref(null);
const cardtext = ref(null);
const dialog1 = ref(false);
function info(title, text) {
    cardtitle.value = title;
    cardtext.value = text;
    dialog1.value = true;
}

function formatDate(date) {
    var d = new Date(date),
        month = '0' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    return [year + '/' + month + '/' + day].join(''); // 返回形如 MM/DD 的字符串
}

function refresh() {
    loading.value = true;
    axios.get('/api/seasonInfo')
        .then(function (response) {
            const data = response.data;
            seasons.value.length = 0;
            for (var i = 0; i < data.Seasons.length; i++) {
                const season = ref({
                    season_id: data.Seasons[i].season_id,
                    season_name: data.Seasons[i].season_name,
                    start_date: data.Seasons[i].start_date,
                    end_date: data.Seasons[i].end_date,
                    season_enable: data.Seasons[i].season_enable,
                    // user_is_su: data.Seasons[i].is_su,
                })
                seasons.value[i] = season;
            }
        })
        .catch(function (error) {
            console.log(error);
        })
    loading.value = false;
}

refresh();

function season_end(endSeason) {
    endLoading.value = true;
    axios.post('/api/seasonManage', {
        season_id: endSeason.season_id,
        condition_singal: 1,
    })
        .then(function (response) {
            const data1 = response.data;
            if (data1.status === "FAILED") {
                info("结束失败！", "");
            }
            refresh();
        })
        .catch(function (error) {
            console.log(error);
        })
    endLoading.value = false;
}

function season_restart(restartSeason) {
    restartLoading.value = true;
    axios.post('/api/seasonManage', {
        season_id: restartSeason.season_id,
        condition_singal: -1,
    })
        .then(function (response) {
            const data1 = response.data;
            if (data1.status === "FAILED") {
                info("重启失败！", "");
            }
            refresh();
        })
        .catch(function (error) {
            console.log(error);
        })
    restartLoading.value = false;
}

function season_start() {
    startLoading.value = true;
    axios.post('/api/seasonManage', {
        season_name: new_season_name.value,
        start_date: selectedDate.value.toLocaleDateString(),
        condition_singal: 0,
    })
        .then(function (response) {
            const data1 = response.data;
            if (data1.status === "FAILED") {
                info("开启失败！", "");
            }
            refresh();
            dialog.value = false;
        })
        .catch(function (error) {
            console.log(error);
        })
    startLoading.value = false;
}

</script>