﻿<template>
    <div class="container-fluid">
        <v-data-table v-model="data_table.selected"
                      :items="data_table.list"
                      :search-props="search"
                      item-key="order_no"
                      :options.sync="options"
                      :headers="data_table.header"
                      :footer-props="data_table.footer"
                      :server-items-length="data_table.count"
                      :loading="data_table.loading"
                      :single-select="data_table.singleSelect"
                      show-select
                      hide-default-footer
                      :page.sync="data_table.page"
                      :items-per-page.sync="data_table.pageSize"
                      class="elevation-1">
            <template #item.up_time="{ item }">
                {{ item.up_time|timeString('YYYY/MM/DD') }}
            </template>
            <template #item.u_name="{ item }">
                <a v-if="item.f_num != null && item.activity_num != null" @click="checkInMsg(item)" class="btn btn-outline-secondary btn-sm"><i class="mdi mdi-account-check"></i>報到</a>
                {{ item.u_name }}
            </template>
            <template #item.slot_btn="{ item }">
                <a @click="gotoSignupList(item)" class="btn btn-outline-secondary btn-sm">明細</a>
                <a @click="deleteItem(item)" class="btn btn-outline-secondary btn-sm"><i class="mdi mdi-trash-can"></i>刪除</a>
            </template>
        </v-data-table>
        <v-container>
            <v-row class="align-baseline" wrap>
                <v-col cols="12" md="9">
                    <v-pagination v-model="data_table.page"
                                  :length="pageCount">
                    </v-pagination>
                </v-col>
                <v-col class="text-truncate text-right" cols="12" md="2">
                    共 {{ data_table.count }} 筆, 頁數:
                </v-col>
                <v-col cols="6" md="1">
                    <v-text-field v-model="data_table.page"
                                  type="number"
                                  hide-details
                                  dense
                                  min="1"
                                  :max="pageCount"
                                  @input="data_table.page = parseInt($event, 10)"></v-text-field>
                </v-col>
            </v-row>
        </v-container>
    </div>
</template>

<script>

    module.exports = {
        props: ['formData'],
        data() {
            return {
                this_act:'',
                options: { multiSort: false },
                search_options: { multiSort: false },

                data_table: {
                    loading: true,
                    list: [],
                    selected: [],
                    singleSelect: false,
                    count: 0,
                    page: 1,
                    pageSize: 10,
                    header: [
                        { text: '活動分類', value: 'kindsTxt' },
                        { text: '活動名稱', value: 'subject' },
                        { text: '開始日期', value: 'startDate_solar' },
                        { text: '結束日期', value: 'endDate_solar', align: 'start' },
                        { text: '報名人數', value: 'orderCounts' },
                        { text: '', value: 'slot_btn', sortable: false, align: 'end' }
                    ],
                    footer: {
                        showFirstLastPage: true,
                        itemsPerPageOptions: [5, 10, 20, 30],
                    },
                },
                //列印管理報表
                print_conditions: 'yy',
                print_search: {
                    year: '',
                    month: '',
                    season: '',
                    chk_hasact: false,
                    chk_noact: false,
                    select_act: '',
                    select_actitem: '',

                },
                select_act_list: [],
                select_items: {
                    month: [{
                        text: "請選擇",
                        val: 0
                    },],
                    season: [{
                        text: "請選擇",
                        val: 0
                    },],
                },
                print_dialog: {
                    show: false,
                },
                search_dialog: {
                    controls: {
                        search1: {
                            id: 'search1',
                            title: '國籍',
                            text_prop: 'name_zh',
                            value_prop: 'id',
                            keys: [
                                { id: 'keyword', title: '關鍵字' },
                            ],
                            api_url: HTTP_HOST + 'api/country/GetList',
                            columns: [
                                { id: 'id', title: '代碼' },
                                { id: 'name_en', title: '英文短名稱' },
                                { id: 'name_zh', title: '中文名稱' },
                            ],
                            selected: {},
                            select(item, t) {
                                //console.log("select search1", t);
                                t.search.country = item.id;
                                t.search.country2 = '';
                            }
                        },
                        search2: {
                            id: 'search2',
                            title: '報名活動',
                            text_prop: 'subject',
                            value_prop: 'num',
                            keys: [
                                { id: 'subject', title: '活動名稱', value: '' },
                                { id: 'kindTxt', title: '活動分類' },
                            ],
                            api_url: HTTP_HOST + 'api/activity/GetList',
                            columns: [
                                { id: 'subject', title: '活動名稱' },
                                { id: 'kindTxt', title: '活動分類' },
                            ],
                            selected: {},
                            select(item, t) {
                                t.print_search.select_act = item.num;
                            }
                        },
                        search3: {
                            id: 'search3',
                            title: '活動品項',
                            text_prop: 'subject',
                            value_prop: 'num',
                            keys: [
                                { id: 'subject', title: '項目名稱', value: '' },
                                { id: 'kindTxt', title: '項目分類' },
                                { id: 'num', visible: false },
                            ],
                            api_url: HTTP_HOST + 'api/activity/GetOrderList',
                            columns: [
                                { id: 'subject', title: '項目名稱' },
                                { id: 'kindTxt', title: '項目分類' },
                            ],
                            selected: {},
                            select(item, t) {
                                t.print_search.select_actitem = item.num;
                            }
                        }

                    }, show: false,
                    current: {},
                    list: [],
                    count: 0,
                    page: 1,
                    loading: false,
                    footer: {
                        showFirstLastPage: true,
                        disableItemsPerPage: true,
                        itemsPerPageAllText: '',
                        itemsPerPageText: '',
                    },
                },
                search: {
                    keyin1: '',
                    order_no: '',
                    subject: '',
                    u_name: '',
                    up_time1: '',
                    up_time2: '',
                    actItemTxt: '',
                    introducerTxt: '',
                    activity_num: '',
                    country: '',
                    country2: '',
                    hasPrice: '',
                }
                //報到
                , check_dialog: {
                    show: false,
                },
                check_data: {
                    f_num: 0,
                    u_name: '',
                    activity_num: 0,
                    activity_name: '',
                    qty: 1,
                    status: {
                        text: '',
                        val: 1
                    },
                },
                keyin1_items: [//狀態
                    //{ 
                    //text: "請選擇",
                    //val: 0
                    //},
                ],
            };
        },
        mounted() {
            //this.detalKeyinArray();
            this.search_dialog.current = this.search_dialog.controls.search1 ///default
            if (this.this_act != '')
                this.search.activity_num = this.this_act;
            //this.initPrintSearch();
            //this.initActivity();
            const navEntries = performance.getEntriesByType("navigation");
            const isReload = navEntries.length > 0 && navEntries[0].type === "reload";
            if (isReload) {
                sessionStorage.removeItem("orderpage");
            }
            else {
                const savedPage = parseInt(sessionStorage.getItem('orderpage'));
                if (savedPage) {
                    this.options.page = savedPage;
                }
            }
        },
        watch: {
            options: {
                handler() {
                    this.getDefault()
                },
                deep: true,
            },
            search_options: {
                handler() {
                    this.search_get()
                },
                deep: true,
            },
        },
        methods: {
            gotoSignupList(item) {
                this.$emit('custom-event', { action:'detail', item:item });
            },
            search_show(curr) {
                //console.log("btn_click:", curr, curr.api_url);
                this.search_dialog.current = curr;
                this.search_clear()
                //this.search_get()//清除完自動會重抓, 故取消
                this.search_dialog.show = true;
            },
            search_clear() {
                if (!this.search_dialog.current.keys) return;
                this.search_dialog.current.keys.forEach((t, i) => { t.value = '' })
                this.search_get()
            },
            search_get() {
                if (!this.search_dialog.current.keys) return;
                let api_url = this.search_dialog.current.api_url;
                let keys = this.search_dialog.current.keys;
                //const { page, itemsPerPage } = this.options
                //const { sortBy, sortDesc, page, itemsPerPage } = this.options
                this.search_dialog.page = this.search_options.page ?? 1
                let params = { page: this.search_dialog.page, pageSize: 10 };//url params
                var search = {};//post body
                keys.forEach((t, i) => {
                    search[t.id] = t.value;
                });
                //necessary parameter===
                if (this.search_dialog.current.id == 'search2') {
                    params = { sortBy: 'startDate_solar', sortDesc: true, page: this.search_dialog.page, pageSize: 10 };//url params
                }

                console.log("search_get", api_url, search, params, this.search_options);
                this.search_dialog.loading = true
                axios.post(api_url, search, { params: params })
                    .then(response => {
                        this.search_dialog.list = response.data.list
                        this.search_dialog.count = response.data.count
                        this.search_dialog.loading = false
                    })
                    .catch(error => {
                        console.log(error)
                        this.search_dialog.list = []
                        this.search_dialog.count = 0
                        this.search_dialog.loading = false
                        this.snackbar.text = "錯誤:" + error
                        this.snackbar.show = true
                    })
            },
            search_headers() {
                if (!this.search_dialog.current.columns) return;
                r = [];
                this.search_dialog.current.columns.forEach((t, i) => {
                    r.push({
                        text: t.title,
                        align: 'start',
                        sortable: false,
                        value: t.id,
                    })
                })
                return r
            },
            search_select(row) {
                let curr = this.search_dialog.current;
                let target = $(`[data-search-control=${curr.id}]`);
                curr.selected = row;
                target.children("input.search-text").val(curr.selected[curr.text_prop])//text
                target.children("input:hidden").val(curr.selected[curr.value_prop])//value
                if (curr.select instanceof Function) {
                    curr.select(row, this);
                }
                this.search_dialog.show = false;
                //console.log(row, row["u_name"], row["f_number"], curr.id, target);
            },
            getDetail(clearpage = false) {
                console.log("test");
                const { sortBy, sortDesc, page, itemsPerPage } = this.options
                const params = {
                    sortBy: sortBy[0], sortDesc: sortDesc[0],
                    page: clearpage ? '1' : page, pageSize: itemsPerPage
                };
                this.detail_table.loading = true
                sessionStorage.setItem('orderpage', clearpage ? '1' : page);
                axios
                    //.post(HTTP_HOST + 'api/order/GetList', this.search, { params: params })
                    .post(HTTP_HOST + 'api/order/GetList', this.search, { params: params })
                    .then(response => {
                        this.detail_table.list = response.data.list
                        this.detail_table.count = response.data.count;
                        this.detail_table.loading = false
                    })
                    .catch(error => console.log(error))
            },
            getDefault(clearpage = false) {
                const { sortBy, sortDesc, page, itemsPerPage } = this.options
                const params = {
                    sortBy: sortBy[0], sortDesc: sortDesc[0],
                    page: clearpage ? '1' : page, pageSize: itemsPerPage
                };
                this.data_table.loading = true
                sessionStorage.setItem('orderpage', clearpage ? '1' : page);
                axios
                    //.post(HTTP_HOST + 'api/order/GetList', this.search, { params: params })
                    .post(HTTP_HOST + 'api/activity/GetList', this.search, { params: params })
                    .then(response => {
                        this.data_table.list = response.data.list
                        this.data_table.count = response.data.count;
                        this.data_table.loading = false
                    })
                    .catch(error => console.log(error))
            },
    editItem(item) {
        console.log("edit", item);
    },
    deleteItem(item) {
        if (confirm('是否確定刪除此筆資料?')) {
            const index = this.data_table.list.indexOf(item)
            if (index != -1) {
                axios
                    .delete(HTTP_HOST + 'api/order/' + item.order_no)
                    .then(response => {
                        console.log("del", item);
                        this.data_table.list.splice(index, 1);
                        this.data_table.count = this.data_table.list.length
                    })
                    .catch(error => console.log(error))
            }
        }
    },
    deleteAll() {
        if (confirm('是否確定刪除已勾選的資料?')) {
            axios
                .delete(HTTP_HOST + 'api/order/DeleteAll/' + this.data_table.selected.map(x => x.order_no))
                .then(response => {
                    //console.log("delAll");

                    //for (var i = 0; i < this.data_table.selected.length; i++) {
                    //    const index = this.data_table.list.indexOf(this.data_table.selected[i]);
                    //    this.data_table.list.splice(index, 1);
                    //}
                    //this.data_table.selected = [];
                    //this.data_table.count = this.data_table.list.length
                    location.reload();
                })
                .catch(error => console.log(error))
        }
    },
    btn_search() {
        this.this_act = '';
        this.search.activity_num = '';

        this.getDefault(true)
    },
    btn_all() {
        this.this_act = '';
        this.search.activity_num = '';
        clearObjProps(this.search);
        this.btn_search()
    },
    checkInMsg(item) {
        this.check_data.f_num = item.f_num;
        this.check_data.u_name = item.u_name;
        this.check_data.activity_num = item.activity_num;
        this.check_data.activity_name = item.subject;
        this.check_dialog.show = true;
    },
    checkIn() {
        if (this.check_data.qty > 0 && this.check_data.status.val > 0) {
            var chechdata =
            {
                f_num: this.check_data.f_num,
                activity_num: this.check_data.activity_num,
                status: this.check_data.status.val,
                qty: this.check_data.qty,
            }
            axios
                .post(HTTP_HOST + 'api/activity/OrderCheckIn', chechdata)
                .then(response => {
                    //清空
                    this.check_data.f_num = 0;
                    this.check_data.u_name = '';
                    this.check_data.activity_num = 0;
                    this.check_data.activity_name = '';
                    this.check_data.qty = 1;
                    this.check_data.status.text = '';
                    this.check_data.status.val = 1;

                    this.check_dialog.show = false;
                    msgtop('簽到成功')
                })
                .catch(
                    error => {
                        console.log(error)
                        msgtop('簽到失敗', 'error')
                    }
                )
        } else {
            msgbox('報到資訊請填寫完整');
        }
    }, goPrint() {
        let _qry = "";
        Object.keys(this.search).forEach(key => {
            //console.log(`${key}: ${this.search[key]}`);
            if (this.search[key] != undefined && this.search[key] != null && this.search[key] != '') {
                _qry += (_qry != '' ? '&' : '?') + (key + '=' + this.search[key]);
            }
        });
        window.open("print.aspx" + _qry, '_blank');
    },
    countryChange() {
        this.search.country = '';
        $('#country_txt').val('')
    },
    //列印管理報表
    print_close() {
        this.print_dialog.show = false;
    }
      ,
    initPrintSearch() {
        //下拉選單
        for (let i = 1; i <= 12; i++) {
            var _tmp = {
                text: i,
                val: i,
            }
            this.select_items.month.push(_tmp);
        }
        for (let i = 1; i <= 4; i++) {
            var _tmp = {
                text: i,
                val: i,
            }
            this.select_items.season.push(_tmp);
        }

        //預設值
        const Today = new Date();//現在日期時間
        const first_date = new Date(Today.getFullYear(), Today.getMonth(), 1); //本月第一天
        const last_month_date = new Date(first_date - 1); //上個月最後一天

        this.print_search.year = last_month_date.getFullYear();
        this.print_search.month = last_month_date.getMonth() + 1 //預設上個月的年份

        let _season = 1;
        const _month = first_date.getMonth() + 1; //本月
        if (_month >= 1 && _month <= 3) {
            _season = 4;
        } else if (_month >= 4 && _month <= 6) {
            _season = 1;
        } else if (_month >= 7 && _month <= 9) {
            _season = 2;
        } else if (_month >= 10 && _month <= 12) {
            _season = 3;
        }
        this.print_search.season = _season; //預設上一季

    },
    goPrint2() {
        if (this.print_search.year != '') {
            if (this.print_search.chk_noact || this.print_search.chk_hasact) {
                let _qry = "";
                Object.keys(this.print_search).forEach(key => {
                    if (this.print_search[key] != undefined && this.print_search[key] != null && this.print_search[key] != '') {
                        if (key == 'month') {
                            if (this.print_conditions == 'mm') {
                                _qry += "&month=" + this.print_search.month;
                            }
                        } else if (key == 'season') {
                            if (this.print_conditions == 'ss') {
                                _qry += "&season=" + this.print_search.season;
                            }
                        }
                        else {
                            _qry += (_qry != '' ? '&' : '?') + (key + '=' + this.print_search[key]);
                        }
                    }
                });

                this.print_dialog.show = false;
                window.open("print.aspx" + _qry, '_blank');
            } else {
                msgbox('活動/非活動至少勾選一項');
            }


        } else {
            msgbox('請輸入年份');
        }

    }, chk_hasact_change() {
        if (!this.print_search.chk_hasact) {
            //$('#activity_num_txt').val('')
            //this.print_search.select_act = '';
            this.clear_select_act();
            $('#activity_num_txt').attr("placeholder", "可選擇單一活動(需先勾選活動報名)");
        } else {
            $('#activity_num_txt').attr("placeholder", "可選擇單一活動");
        }

    },
    clear_select_act() {
        $('#activity_num_txt').val('')
        this.print_search.select_act = '';
    }, clear_select_actitem() {
        $('#actItem_num_txt').val('')
        this.print_search.select_actitem = '';
    },
    initActivity() {
        axios.get(HTTP_HOST + 'api/activity')
            .then(response => {
                this.select_act_list = response.data
            })
            .catch(error => {
                console.log(error)
            })
    }
  },
        computed: {
            pageCount() {
                return Math.ceil(this.data_table.count / this.data_table.pageSize)
            },
        }
    };

</script>