<template>
    <view class="charts-card uni-row2">
        <view class="charts-header">
            <view class="charts-title">{{typeMap.find(item => item.value === search.type)?.text}}</view>
            <uni-datetime-picker type="daterange" v-model="search.date"
                :placeholder="t('placeholder.Start') + ' - ' + t('placeholder.End')" @change="handleDateChange" />
        </view>
        <view class="charts-account" v-if="search.login">
            <text v-t="'Label.TradingAccount'"></text>
            <text> - </text>
            <text>{{ search.login }}</text>
        </view>
        <view class="search-bar">
            <cwg-combox v-model:value="search.type" :clearable="false" :options="typeMap"
                :placeholder="t('Label.ChartType')" />
            <cwg-combox v-model:value="search.platform" :clearable="false" :options="platformMap"
                :placeholder="t('Label.PlatformType')" />
            <cwg-combox v-model:value="search.login" :clearable="false" :options="loginOptions"
                :placeholder="t('Label.TradingAccount')" />
            <view class="s-btn" @click="getChart" v-t="'Btn.Confirm'" />
        </view>
        <view class="charts-box">
            <cwg-charts type="column" :chartData="chartsDataColumn1" :echartsH5="true" :echartsApp="true"
                @complete="complete" />
        </view>
    </view>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, watch } from 'vue';
import { useI18n } from 'vue-i18n';
const { t, locale } = useI18n();
import { customApi } from '@/service/custom';
import useUserStore from "@/stores/use-user-store";
import useRouter from "@/hooks/useRouter";
import { start } from 'repl';
const router = useRouter();
const search = ref({
    type: 4,
    platform: 'MT4',
    login: null,
    date: [],
    startDate: null,
    endDate: null
})
const typeMap = computed(() => ([
    { value: 4, text: t('Custom.Index.TradingVolumeStatistics') },
    { value: 2, text: t('Custom.Index.DepositStatistical') },
    { value: 3, text: t('Custom.Index.WithdrawalsStatistical') },
    { value: 6, text: t('Custom.Index.ProfitLoss') },
]));
const platformMap = computed(() => ([
    { value: 'MT4', text: 'MT4' },
    { value: 'MT5', text: 'MT5' }
]));
const loginOptions = ref([])
const getAccountList = async () => {
    let res = await customApi.CustomDropdown({
        platform: search.value.platform
    });
    if (res.code == 200) {
        loginOptions.value = res.data.map(item => ({
            value: item.login,
            text: item.login
        }))
    } else {
        loginOptions.value = []
    }
}
const flag = ref(false) // 防止重复请求

const handleDateChange = (val) => {
    search.value.startDate = val[0]
    search.value.endDate = val[1]
    getChart()
}
//获取图表信息
const getChart = async () => {
    if (flag.value) {
        return;
    } else {
        flag.value = true;
    }
    // chartDates.value = [];
    // chartTimes.value = [];
    let res = await customApi.getChartInfo({
        ...search.value,
    });
    if (res.code == 200) {
        // res.data.forEach((item) => {
        //   chartDates.value.push(item.amount);
        //   chartTimes.value.push(item.date.split(" ")[0]);
        // });
        // drawLine();
        // $pigeon.MessageOK($i18n.t("Msg.SearchSuccess"));
        flag.value = false;
    } else {
        flag.value = false;
    }
}
const chartsDataColumn1 = ref({
    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    series: [
        {
            name: 'Promotion A',
            data: [29, 71, 106, 129, 144, 176, 135, 148, 216, 194, 95, 54]
        },
        {
            name: 'Promotion B',
            data: [39, 81, 116, 139, 154, 186, 145, 158, 226, 204, 105, 64]
        }
    ]
})
const complete = (e) => {
    console.log("渲染完成事件", e);
}
const time = ref('')
const getDate = () => {
    let timezone = 2; //目标时区时间，东2区   东时区正数 西市区负数
    let offset_GMT = new Date().getTimezoneOffset(); // 本地时间和格林威治的时间差，单位为分钟
    let nowDate = new Date().getTime(); // 本地时间距 1970 年 1 月 1 日午夜（GMT 时间）之间的毫秒数
    let now = new Date(
        nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000
    );

    //当前时间
    let month = now.getMonth() + 1; //月
    let day = now.getDate(); //日
    let hh = now.getHours(); //时
    let mm = now.getMinutes(); //分
    let clock;
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    if (hh < 10) {
        hh = "0" + hh;
    }
    if (mm < 10) {
        mm = "0" + mm;
    }
    clock = "  " + hh + ":" + mm + "  " + month + "/" + day;
    time.value = clock;
}
// 设置默认日期
const setDefaultDate = () => {
    // 先置空
    search.value.date = []

    // 使用 setTimeout 确保在下一个事件循环赋值
    setTimeout(() => {
        search.value.date = [search.value.startDate, search.value.endDate];
    }, 0)
}
const goTime = () => {
    getDate();
    let timezone = 2; //目标时区时间，东2区   东时区正数 西市区负数
    let offset_GMT = new Date().getTimezoneOffset(); // 本地时间和格林威治的时间差，单位为分钟
    let nowDate = new Date().getTime(); // 本地时间距 1970 年 1 月 1 日午夜（GMT 时间）之间的毫秒数
    let data = new Date(
        nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000
    );
    //当月第一天和最后一天
    let mon1 = data.setDate(1); //当月第一天
    let mon2 = data.setMonth(data.getMonth() + 1); //下月
    let y1 = new Date(mon1).getFullYear();
    let m1 = new Date(mon1).getMonth() + 1;
    let d1 = new Date(mon1).getDate();
    let y2 = new Date(mon2).getFullYear();
    let m2 = new Date(mon2).getMonth() + 1;
    let d2 = 1;
    search.value.startDate =
        y1 + "-" + (m1 < 10 ? "0" + m1 : m1) + "-" + (d1 < 10 ? "0" + d1 : d1);
    search.value.endDate =
        y2 + "-" + (m2 < 10 ? "0" + m2 : m2) + "-" + (d2 < 10 ? "0" + d2 : d2);
    setDefaultDate();
    console.log(search.value.date);

    getChart();
}
watch(() => search.value.platform, () => {
    loginOptions.value = []
    search.value.login = null
    getAccountList()
})
onMounted(() => {
    getAccountList()
    goTime()
})
</script>

<style scoped lang="scss">
@import "@/uni.scss";

.charts-card {
    width: 100%;
    padding: px2rpx(12);
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;

    .charts-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: px2rpx(38);

        .uni-date {
            width: px2rpx(264) !important;
            flex: none;
        }
    }

    .charts-title {
        font-size: px2rpx(21);
        font-weight: 500;
        color: var(--bs-emphasis-color);
    }

    .charts-account {
        margin-top: px2rpx(16);
        font-size: px2rpx(16);
        font-weight: 700;
        color: var(--color-error);
    }

    .charts-box {
        width: 100%;
        height: px2rpx(300);
    }
}
</style>