<template>
    <a-row>
        <a-col :span="13">
            <a-card title="调试输出" style="background-color: #eef0f5;">
                <template #extra >
                    <a-button type="primary" @click="clearLog" >清空日志</a-button>
                </template>
                <a-row>
                    <a-col :span="6" class="app-imitate" >应用模拟器</a-col>
                    <a-col :span="3" class="app-to-platform" >
                        <div class="equipment-platform" >
                            <div class="border-dot-top">命令下发</div>
                            <div class="border-dot-bottom">数据上报</div>
                        </div>
                    </a-col>
                    <a-col :span="6" class="IOT" @click="state.msgTrackVisible = !state.msgTrackVisible" >
                        IOT平台 <span v-if="state.eventList.length " >（输出数：{{state.eventList.length }}）</span>
                    </a-col>
                    <a-col :span="3" class="app-to-platform" >
                        <div class="equipment-platform" >
                            <div class="border-dot-top">命令下发</div>
                            <div class="border-dot-bottom">数据上报</div>
                        </div>
                    </a-col>
                    <a-col :span="6" class="device-imitate" >真实设备</a-col>
                </a-row>
                <a-row style="height: 505px;width: 100%" justify="space-between"   >
                    <a-col :span="11" style="height: 100%;background-color: #fff;position: relative;overflow: hidden;overflow-y: auto;" >
                        <a-empty v-if="state.eventList.length == 0" style="position: absolute;top: 50%;left:50%; transform: translate(-50%, -50%);" ></a-empty>
                        <span v-else >
                            <div v-for="(item, index) in state.eventList"
                                class="log-item"
                                :key="index"
                            >
                                <div><api-two-tone style="margin-right: 10px;" />{{item.ts}}</div>

                                <a-row
                                    v-for="(_, i) in item.json"
                                    :key="_.id"
                                    :gutter="[8, 8]"
                                >

                                <span v-if="_.eventType !== 'TRANSPORT_TO_PLATFORM'" >
                                    <a-col span="24" >事件名称：{{_.eventName}}</a-col>
                                    <a-col span="24" >事件类型：{{EventController.eventTypeMap.get(_.eventType)?.name}}</a-col>
                                    <a-col span="24" >事件参数：{{_.eventPayload}}</a-col>
                                    <a-divider v-if="index !== state.eventList.length && i === 1" style="height: 1px; background-color: #8a8e99; margin: 8px 0px;" dashed />
                                </span>
                                </a-row>
                            </div>
                        </span>
                    </a-col>
                    <a-col :span="11" style='background-color: #fff;height: 100%;overflow: hidden;overflow-y: auto;' >
                        <a-empty v-if="state.eventList.length == 0" style="position: absolute;top: 50%;left:50%; transform: translate(-50%, -50%);" ></a-empty>
                        <div v-for="(item, index) in state.eventList"
                                class="log-item"
                                :key="index"
                            >
                                <div><api-two-tone style="margin-right: 10px;" /> {{item.ts}}</div>

                                <a-row
                                    v-for="(_, i) in item.json"
                                    :key="_.id"
                                    :gutter="[8, 8]"
                                >
                                    <span v-if="_.eventType === 'TRANSPORT_TO_PLATFORM'">
                                        <a-col span="24" >事件名称：{{_.eventName}}</a-col>
                                        <a-col span="24" >事件类型：{{EventController.eventTypeMap.get(_.eventType)?.name}}</a-col>
                                        <a-col span="24" >事件参数：{{_.eventPayload}}</a-col>
                                        <a-divider  v-if="index != state.eventList.length - 1" style="height: 1px; background-color: #8a8e99; margin: 8px 0px;" dashed />
                                    </span>
                                </a-row>
                            </div>
                    </a-col>
                    <a-col class="msg-track" :span="11" >
                            <a-drawer
                                title="消息追踪"
                                :mask="false"
                                placement="left"
                                :open="state.msgTrackVisible"
                                :get-container="false"
                                :style="{ position: 'absolute' }"
                                headerStyle="{text-align: center;}"
                                @close="state.msgTrackVisible = false"
                                >
                                <a-row>
                            <a-col>
                                <div v-for="(item, index) in state.eventList"
                                class="log-item"
                                :key="index"
                            >
                                <div><api-two-tone style="margin-right: 10px;" />{{item.ts}}</div>
                                    <a-row
                                        v-for="(_, i) in item.json"
                                        :key="_.id"
                                        :gutter="[8, 8]"
                                    >
                                    <span>
                                        <a-col span="24" >事件名称：{{_.eventName}}</a-col>
                                        <a-col span="24" >事件类型：{{EventController.eventTypeMap.get(_.eventType)?.name}}</a-col>
                                        <a-col span="24" >事件参数：{{_.eventPayload}}</a-col>
                                        <a-divider  style="height: 1px; background-color: #8a8e99; margin: 8px 0px;" dashed />
                                    </span>
                                    </a-row>
                                </div>
                            </a-col>
                        </a-row>
                            </a-drawer>
                    </a-col>
                </a-row>

            </a-card>
        </a-col>
        <a-col :span="9">
            <a-row justify='end' >
                <a-col>
                    <a-button type="link" >{{state.device.deviceLabel ? state.device.deviceLabel : "尚未选择设备"}}</a-button>
                    <a-button type="primary" @click="state.drawerVisible = true" >选择设备</a-button>
                </a-col>
            </a-row>
            <!-- :tab-list="tabListNoTitle"
                :active-tab-key="state.activeKey"
                @tabChange="onTabChange" -->
            <a-card
                title="应用模拟器"
                style="width: 100%;height: 632px;margin-top: 10px;position: relative;"
            >
                <a-row :gutter="[8, 8]">
                    <a-col span="24" ><a-tag color="blue" style="scale: 1.2;" >命令下发</a-tag></a-col>
                    <a-col class="subtitle"  span="24"  >
                        应用模拟器可根据产品定义向设备下发命令。<br/>
                        若您使用了图形化开发的编解码插件，为获得正确的编码结果，下发命令时，请携带所有在插件中定义的字段，且每个命令的长度需小于512个字节
                    </a-col>
                    <a-col  span="24" v-if="false" >
                        <a-form
                            :labelCol="{span: 2}"
                            :wrapperCol="{span: 14}"
                        >
                            <a-form-item label="产品" >
                                <a-select allowClear v-model:value="state.modelId" >
                                    <a-select-option
                                        v-for="item in state.modelSouce"
                                        :key="item.id"
                                        :value="item.id"
                                    >
                                        {{item.modelLabel}}
                                    </a-select-option>
                                </a-select>
                            </a-form-item>
                            <a-form-item label="命令" >
                                <a-select allowClear v-model:value="state.cmdId" >
                                    <a-select-option
                                        v-for="item in state.modelCmdList"
                                        :key="item.id"
                                        :value="item.id"
                                    >
                                        {{item.cmdLabel}}
                                    </a-select-option>
                                </a-select>
                            </a-form-item>

                            <span  v-if="cmdDetail?.cmdParams.length" >
                                <a-form-item :label="item.paramLabel"  v-for="(item, index) in cmdDetail?.cmdParams" :key="item.id" >
                                    <a-input  allowClear v-model:value="item.dataUnit" ></a-input>
                                </a-form-item>
                            </span>
                        </a-form>
                    </a-col>
                </a-row>
                <template #extra >
                    <a-button type="primary" @click="openCmdModal">命令下发</a-button>
                </template>

            </a-card>
        </a-col>
    </a-row>

    <a-drawer
        v-model:open="state.drawerVisible"
        size="large"
        class="custom-class"
        title="选择设备2233"
        placement="right"
    >
        <SelectDevice ref="selectDeviceRef" />
        <template #footer >
            <a-row justify="end" >
                <a-col>
                    <a-space>
                        <a-button @click="state.drawerVisible = false">取消</a-button>
                        <a-button type="primary" @click="handleSelectDevice">确定</a-button>
                    </a-space>
                </a-col>
            </a-row>
        </template>
    </a-drawer>

    <cmd-push
        :visible="cmdState.visible"
        :device-id="state.device.id"
        :model-id="state.device.modelId"
        @cancel="cmdState.visible = false"
        @ok="cmdState.visible = false"
    />
</template>
<script lang='ts' setup >
import { computed, onMounted, reactive, ref, watch } from 'vue'
import SelectDevice from '@/pages/iot/rule/components/selectDevice.vue'
import { message } from 'ant-design-vue'
import { DeviceContriller, EventController, ModelCmdController, ModelController } from '@/controller'
import { useRoute } from 'vue-router'
import dayjs from 'dayjs'
import { FieldTimeOutlined, ApiTwoTone } from '@ant-design/icons-vue'
import CmdPush from '@/pages/iot/device/modal/cmdPush.vue'
import { useScheduler } from '@/hooks'

const route = useRoute()

const selectDeviceRef = ref()

const cmdState = reactive({
  visible: false
})

const state = reactive<{
    activeKey: 'app',
    drawerVisible: boolean,
    modelSouce: IOT.API.MODEL.Model[],
    modelId: string,
    cmdId: string,
    modelCmdList: IOT.API.CMD.Cmd[],
    eventList: any,
    startTime: number,
    lastId: string
    msgTrackVisible: boolean
    device: {
        id: string
        deviceLabel: string
        modelId: string
    }
}>({
  activeKey: 'app',
  drawerVisible: false,
  msgTrackVisible: false,
  modelSouce: [],
  modelId: '',
  cmdId: '',
  modelCmdList: [],
  eventList: [],
  startTime: 0,
  lastId: '',
  device: {
    id: '',
    deviceLabel: '',
    modelId: ''
  }
})

watch(() => state.modelId, () => getModelCmdList())

watch(
  () => state.device.id,
  () => {
    addEventList()
  },
  {
    deep: true
  }
)

const cmdDetail = computed(() => state.modelCmdList.find(item => item.id === state.cmdId))

const clearLog = () => {
  state.eventList = []
  message.success('清除成功')
}

const openCmdModal = () => {
  if (!state.device.id) {
    message.error('请先选择设备')
    return
  }
  cmdState.visible = true
}

const handleSelectDevice = () => {
  console.log('我不处罚')
  const _device = selectDeviceRef.value.getSelectDevice()
  console.log('_device:', _device)

  if (_device) {
    state.device = _device
    console.log('state.device:', state.device)

    state.drawerVisible = false
  } else {
    message.warn('请选择产品')
  }
}

const getModelCmdList = async () => {
  const { data } = await ModelCmdController.list({ modelId: state.modelId })
  state.modelCmdList = data
}

const getEventList = async () => {
  const { data, sum } = await EventController.list({ deviceId: state.device.id, startTime: state.startTime, lastId: state.lastId })
  if (data) {
    state.eventList.unshift ({
      json: data,
      ts: dayjs(new Date().getTime()).format('YYYY/MM/DD HH:mm:ss')
    })
  } else {
    state.eventList = []
  }
}

const { start, stop } = useScheduler(getEventList, 2000)

const getEventTraceList = async () => {
  await EventController.listTrace({ deviceId: state.device.id }) as unknown as Number
  start()
}

const addEventList = async () => {
  stop()
  await EventController.addTrace({ deviceId: state.device.id })
  getEventTraceList()
}

const getDeviceById = async () => {
  const data = await DeviceContriller.byId(state.device.id)
  state.device = data
}

onMounted(() => {
  const deviceId = route.query.id as string

  if (deviceId) {
    state.device.id = deviceId
    getDeviceById()
  }
})
</script>
<style lang='less' scoped >

@import "~@/styles/theme.less";
.subtitle {
  font-size: 12px;
  color: @label-color;
}
.app-imitate {
    width: 250px;
    height: 80px;
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
}
.IOT {
    width: 250px;
    height: 64px;
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
    cursor: pointer;
    span {
        color: @sublabel-color;
        font-size: 16px;
    }
}
.app-to-platform {
    height: 100%;
    // width: 12.5%;
    // float: left;
    // height: 100%;
}
.device-imitate {
    width: 250px;
    height: 80px;
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
}
.equipment-platform {
    position: absolute;
    display: inline-block;
    vertical-align: middle;
    width: 100%;
    line-height: 1;
    color: #4d4d4d;
    text-align: center;
    font-size: 12px;
    .border-dot-top {
        position: relative;
        padding-bottom: 0.6rem;
        margin-bottom: 1rem;
        border-bottom: 2px #999 solid;
    }
    .border-dot-top::before {
        left: 0;
        top: 100%;
        margin-top: -0.15rem;
        content: "";
        display: block;
        width: 0.4rem;
        height: 0.4rem;
        border-radius: 0.2rem;
        border: 2px #999 solid;
        background-color: #ebedf0;
        position: absolute;
    }
    .border-dot-top::after {
        content: "";
        display: block;
        border: 4px #999 solid;
        width: 0;
        height: 0;
        transform: rotate(45deg);
        position: absolute;
        right: 0;
        top: 97%;
        margin-top: -0.15rem;
        border-color: #999 #999 transparent transparent;
    }
    .border-dot-bottom {
        border-color: #ccc;
    position: relative;
    padding-top: 0.6rem;
    border-top: 2px #999 dashed;
    }
    .border-dot-bottom::before {
        content: "";
        display: block;
        border: 4px #999 solid;
        width: 0;
        height: 0;
        transform: rotate(-135deg);
        position: absolute;
        top: -11%;
        margin-top: -0.15rem;
        border-color: #999 #999 transparent transparent;
    }
    .border-dot-bottom::after {
        right: 0;
        top: -1px;
        margin-top: -0.15rem;
        content: "";
        display: block;
        width: 0.4rem;
        height: 0.4rem;
        border-radius: 0.2rem;
        border: 2px #999 solid;
        background-color: #ebedf0;
        position: absolute;
    }
}

.log-item {
    width: 100%;
    table-layout: fixed;
    word-wrap: break-all;
    word-break: normal;
    word-wrap: break-word;
    white-space: pre-wrap;
    padding: 0px 10px;
    box-sizing: border-box;
    margin-top: 10px;
}

.msg-track {
    width: 100%;
    height: 300px;
    position: absolute;
    bottom: 24px;
    left: 24px;
    box-shadow: #000;
    overflow: hidden;
    overflow-y: auto;
    .title {
        font-size: 20px;
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 10px;

    }
}

</style>
