<template>
    <PageHeader :title="title">
        <template #content>
            <Table border :columns="columns" :data="usbInfo.arr" width="800">
                <template #info="{ row }">
                    <p v-for="item in row.info">{{ item }}</p>
                </template>
                <template #status="{ row }">
                    <div v-if="row.status">
                        <Icon type="md-analytics" color="#19be6b" /><span>已连接</span>
                    </div>
                    <div v-else>
                        <Icon type="ios-alert" color="#ed4014" /><span>未连接</span>
                    </div>
                </template>
                <template #edit="{ row }">
                    <Button v-if="!row.status" @click="bindusb(row.key)">绑定</Button>
                </template>
            </Table>
        </template>
        <template #extra>
            <div>
                <div style="text-align: center">
                    <span style="color: #17233d;margin-right: 10px;">远端状态:</span>
                    <div v-if="connectSatus" style="display: inline;">
                        <span style="margin-right: 10px;color: #19be6b;">连接中</span>
                        <Button size="small" type="info" @click="killssh">断开连接</Button>
                    </div>
                    <div v-else style="display: inline;">
                        <Icon type="md-warning" color="#ed4014" size="25" /><span style="color: #ed4014;">未连接</span>
                    </div>
                </div>
                <div v-if="!connectSatus">
                    <div>
                        <span style="color: #17233d;margin-right: 10px;">连接命令:</span>
                        <span style="margin-right: 10px;">ssh -N -R 3240:localhost:3240 root@192.168.11.185</span>
                        <Button size="small" style="margin-right: 10px;" type="info" @click="copyinfo('connect')">复制</Button>
                    </div>
                    <div style="text-align: center;">
                        <Button size="small" style="margin-top: 5px;margin-right: 10px;" type="info"
                            @click="copyinfo('connectPass')">复制连接密码</Button>
                    </div>
                </div>
                <div style="text-align: center;margin-top: 5px;">
                    <div v-if="connectSatus">
                        <span style="color: #17233d;margin-right: 10px;">appium:</span>
                        <div v-if="appiumStatus" style="display: inline;">
                            <span style="margin-right: 10px;color: #19be6b;">已启动</span>
                            <Button size="small" style="margin-right: 10px;" type="info" @click="restartAppium"
                                :disabled="canRestartAppium">重启</Button>
                            <Button size="small" type="info" @click="tailLog">查看日志</Button>
                        </div>

                        <div v-else style="display: inline;">
                            <span style="margin-right: 10px;color: #19be6b;">未启动</span>
                            <Button size="small" type="info" @click="startAppium" :disabled="canRestartAppium">启动</Button>
                        </div>
                        <div v-if="appiumStatus" style="margin-top: 5px;">
                            <span style="color: #17233d;margin-right: 10px;">appium远程主机:</span>
                            <span style="margin-right: 10px;">192.168.11.185</span>
                            <Button size="small" style="margin-right: 10px;" type="info" @click="copyinfo('appiumHost')">复制</Button>
                        </div>
                        <div v-if="appiumStatus" style="margin-top: 5px;">
                            <span style="color: #17233d;margin-right: 10px;">appium远程端口:</span>
                            <span style="margin-right: 10px;">4567</span>
                            <Button size="small" style="margin-right: 10px;" type="info" @click="copyinfo('appiumPort')">复制</Button>
                        </div>
                    </div>
                </div>
            </div>
        </template>
    </PageHeader>
    <div v-if="usbInfo.arr.filter(item => item.status == 1).length">
        <Row style="margin-top: 20px;">
            <Col :span="phoneStyle.android.span" :offset="phoneStyle.android.offset">
            <div v-if="selectSystem == 0 || selectSystem == 1" class="phone">
                <Icon style="margin-top: 50px;" type="logo-android" size="100" color="#19be6b" />
                <p v-if="!androidConnectInfo.adbinfo" style="color: #ff9900;">请确保已打开usb调试模式</p>
                <Button v-if="selectSystem == 0" style="margin-top: 30px;" @click="connectAndroid">连接</Button>
                <p v-if="androidConnectInfo.adbinfo" style="font-size: 20px;color:#2d8cf0">adb信息</p>
                <p v-if="androidConnectInfo.adbinfo">{{ androidConnectInfo.adbinfo }}</p>
                <p v-if="Object.getOwnPropertyNames(androidConnectInfo.appiumArgs).length"
                    style="font-size: 20px;color:#2d8cf0">appium连接参数</p>
                <div style="background-color: #19be6b;margin-left: 5px;margin-right: 5px;margin-top: 10px;">
                    <div v-for="v, k in androidConnectInfo.appiumArgs">
                        <p><span style="color: blueviolet; margin-right: 5px;">{{ k }}:</span>
                            <Tooltip v-if="getlowV(k, v)[0]" content="Top Center text" placement="top"><span>{{
                                getlowV(k, v)[1] }}</span></Tooltip><span v-else>{{ getlowV(k, v)[1] }}</span>
                        </p>
                    </div>
                </div>
                <p>
                    <Icon v-if="(!androidConnectInfo.adbinfo || !androidConnectInfo.appiumArgs) && selectSystem == 1"
                        type="ios-loading" class="ivu-anim-loop" size="24" />
                </p>
                <div>
                    <Button style="margin-right: 5px;margin-top: 10px;"
                        v-if="Object.getOwnPropertyNames(androidConnectInfo.appiumArgs).length"
                        @click="copyappiumconn">复制参数</Button>
                    <Button v-if="selectSystem == 1" style="margin-top: 10px;" @click="disconnectAndroid">断开连接</Button>
                </div>
                <div>
                    <Button style="margin-right: 5px;margin-top: 10px;"
                        v-if="Object.getOwnPropertyNames(androidConnectInfo.appiumArgs).length"
                        @click="setAppuimInfo">修改参数</Button>
                    <Button v-if="Object.getOwnPropertyNames(androidConnectInfo.appiumArgs).length"
                        style="margin-top: 10px;" @click="disconnectAndroid" disabled>运行脚本</Button>
                </div>

            </div>
            </Col>
            <Col :span="phoneStyle.ios.span" :offset="phoneStyle.ios.offset">
            <div v-if="selectSystem == 0 || selectSystem == 2" class="phone" style="border-color: #c5c8ce;">
                <Icon style="margin-top: 50px;" type="logo-apple" size="100" color="#808695" />
                <Input v-model="webdriveragentId" placeholder="请输入webdriveragentId" style="width: 200px;" />
                <Button v-if="selectSystem == 0" style="margin-top: 10px;" @click="connectIos" disabled>连接</Button>
                <p style="color: #ed4014;">最新版的ios连接不稳定，尚在调试和寻找处理方法</p>
                <p>
                    <Icon v-if="selectSystem == 2 && !iosConnectInfo?.IosId" type="ios-loading" class="ivu-anim-loop"
                        size="24" />
                </p>
                <p v-if="iosConnectInfo?.IostestResult == 1" style="color: #ff9900;">请在设备上信任!!</p>
                <p v-if="iosConnectInfo?.IostestResult == 3" style="color: #ed4014;">设备的WDAid与实际安装的不一致或WDAid已过期</p>
                <p v-if="iosConnectInfo?.IostestResult == 4" style="color: #ed4014;">设备连接异常</p>
                <div v-if="iosConnectInfo?.IostestResult == 2"
                    style="background-color: #19be6b;margin-left: 5px;margin-right: 5px;margin-top: 10px;">
                    <div v-for="v, k in iosConnectInfo.appiumArgs">
                        <p><span style="color: blueviolet; margin-right: 5px;">{{ k }}:</span>
                            <Tooltip v-if="getlowV(k, v)[0]" content="Top Center text" placement="top"><span>{{
                                getlowV(k, v)[1] }}</span></Tooltip><span v-else>{{ getlowV(k, v)[1] }}</span>
                        </p>
                    </div>
                </div>
                <Button v-if="selectSystem == 2" style="margin-top: 10px;" @click="disconnectIos">断开连接</Button>
            </div>
            </Col>
        </Row>
    </div>
    <Drawer title="appium日志" :closable="false" height="80" v-model="LogDrawer" placement="bottom">
        <div ref="logBox" style="height: 92%; overflow:scroll; background-color: black;font-size: 18px">
        </div>
    </Drawer>
    <Modal v-model="appiumModal" :title="ModalTitle()" @on-ok="save" @on-cancel="cancel">
        <div style="margin-top: 5px;" v-for="item, index in LinShiAppuim.info">
            <Input v-model="item.key" style="width: 200px;margin-right: 5px;" />
            <span style="display: inline;margin-right: 5px;">:</span>
            <Input v-model="item.value" style="width: 200px;margin-right: 5px" />
            <Button style="display: inline;" size="small" icon="md-remove" type="error" shape="circle"
                @click="removeLishItem(index)"></Button>
        </div>
        <Button style="margin-top: 15px;" size="small" icon="md-add" type="primary" shape="circle"
            @click="addLishiItem()"></Button>
    </Modal>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, watch, onUnmounted, nextTick } from 'vue'
// import clipboard from 'clipboard';

import useClipboard from 'vue-clipboard3';

import { AnsiUp } from 'ansi_up'
const ansi_up = new AnsiUp();

ansi_up.escape_html = false

const { proxy, ctx } = getCurrentInstance()

let Message = proxy.$Message
let socket = proxy.$socket
const { toClipboard } = useClipboard();


const appiumModal = ref(false)
let appiumStatus = ref(false)
let canRestartAppium = ref(false)

let LogDrawer = ref(false)

let logBox = ref(null)

let LogButtom = ref(false)

let LinShiAppuim = reactive({
    info: []
})

const copycmd={
    connect:'ssh -N -R 3240:localhost:3240 root@192.168.11.185',
    connectPass:'galaxy123',
    appiumHost:'192.168.11.185',
    appiumPort:'4567'
}


let title = ref('移动端自动化')
let webdriveragentId = ref(null)

let phoneStyle = reactive(
    {
        android: {
            span: "8",
            offset: "6"
        },
        ios: {
            span: "8",
            offset: "1"
        }
    }
)

let selectSystem = ref(0)
let connectSatus = ref(false)
let usbInfo = reactive({ arr: [] })

let nowRender = null
let buttomLine = ''

let androidConnectInfo = reactive({
    adbinfo: null,
    appiumArgs: {},
})

let iosConnectInfo = reactive({
    // Iostest: false,
    // IostestResult: 0,
    // IosId: null,
    // webDriverAgentID: null,
    // startCon: false,
    appiumArgs: {}
})



let columns = reactive([
    {
        title: 'key',
        key: 'key',
        width: 70
    },
    {
        title: '信息',
        slot: 'info'
    },
    {
        title: '状态',
        slot: 'status',
        width: 100
    },
    {
        title: '操作',
        slot: 'edit',
        width: 100
    },
])

watch(
    () => selectSystem.value,
    (newVal, oldVal) => {
        if (newVal == 0) {
            phoneStyle.android = {
                span: "8",
                offset: "6"
            }
            phoneStyle.ios = {
                span: "8",
                offset: "1"
            }
        } else if (newVal == 1) {
            phoneStyle.android = {
                span: "8",
                offset: "8"
            }
        } else if ((newVal == 2)) {
            phoneStyle.ios = {
                span: "8",
                offset: "8"
            }
        }
    })


function getlowV(k, v) {
    if (k.length + v.length + 2 >= 27) {
        return [true, v.slice(0, 25 - k.length - 1) + '...']
    } else {
        return [false, v]
    }
}

async function copyappiumconn() {
    const text = JSON.stringify(androidConnectInfo.appiumArgs)
    await toClipboard(text)
    Message.success("复制成功")
}

function connectAndroid() {
    selectSystem.value = 1
    socket.on("adbFlush", (data) => {
        androidConnectInfo.adbinfo = data
        if (data && !Object.keys(androidConnectInfo.appiumArgs).length) {
            console.log(data.split(' '))
            androidConnectInfo.appiumArgs = {
                "platformName": "Android",
                "appium:Android": 12,
                "appium:automationName": "UiAutomator2",
                "appium:deviceName": data.split('\t')[0],
                "appium:appPackage": "com.galaxy.galaxyandroid",
                "appium:appActivity": "com.galaxy.galaxyandroid.SplashActivity",
                "appium:remoteAdbHost": "172.17.0.1"
            }
        }
    })
    socket.emit("adbInfo")
}

function connectIos() {
    selectSystem.value = 2
    socket.on('iosinfo', data => {
        for (var k in data) {
            iosConnectInfo[k] = data[k]
        }
    })
    socket.emit('connectIOS', webdriveragentId.value)
}

function tailLog() {
    LogDrawer.value = true
}

function disconnectAndroid() {
    selectSystem.value = 0
    socket.emit('leaveAdbinfo')
    socket.off("adbFlush")
    androidConnectInfo.adbinfo = null
    androidConnectInfo.appiumArgs = {}
}

function disconnectIos() {
    selectSystem.value = 0
    if (iosConnectInfo?.IosId) {
        socket.off('iosinfo')
        socket.emit('disconnectIOS', webdriveragentId.value)
        iosConnectInfo = {
            appiumArgs: {}
        }
    }
}

function restartAppium() {
    canRestartAppium.value = true
    setTimeout(() => {
        canRestartAppium.value = false
    }, 5000);
    socket.emit("restartAppium")
}

function startAppium() {
    canRestartAppium.value = true
    setTimeout(() => {
        canRestartAppium.value = false
    }, 5000);
    socket.emit("startAppium")
}


// function disconnectIos() {
//     selectSystem.value = 0
// }

async function copyinfo(key) {
    await toClipboard(copycmd[key])
    Message.success("复制成功")
}

// async function copyConnectCmd() {
//     const text = "ssh -N -R 3240:localhost:3240 root@192.168.11.185"
//     await toClipboard(text)
//     Message.success("复制成功")
// }

// async function copyConnectPass() {
//     const text = "galaxy123"
//     await toClipboard(text)
//     Message.success("复制成功")
// }

function killssh() {
    socket.emit('killproxy')
}

function bindusb(key) {
    console.log(key)
    socket.emit('connectUsb', key)
}

function setAppuimInfo() {
    if (selectSystem.value != 1 && selectSystem.value != 2) return Message.error('未知的手机系统');
    let selet = null
    if (selectSystem.value == 1) {
        selet = androidConnectInfo.appiumArgs
    } else if (selectSystem.value == 2) {
        selet = iosConnectInfo.appiumArgs
    }
    for (let i in selet) {
        LinShiAppuim.info.push({ key: i, value: selet[i] })
    }
    appiumModal.value = true
}

function renderLog(data) {
    // console.info(data)
    LogButtom.value = (logBox.value.scrollHeight - logBox.value.scrollTop <= logBox.value.clientHeight + 10 || (logBox.value.scrollTop == 0 && logBox.value.clientHeight == logBox.value.scrollHeight)) ? true : false
    const result = data.replace('\t', '&emsp;').split('\n')
    result[0] = (buttomLine + result[0])
    buttomLine = result[result.length - 1]
    for (let i = 0; i < result.length; i++) {
        if (i == result.length - 1) {
            if (!nowRender) {
                nowRender = document.createElement("p");
                nowRender.innerHTML = ansi_up.ansi_to_html(result[i])
                logBox.value.appendChild(nowRender)
            } else {
                nowRender.innerHTML = ansi_up.ansi_to_html(result[i])
            }
            buttomLine = result[i]
        } else {
            const res = document.createElement("p")
            res.innerHTML = ansi_up.ansi_to_html(result[i])
            logBox.value.appendChild(res)
        }

    }
    if (LogButtom.value) logBox.value.scrollTop = logBox.value.scrollHeight
}

function removeLishItem(k) {
    LinShiAppuim.info.splice(k, 1)
}

function addLishiItem() {
    LinShiAppuim.info.push({ key: '', value: '' })
}

function save() {
    let result = {}
    console.info("进来了")
    for (var item of LinShiAppuim.info) {
        console.info(item)
        if (item.key == '' || item.key == null || item.value == '' || item.value == null) {
            return Message.error('请完善信息')
        } else {
            result[item.key] = item.value
        }
    }


    console.info(result)
    if (selectSystem.value != 1 && selectSystem.value != 2) return Message.error('未知的手机系统');
    if (selectSystem.value == 1)
        androidConnectInfo.appiumArgs = result
    else if (selectSystem.value == 2)
        iosConnectInfo.appiumArgs = result
    cancel()
}

function cancel() {
    LinShiAppuim.info = []
    appiumModal.value = false
}

function ModalTitle() {
    if (selectSystem.value == 1) return '安卓appuim连接参数编辑'
    if (selectSystem.value == 2) return 'ios appuim连接参数编辑'
}

onMounted(() => {
    socket.connect()
    socket.on('usbFlush', (data) => {
        usbInfo.arr = data
    })
    socket.on('sshFlush', (data) => {
        connectSatus.value = data
    })
    socket.on('appiumstatus', (data) => {
        appiumStatus.value = data
    })
    socket.emit("usbInfo")
    socket.emit('appiumLog')
    socket.on('sendappiumLog', (data) => { renderLog(data) })
})



onUnmounted(() => {
    disconnectIos()
    socket.emit('leaveappiumLog')
    socket.off('sendappiumLog')
    socket.off('usbFlush')
    socket.off('sshFlush')
    socket.off('appiumstatus')
})

</script>

<style>
.phone {
    width: 250px;
    height: 500px;
    background-color: rgb(231, 246, 255);
    border-radius: 20px;
    border-style: outset;
    border-width: 10px;
    border-color: rgb(24, 23, 44);
    text-align: center;
}

.transition-box {
    margin-top: 32px;
    width: 100%;
    border-radius: 4px;
    background-color: #409EFF;
    text-align: center;
    color: #fff;
    padding: 24px 0;
}
</style>