<template>
    <el-dialog
        class="cn-operate-dialog device-manage-popup"
        v-model="dialogVisible"
        :title="!addFlag ? '数据绑定' : '数据选择'"
        draggable
        :append-to-body="true"
        width="80%"
    >
        <el-button type="primary" @click="addFlag = true" v-if="!addFlag">新增</el-button>
        <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            icon-color="#626AEF"
            width="200"
            title="是否确认删除所选数据？"
            @confirm="handleDelete('')"
            @cancel="cancelDelete"
        >
            <template #reference>
                <el-button type="danger" :disabled="checkedList.length == 0" v-if="!addFlag">删除</el-button>
            </template>
        </el-popconfirm>

        <div class="device-manage" v-show="addFlag" v-loading="loading">
            <deviceInfoTree
                :showCheckbox="true"
                :default-checked-keys="defaultCheckedKeys"
                @checkChange="checkChange"
                ref="deviceInfoTreeRef"
            ></deviceInfoTree>
            <div class="device-manage-right">
                <TableHeader datePicker ref="TableHeaderRef"></TableHeader>
                <Table ref="tableRef" />
            </div>
        </div>
        <div class="device-manage" v-show="!addFlag" v-loading="loading">
            <div class="device-manage-right">
                <!-- <datePicker ref="datePickerRef"></datePicker>
                <el-button type="primary" @click="handleSearch">查询</el-button> -->
                <vxe-table
                    v-bind="defaultAttribute"
                    :data="tableData"
                    height="420"
                    style="width: 100%; margin-top: 10px"
                    ref="checkedTableRef"
                    @checkbox-all="selectChangeEvent"
                    @checkbox-change="selectChangeEvent"
                >
                    <vxe-column type="checkbox" width="60"></vxe-column>
                    <vxe-column field="devName" title="设备名称"></vxe-column>
                    <vxe-column field="devMac" title="设备MAC"></vxe-column>
                    <vxe-column field="devNdId" title="网络设备ID"></vxe-column>
                    <vxe-column field="lineName" title="线路号"></vxe-column>
                    <vxe-column field="startTime" title="开始时间"></vxe-column>
                    <vxe-column field="endTime" title="结束时间"></vxe-column>
                    <vxe-column title="操作" width="120" fixed="right">
                        <template #default="{ row }">
                            <el-popconfirm
                                width="150"
                                confirm-button-text="是"
                                cancel-button-text="否"
                                icon-color="#626AEF"
                                title="是否确认删除？"
                                @confirm="handleDelete(row)"
                                @cancel="cancelDelete"
                            >
                                <template #reference>
                                    <el-button type="danger" text   >删除</el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </vxe-column>
                </vxe-table>
            </div>
        </div>
        <template #footer="">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="submit" v-if="addFlag">确 定</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { defaultAttribute } from '@/components/table/defaultAttribute'
import deviceInfoTree from '@/components/tree/govern/deviceInfoTree.vue'
import { mainHeight } from '@/utils/layout'
import { ref, onMounted, provide, watch } from 'vue'
import { getDeviceList, addDevice, delDevice } from '@/api/cs-device-boot/planData'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import { ElMessage } from 'element-plus'
import TableHeader from '@/components/table/header/index.vue'
const pageHeight = mainHeight(-20)
const loading = ref(false)
const defaultCheckedKeys: any = ref([])
const tableData = ref([])
defineOptions({
    name: 'govern/tourist/index'
})
const treeIds: any = ref([])
//树节点选择变化的时候处理树节点选中数据
const checkChange = async (data: any) => {
    if (data.checked) {
        defaultCheckedKeys.value.push(data.data.id)
        data.data.children?.map((item: any) => {
            treeIds.value.push(item.id)
        })
    } else {
        defaultCheckedKeys.value.splice(defaultCheckedKeys.value.indexOf(data.data.id), 1)
        data.data.children?.map((item: any) => {
            treeIds.value.splice(defaultCheckedKeys.value.indexOf(item.id), 1)
        })
    }
    // await tableStore.index()
}
const datePickerRef = ref()
const handleSearch = () => {
    console.log(datePickerRef.value.timeValue)
}
const dialogVisible = ref(false)
const deviceInfoTreeRef = ref()
//判断是否显示新增页面 false显示详情页面和删除按钮隐藏确定按钮 true显示新增页面与确定按钮隐藏删除按钮
const addFlag = ref(false)
const selectId: any = ref('')
//查绑定测试项列表
const getSelectedTable = (id: any) => {
    //新增传0已绑定传1
    getDeviceList({ id: id, isTrueFlag: 1, pageNum: 1, pageSize: 1000 }).then(res => {
        tableData.value = res.data.records
    })
}
//新增设备列表
const tableStore = new TableStore({
    url: '/cs-device-boot/wlRecord/queryPage',
    publicHeight: 210,
    method: 'POST',
    column: [
        { width: '60', type: 'checkbox', fixed: 'left' },
        { title: '序号', type: 'seq', width: 80 },
        { field: 'devName', title: '设备名称', minWidth: 170 },
        { field: 'lineName', title: '线路号', minWidth: 170 },
        { field: 'startTime', title: '开始时间', minWidth: 170 },
        { field: 'endTime', title: '结束时间', minWidth: 170 }
    ],

    beforeSearchFun: () => {
        tableStore.table.params.id = selectId.value
        //新增传0已绑定传1
        tableStore.table.params.isTrueFlag = 0
        tableStore.table.params.treeIds = treeIds.value
    }
})
provide('tableStore', tableStore)
//弹框打开处理
const open = (id: any) => {
    dialogVisible.value = true
    selectId.value = id
    //1 列表  0树
    //获取树形数据
    getDeviceList({ id: id, isTrueFlag: 0 }).then(res => {
        deviceInfoTreeRef.value.getTreeList(res.data)
    })
    //查绑定测试项列表
    getSelectedTable(id)
    //查新增列表
    tableStore.index()
}
const tableRef = ref()
//添加设备
const submit = () => {
    //选择的数据
    let deviceIds = []
    //新增的时候执行的逻辑
    if (addFlag.value) {
        if (tableStore.table.selection.length != 0) {
            tableStore.table.selection.map(item => {
                deviceIds.push(item.id)
            })
            const addForm = {
                id: selectId.value,
                list: deviceIds
            }
            addDevice(addForm).then(res => {
                if (res.code == 'A0000') {
                    ElMessage.success('添加成功')
                    getSelectedTable(selectId.value)
                    //清除树节点选择状态
                    defaultCheckedKeys.value = []
                    //刷新新增列表状态
                    tableStore.index()
                    addFlag.value = false
                }
            })
        } else {
            ElMessage.warning('请选择设备信息')
        }
    }
}

const close = () => {
    if (addFlag.value) {
        addFlag.value = false
        checkedList.value = []
        checkedTableRef.value.clearCheckboxRow()
    } else {
        dialogVisible.value = false
    }
}
//删除设备
const checkedTableRef = ref()
//判断是否选择了设备数据
const checkedList: any = ref([])
/*
 * 记录选择的项
 */
const selectChangeEvent = (checked: any) => {
    checkedList.value = checkedTableRef.value.getCheckboxRecords()
}

const handleDelete = (row: any) => {
    let list = []
    //单选删除
    if (row) {
        list.push(row.id)
    }
    //批量删除
    else {
        checkedTableRef.value.getCheckboxRecords().length != 0
            ? checkedTableRef.value.getCheckboxRecords().map((item: any) => {
                  list.push(item.id)
              })
            : (list = [])
    }
    if (list.length != 0) {
        delDevice({ id: selectId.value, list: list }).then(res => {
            if (res.code == 'A0000') {
                ElMessage.success('删除成功')
                getSelectedTable(selectId.value)
            }
        })
    }
}
const cancelDelete = () => {
    console.log('取消')
}
onMounted(() => {})
defineExpose({ open })
</script>

<style lang="scss">
.device-manage {
    display: flex;

    &-right {
        overflow: hidden;
        flex: 1;
        padding: 10px 10px 10px 0;
        .el-descriptions__header {
            height: 36px;
            margin-bottom: 7px;
            display: flex;
            align-items: center;
        }
    }
}
// ::v-deep .el-
</style>
