<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
            <el-form-item label="项目" prop="projectId">
                <el-select :disabled="data.currentPrjId != ''" v-model="queryParams.projectId" placeholder="请选择项目"
                    clearable @change="handleQuery">
                    <el-option v-for="prj in data.projects" :key="prj.id" :label="prj.projectName"
                        :value="prj.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="设备名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备标签" prop="tag">
                <el-input v-model="queryParams.tag" placeholder="请输入设备标签" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备序列号" prop="deviceNo">
                <el-input v-model="queryParams.deviceNo" placeholder="请输入设备序列号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd"
                    v-hasPermi="['manage:attendance_ubi_device:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['manage:attendance_ubi_device:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['manage:attendance_ubi_device:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport"
                    v-hasPermi="['manage:attendance_ubi_device:export']">导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="attendance_ubi_deviceList" @selection-change="handleSelectionChange">
            <el-table-column label="公司" align="center" prop="compName" />
            <el-table-column label="所属项目" align="center" prop="projectName" />
            <el-table-column label="所属工区" align="center" prop="workAreaName" />
            <el-table-column label="设备名称" align="center" prop="name" />
            <el-table-column label="设备标签" align="center" prop="tag" />
            <el-table-column label="设备来源" align="center" prop="souceName" />
            <el-table-column label="设备序列号" align="center" prop="deviceNo" />
            <el-table-column label="设备模式" align="center" prop="deviceModel" v-if="false" />
            <el-table-column label="设备状态" align="center" prop="deviceState">
                <template #default="scope">
                    <span v-if="scope.row.deviceState == 1">未绑定</span>
                    <span v-if="scope.row.deviceState == 2">已绑定</span>
                    <span v-if="scope.row.deviceState == 3">已禁用</span>
                </template>
            </el-table-column>
            <el-table-column label="比对模式" align="center" prop="recType">
                <template #default="scope">
                    <span v-if="scope.row.recType == 1">本地识别</span>
                    <span v-if="scope.row.recType == 2">云端识别</span>
                </template>
            </el-table-column>
            <el-table-column label="在线状态" align="center" prop="onlineState">
                <template #default="scope">
                    <span v-if="scope.row.onlineState == 1">在线</span>
                    <span v-if="scope.row.onlineState == 2">离线</span>
                </template>
            </el-table-column>
            <el-table-column label="版本号" align="center" prop="versionNo" />
            <el-table-column label="最后激活时间" align="center" prop="lastActiveTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.lastActiveTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="注册状态" align="center" prop="hasRegister">
                <template #default="scope">
                    <span v-if="scope.row.onlineState == 1">已注册</span>
                    <span v-else>未注册</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
                <template #default="scope">
                    <el-button link type="primary" icon="ChromeFilled" @click="handleAuth(scope.row)"
                        v-hasPermi="['manage:attendance_ubi_device:edit']">同步</el-button>
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['manage:attendance_ubi_device:edit']">修改</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['manage:attendance_ubi_device:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改宇泛的设备信息对话框 -->
        <el-dialog :title="title" v-model="open" width="600px" append-to-body :close-on-click-modal="false"
            :close-on-press-escape="false" class="dlg-hide-form-hidden-scroll">
            <el-form ref="attendance_ubi_deviceRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="所属项目">
                    <el-tag effect="plain">{{ form.projectName }}</el-tag>
                </el-form-item>
                <el-form-item label="设备名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入设备名称" />
                </el-form-item>
                <el-form-item label="设备标签" prop="tag">
                    <el-input v-model="form.tag" placeholder="请输入设备标签" />
                </el-form-item>
                <el-form-item label="设备来源" prop="source">
                    <el-select v-model="form.source" placeholder="请选择设备来源" clearable>
                        <el-option v-for="dict in ubi_device_source" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="设备序列号" prop="deviceNo">
                    <el-input v-model="form.deviceNo" placeholder="请输入设备序列号" />
                </el-form-item>
                <el-form-item label="所属工区" prop="workAreaId">
                    <el-tree-select v-model="form.workAreaId" :data="data.workAreaOptions"
                        :props="{ value: 'id', label: 'title', children: 'children' }" value-key="id"
                        placeholder="请选择工区" clearable style="width:300px;" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm" :loading="data.submitLoading">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Attendance_ubi_device">
import {
    listAttendance_ubi_device,
    getAttendance_ubi_device,
    delAttendance_ubi_device,
    addAttendance_ubi_device,
    updateAttendance_ubi_device,
    authAttendance_ubi_device,
} from '@/api/manage/attendanceubidevice'
import useUserStore from '@/store/modules/user'
import { findMyProjectList } from '@/api/publics'
import { workAreaTree, transformTreeData } from '@/api/system/workAarea'
const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const { ubi_device_source } = proxy.useDict('ubi_device_source')
const attendance_ubi_deviceList = ref([])
const workAreaList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        comId: null,
        projectId: null,
        name: null,
        tag: null,
        sceneGuid: null,
        source: null,
        deviceNo: null,
        addition: null,
        bindDefaultScene: null,
        forceEmptyDevice: null,
        password: null,
        deviceModel: null,
        deviceState: null,
        recType: null,
        onlineState: null,
        versionNo: null,
        lastActiveTime: null,
        hasRegister: null,
        state: null,
        isDel: null,
    },
    rules: {
        name: [{ required: true, trigger: ['blur', 'change'], message: '请输入设备名称' }],
        tag: [{ required: true, trigger: ['blur', 'change'], message: '请输入设备标签' }],
        source: [{ required: true, trigger: ['blur', 'change'], message: '请选择设备来源' }],
        deviceNo: [{ required: true, trigger: ['blur', 'change'], message: '请输入设备序列号' }],
        workAreaId: [{ required: false, trigger: 'blur', message: '请选择所属工区' }],
    },
    projects: [],
    currentPrjId: '',
    mode: '',
    workAreaOptions: [],
    submitLoading: false,
})

const { queryParams, form, rules } = toRefs(data)
/**
 * 设备人员同步
 */
function handleAuth(row) {
    authAttendance_ubi_device(row).then((d) => {
        if (d.code == 200) {
            proxy.$modal.msgSuccess('同步成功!')
        } else {
            proxy.$modal.msgError('同步失败!')
        }
    })
}
/** 查询项目列表 */
function getProjectList() {
    findMyProjectList({ pageNum: 1, pageSize: 100 }).then((response) => {
        data.projects = response.rows
        if (userStore.currentPrjId) {
            queryParams.value.projectId = userStore.currentPrjId
            data.currentPrjId = userStore.currentPrjId
        }
    })
}

/** 查询宇泛的设备信息列表 */
function getList() {
    loading.value = true
    queryParams.value.projectId = userStore.currentPrjId
    listAttendance_ubi_device(queryParams.value).then((response) => {
        attendance_ubi_deviceList.value = response.rows
        total.value = response.total
        loading.value = false
    })
}

// 取消按钮
function cancel() {
    open.value = false
    reset()
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        comId: null,
        projectId: null,
        name: null,
        tag: null,
        sceneGuid: '',
        source: null,
        deviceNo: null,
        addition: null,
        bindDefaultScene: null,
        forceEmptyDevice: null,
        password: null,
        deviceModel: null,
        deviceState: null,
        recType: null,
        onlineState: null,
        versionNo: null,
        lastActiveTime: null,
        hasRegister: null,
        state: null,
        remark: null,
        isDel: null,
        workAreaId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
    }
    proxy.resetForm('attendance_ubi_deviceRef')
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm('queryRef')
    handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id)
    single.value = selection.length != 1
    multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
    if (!userStore.currentPrjId) {
        proxy.$modal.msgWarning('请切换到项目数据！！！')
        return false
    }
    reset()
    form.value.projectId = userStore.currentPrjId
    form.value.projectName = userStore.currentProName
    form.value.source = ubi_device_source.value[0].value
    open.value = true
    title.value = '添加宇泛的设备信息'
}

/** 修改按钮操作 */
function handleUpdate(row) {
    if (!userStore.currentPrjId) {
        proxy.$modal.msgWarning('请切换到项目数据！！！')
        return false
    }
    reset()
    const _id = row.id || ids.value
    getAttendance_ubi_device(_id).then((response) => {
        form.value = response.data
        open.value = true
        title.value = '修改宇泛的设备信息'
    })
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs['attendance_ubi_deviceRef'].validate((valid) => {
        if (valid) {
            form.value.comId = userStore.currentComId
            data.submitLoading = true
            if (form.value.id != null) {
                updateAttendance_ubi_device(form.value).then((response) => {
                    proxy.$modal.msgSuccess('修改成功')
                    open.value = false
                    getList()
                }).finally(() => {
                    data.submitLoading = false
                })
            } else {
                addAttendance_ubi_device(form.value).then((response) => {
                    proxy.$modal.msgSuccess('新增成功')
                    open.value = false
                    getList()
                }).finally(() => {
                    data.submitLoading = false
                })
            }
        }
    })
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _ids = row.id || ids.value
    proxy.$modal
        .confirm('是否确认删除宇泛的设备信息编号为"' + _ids + '"的数据项？')
        .then(function () {
            return delAttendance_ubi_device(_ids)
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess('删除成功')
        })
        .catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download(
        'manage/attendance_ubi_device/export',
        {
            ...queryParams.value,
        },
        `attendance_ubi_device_${new Date().getTime()}.xlsx`
    )
}
/** 查询工区树结构 */
function getWorkAreaTree() {
    workAreaTree(userStore.currentPrjId).then(response => {
        // 转换数据格式以适配el-tree-select组件
        data.workAreaOptions = transformTreeData(response.data);
    });
}


getList()
getProjectList()
getWorkAreaTree()
</script>
