<template>
    <div class="center-line workbenches">
        <div class="center-align" style="width: 100%; margin: 0 20px;">
            <div class="box-card-num1 center-line">
                <div>总数量: <span>{{ hostData.totalCount }}</span></div>
                <div>有效主播: <span>{{ hostData.validAnchorsCount }}</span></div>
                <div> 已查询: <span>{{ hostData.checkedDataCount }}</span></div>
                <div>可邀请: <span>{{ hostData.canInvitationCount }}</span></div>

            </div>
            <div class="center-line" style="padding-top: 15vh;">
                <el-button class="open-login" type="primary" @click="openTK">开启tk</el-button>
            </div>

            <div>

                <el-card class="box-card-num" v-for="(item, index) in 2" :key="index">
                    <div class="center-justify">
                        <div class="from-input-item">
                            <div class="from-input-item-title center-justify">
                                公会账号：
                            </div>
                            <el-input :disabled="!(isTk && tkData[index].code == 0)" v-model="tkData[index].account"
                                style="height: 50px;" placeholder="请输入登录账号" clearable />
                        </div>

                        <div class="from-input-item">
                            <div class="from-input-item-title center-justify">
                                公会密码：
                            </div>
                            <el-input :disabled="!(isTk && tkData[index].code == 0)" v-model="tkData[index].password"
                                style="height: 50px;" type="password" placeholder="请输入登录密码" show-password />
                        </div>

                        <el-button class="open-login" style="margin-left: 60px;"
                            :disabled="!(isTk && tkData[index].code == 0)" type="primary"
                            @click="loginTK(index)">登录tk</el-button>
                        <div v-if="tkData[index].code == 0" class="loginState"></div>
                        <div v-if="tkData[index].code == 1" class="loginState" style="background-color: green;"></div>

                    </div>
                    <div class="todayCount">今日已查询次数：{{ tkData[index].num }}</div>
                </el-card>

            </div>
        </div>

        <div class="container ">

            <el-card class="box-card">
                <template #header>
                    <div class="card-header">
                        <span class="center-justify"><img src="@/assets/worklogo.png">工作台 </span>
                        <div style="margin-right: 120px;">当前网络:{{ countryData }}
                            <!-- <el-button class="reset-button" @click="reset">重置数据</el-button> -->
                        </div>
                    </div>
                </template>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <div class="input-group">
                            <label>设置金币数量</label>
                            <el-input type='number' v-model="pyData.gold.min" :min="0" :max="pyData.gold.max - 1"
                                placeholder="最小值" style="width: 100%" :disabled="!pyData.isStart">
                                <template #prepend>最小金币数</template>
                            </el-input>
                            <el-input type='number' v-model="pyData.gold.max" :min="pyData.gold.min + 1" :max="100"
                                placeholder="最大值" style="width: 100%; margin-top: 10px" :disabled="!pyData.isStart">
                                <template #prepend>最大金币数</template>
                            </el-input>
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <div class="input-group">
                            <label>设置粉丝数量</label>
                            <el-input type='number' v-model="pyData.fans.min" :min="0" :max="pyData.fans.max - 1"
                                placeholder="最小值" style="width: 100%" :disabled="!pyData.isStart">
                                <template #prepend>最小粉丝数</template>
                            </el-input>
                            <el-input type='number' v-model="pyData.fans.max" :min="pyData.fans.min + 1" :max="100"
                                placeholder="最大值" style="width: 100%; margin-top: 10px" :disabled="!pyData.isStart">
                                <template #prepend>最大粉丝数</template>
                            </el-input>
                        </div>
                    </el-col>
                    <el-col :span="8">
                        <div class="input-group">
                            <label>后台查询频率</label>
                            <el-input type='number' v-model="pyData.frequency.hour" :min="0"
                                :max="pyData.frequency.day - 1" placeholder="次/小时" style="width: 100%"
                                :disabled="!pyData.isStart">
                                <template #append>次/小时</template>
                            </el-input>
                            <el-input type='number' v-model="pyData.frequency.day" :min="pyData.frequency.hour + 1"
                                :max="100" placeholder="次/24小时" style="width: 100%; margin-top: 10px"
                                :disabled="!pyData.isStart">
                                <template #append>次/24小时</template>
                            </el-input>
                        </div>
                    </el-col>
                </el-row>
                <div style="margin-top: 20px; text-align: center">

                    <el-button class="submit-button" :disabled="submitting" v-show="pyData.isStart" type="primary"
                        @click="submit">开始获取数据</el-button>
                    <el-button v-show="!pyData.isStart" type="danger" @click="unsubmit">停止获取</el-button>

                </div>

            </el-card>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { usePythonBridge, } from '@/utils/pythonBridge'
import { setNumData, getNumData, getUser, setTkUser, getTkUser } from '@/utils/storage'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCountryName } from '@/utils/countryUtil'
import { tkaccountuseinfo } from '@/api/account'
//导入python交互方法
const { fetchDataConfig, fetchDataCount, loginBackStage, loginTikTok, backStageloginStatus, backStageloginStatusCopy } = usePythonBridge();

//ip国家
let countryData = ref('');
//获取主播数量的定时器
let getHostTimer = ref(null);
//获取的主播信息
let hostData = ref({
    totalCount: 0,
    validAnchorsCount: 0,
    canInvitationCount: 0,
    checkedDataCount: 0,

});
//是否开启tk
let isTk = ref(true);

//设置状态轮询定时器
let statusTimer = ref(null);
let statusTimerCopy = ref(null);


//tk账号信息
let tkData = ref([
    {
        account: '',
        password: '',
        index: 1,
        code: 0,
        num: 0
    },
    {
        account: '',
        password: '',
        index: 2,
        code: 0,
        num: 0

    },

]);

//python需要的数据
let pyData = ref({
    gold: { min: 0, max: 0 },
    fans: { min: 0, max: 0 },
    frequency: { hour: 0, day: 0 },
    isStart: true,
    country: countryData.value,
    test: '123',
    test1: { test: 123, test12: 123 },
    tenantId: getUser().tenantId,
    userId: getUser().userId,
});

//按钮提交状态
let submitting = ref(false);

onMounted(() => {
    //从缓存获取数据
    if (getNumData()) {
        pyData.value = getNumData();
    }
    if (getTkUser()) {
        tkData.value = getTkUser();
        tkData.value[0].code = 0;
        tkData.value[1].code = 0;
    }

    tkaccountuse(tkData.value[0].account, 0)
    tkaccountuse(tkData.value[1].account, 1)

    getIpInfo()
    //查询次数查询


})

const getIpInfo = async () => {
    try {
        const response = await fetch('https://ipapi.co/json/');
        if (!response.ok) {
            throw new Error('请求失败');
        }
        const data = await response.json();
        console.log('IP信息:', data.country);

        countryData.value = getCountryName(data.country);
    } catch (error) {
        console.error('请求出错:', error);
    }
};

//提交数据到py
const submit = () => {
    pyData.value.country = countryData.value;
    console.log('提交的区间值：', pyData.value);
    if (tkData.value[0].account == '' || tkData.value[1].account == '') {
        ElMessage.error('请输入账号密码');
        return;
    }
    if (tkData.value[0].password == '' || tkData.value[1].password == '') {
        ElMessage.error('请输入账号密码');
        return;
    }
    ElMessageBox.confirm(
        '确认开始爬取数据?',
        '开始',
        {
            confirmButtonText: '开始',
            cancelButtonText: '取消',
            type: 'success',
        }
    )
        .then(() => {
            // console.log('提交的区间值：', pyData.value.gold, pyData.value.fans, pyData.value.frequency);
            //开始按钮的状态  改为禁用
            submitting.value = true;
            setNumData(pyData.value);
            console.error('提交的区间值：', JSON.stringify(pyData.value));

            fetchDataConfig(JSON.stringify({
                gold: pyData.value.gold,
                fans: pyData.value.fans,
                frequency: pyData.value.frequency,
                isStart: true,
                country: countryData.value,
                tenantId: getUser().tenantId,
                userId: getUser().userId,
            })).then((res) => {

                getHostTimer.value = setInterval(() => {
                    fetchDataCount().then((res) => {
                        hostData.value = JSON.parse(res);
                    })
                }, 1000);


            }).finally(() => {
                setTimeout(() => {
                    pyData.value.isStart = false;
                    submitting.value = false;
                }, 2000)

            })
        })
        .catch(() => {

        })



};

//停止
const unsubmit = () => {
    fetchDataConfig(JSON.stringify({
        gold: pyData.value.gold,
        fans: pyData.value.fans,
        frequency: pyData.value.frequency,
        isStart: false,
        country: countryData.value,
        tenantId: getUser().tenantId,
        userId: getUser().userId,
    })).then((res) => {
        pyData.value.isStart = true;
        clearInterval(getHostTimer.value);
        getHostTimer.value = null;
        // ElMessage.sussec('已停止')
    }).catch((err) => {
        // ElMessage.error('停止失败')
    })
};

//重置
const reset = () => {
    pyData.value.gold = { min: 0, max: 0 };
    pyData.value.fans = { min: 0, max: 0 };
    pyData.value.frequency = { hour: 0, day: 0 };
};


const loginTK = (index) => {
    setTkUser(tkData.value)
    loginBackStage({
        account: tkData.value[index].account,
        password: tkData.value[index].password,
        index: index
    })
    if (index == 0) {
        statusTimer = setInterval(() => {
            getloginStatus();
        }, 2000)
    } else if (index == 1) {
        statusTimerCopy = setInterval(() => {
            getloginStatusCopy();
        }, 2000)
    }


}

const openTK = () => {
    isTk.value = true;
    console.log(isTk.value)
    loginTikTok();

}

function getloginStatus() {
    backStageloginStatus().then((res) => {
        const data = JSON.parse(res);
        tkData.value[data.index].code = data.code

        if (data.code == 1) {
            clearInterval(statusTimer);
            statusTimer = null;
        }
    })
}
function getloginStatusCopy() {
    backStageloginStatusCopy().then((res) => {
        const data = JSON.parse(res);
        tkData.value[data.index].code = data.code

        if (data.code == 1) {
            clearInterval(statusTimer);
            statusTimer = null;
        }
    })
}


function tkaccountuse(id, index) {
    let num = 0;
    tkaccountuseinfo({ userId: id }).then((res) => {
        num = res
        tkData.value[index].num = num
        console.log('账号使用次数', tkData.value[index].num)
    })

}
</script>

<style scoped lang="less">
.container {
    margin: 0 auto;
}

.workbenches {
    padding: 45px 29px 22px 27px;

    /* 页面无法选中 */
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;


}

.box-card {
    // width: 1240px;
    height: 436px;
    background: #FFFFFF;
    box-shadow: 0px 0px 21px 0px rgba(183, 183, 183, 0.33);
    border-radius: 24px;
}

.box-card-num1 {

    width: 197px;
    height: 321px;
    background: #FFFFFF;
    box-shadow: 0px 0px 21px 0px rgba(183, 183, 183, 0.33);
    border-radius: 24px;
    padding-top: 60px;
    box-sizing: border-box;

    div {
        height: 20%;
        display: flex;
        justify-content: space-around;
        align-items: center;

        color: #8D8E8E;

        span {
            color: #000;
            padding-left: 10px;
        }
    }
}

.box-card-num {
    width: 897px;
    height: 145px;
    background: #FFFFFF;
    box-shadow: 0px 0px 21px 0px rgba(183, 183, 183, 0.33);
    border-radius: 24px;
    margin-bottom: 30px;

    padding-top: 18px;
    box-sizing: border-box;

    .todayCount {
        padding: 15px 21px;
        font-size: 14px;
    }
}

.from-input-item {
    display: flex;

    .from-input-item-title {
        color: #000000;
        font-size: 14px;
        font-weight: 500;
        width: 100px;
        height: 50px;
    }

    .loginButton {
        width: 100%;
        height: 40px;
        color: #ffffff;
        font-size: 16px;

    }
}


.loginState {
    width: 15px;
    height: 15px;
    border-radius: 50%;
    background-color: #b90000;
    margin-left: 15px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
        font-family: Source Han Sans SC;
        font-weight: 400;
        font-size: 20px;
        color: #2D2727;
        line-height: 37px;

        img {
            margin-right: 16px;
        }
    }
}

.input-group {
    margin-bottom: 20px;

    .el-input {
        margin: 22px 0;
    }
}

label {
    display: block;
    margin-bottom: 8px;
    font-weight: bold;
    color: #606266;
}

.open-login {
    width: 100px;
    height: 47px;
    background: #E7CA92;
    border-radius: 10px;
    border: none;
}

.reset-button {
    width: 132px;
    height: 47px;
    background: #E7CA92;
    border-radius: 10px;

    font-family: Source Han Sans SC;
    font-weight: 400;
    font-size: 18px;
    color: #FFFFFF;

    margin-left: 50px;
}

.submit-button {
    width: 160px;
    height: 47px;
    background: #338F6A;
    border-radius: 10px;
}

.center-line {
    display: flex;
    flex-direction: column;
    align-items: center;
    // justify-content: center;
}

.center-justify {
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.center-align {
    display: flex;
    justify-content: space-between;

}

.center-flex {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>


<style scoped>
::v-deep(.el-input-group__prepend) {
    background: #84CEB2;
    border-radius: 10px 0px 0px 10px;
    border: 1px solid #B7CEC5;
    font-family: Source Han Sans SC;
    font-weight: 400;
    font-size: 18px;
    color: #FFFFFF;
    line-height: 37px;
}

::v-deep(.el-input-group__append) {
    background: #84CEB2;
    border-radius: 0px 10px 10px 0px;
    border: 1px solid #B7CEC5;
    font-family: Source Han Sans SC;
    font-weight: 400;
    font-size: 18px;
    color: #FFFFFF;
    line-height: 37px;
}

::v-deep(.el-input__wrapper) {
    width: 218px;
}

.el-input {
    width: 200px;
    height: 48px;
    background: #FFFFFF;
    border-radius: 10px;
    border: 1px solid #B7CEC5;
}
</style>