<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div v-show="showSearch" class="mb-[10px]">
                <el-card shadow="hover">
                    <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
                        <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="sn">
                            <el-input v-model="queryParams.sn" placeholder="请输入设备编号" clearable @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="使用状态" prop="status">
                            <el-select v-model="form.deviceTypeId" clearable placeholder="请选择使用状态">
                                <el-option v-for="dict in use_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                            </el-select>
                        </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-card>
            </div>
        </transition>

        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['jdyw:deviceType:add']" type="primary" plain icon="Plus" @click="handleAdd"> 新增 </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['jdyw:deviceType:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">
                            修改
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
                            v-hasPermi="['jdyw:deviceType:remove']"
                            type="danger"
                            plain
                            icon="Delete"
                            :disabled="multiple"
                            @click="handleDelete"
                        >
                            删除
                        </el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
                </el-row>
            </template>

            <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="设备名称" align="center" prop="name" />
                <el-table-column label="设备编号" align="center" prop="sn" />
                <el-table-column label="所属系统" align="center" prop="deviceSystem" />
                <el-table-column label="品牌" align="center" prop="brand" />
                <el-table-column label="型号" align="center" prop="xh" />
                <el-table-column label="固定资产编号" align="center" prop="fixedId" width="120" />
                <el-table-column label="领用日期" align="center" prop="useDate" width="120" />
                <el-table-column label="质保日期" align="center" prop="qaDate" width="120" />
                <el-table-column label="维保状态" align="center" prop="qaStatus" />
                <el-table-column label="使用状态" align="center">
                    <template #default="scope">
                        <dict-tag :options="use_status" :value="scope.row.useStatus" />
                    </template>
                </el-table-column>
                <el-table-column label="运行状态" align="center" prop="runningStatus" />
                <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="180">
                    <template #default="scope">
                        <el-button size="small" link type="primary">详情</el-button>
                        <el-button size="small" link type="primary" @click="showQrCode(scope.row)">二维码</el-button>
                        <el-button size="small" link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
                        <el-button size="small" link type="danger" @click="handleScrap(scope.row)">报废</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination
                v-show="total > 0"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                :total="total"
                @pagination="getList"
            />
        </el-card>

        <!-- 添加或修改设备类型信息对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" append-to-body>
            <el-form ref="deviceFormRef" :model="form" label-width="80px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item
                            label="设备名称"
                            prop="deviceTypeId"
                            :disabled="ifEdit"
                            :rules="[{ required: true, message: '设备名称不能为空', trigger: 'blur' }]"
                        >
                            <el-input v-model="form.brand" placeholder="请输入设备名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            label="设备编号"
                            prop="deviceTypeId"
                            :disabled="ifEdit"
                            :rules="[{ required: true, message: '设备编号不能为空', trigger: 'blur' }]"
                        >
                            <el-input v-model="form.brand" placeholder="请输入（支持批量新增，以逗号分隔）" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            label="设备类型"
                            prop="deviceTypeId"
                            :disabled="ifEdit"
                            :rules="[{ required: true, message: '设备类型不能为空', trigger: 'change' }]"
                        >
                            <el-select v-model="form.deviceTypeId" placeholder="请选择设备类型">
                                <el-option v-for="dict in deviceTypeOptions" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="品牌" prop="brand">
                            <el-input v-model="form.brand" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="型号" prop="xh">
                            <el-input v-model="form.xh" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="领用日期" prop="xh">
                            <el-date-picker v-model="form.xh" style="width: 100%" :disabled="ifEdit" type="date" placeholder="领用日期" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="质保日期" prop="xh">
                            <el-date-picker v-model="form.xh" style="width: 100%" :disabled="ifEdit" type="date" placeholder="领用日期" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="使用状态" prop="xh">
                            <el-select v-model="form.deviceTypeId" clearable placeholder="请选择使用状态">
                                <el-option v-for="dict in use_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
                </el-form-item>
                <el-form-item label="地理位置" prop="remark">
                    <div id="map" class="bdmap"></div>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm"> 确 定 </el-button>
                    <el-button @click="cancel"> 取 消 </el-button>
                </div>
            </template>
        </el-dialog>
        <el-drawer v-model="drawer" title="报废设备" size="40%">
            <el-form ref="deviceScrapFormRef" :model="scrapForm" label-width="80px">
                <el-form-item label="设备名称">
                    <div>{{ scrapForm.name }}</div>
                </el-form-item>
                <el-form-item label="设备编号">
                    <div>{{ scrapForm.sn }}</div>
                </el-form-item>
                <el-form-item label="品牌">
                    <div>{{ scrapForm.brand }}</div>
                </el-form-item>
                <el-form-item label="型号">
                    <div>{{ scrapForm.xh }}</div>
                </el-form-item>
                <el-form-item label="报废理由" prop="reason" :rules="[{ required: true, message: '报废理由不能为空', trigger: 'blur' }]">
                    <el-input v-model="scrapForm.reason" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="报废时间" prop="scrapDate" :rules="[{ required: true, message: '报废时间不能为空', trigger: 'change' }]">
                    <el-date-picker v-model="scrapForm.scrapDate" style="width: 100%" type="date" placeholder="请选择" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="drawer = false">取消</el-button>
                    <el-button type="primary" @click="confirmClick">确认</el-button>
                </div>
            </template>
        </el-drawer>
        <el-dialog v-model="qrDialog" title="设备二维码" width="600px" append-to-body>
            <el-descriptions class="custom-descriptions" title="" :column="1" border>
                <el-descriptions-item label="设备名称"> {{ qrInfo.name }} </el-descriptions-item>
                <el-descriptions-item label="设备编号"> {{ qrInfo.sn }} </el-descriptions-item>
                <el-descriptions-item label="设备品牌"> {{ qrInfo.brand }} </el-descriptions-item>
                <el-descriptions-item label="设备型号"> {{ qrInfo.xh }} </el-descriptions-item>
                <el-descriptions-item label="存放位置"> {{ qrInfo.position }} </el-descriptions-item>
            </el-descriptions>
            <img class="qrImg" src="@/assets/images/qrcode.png" alt="" />
        </el-dialog>
    </div>
</template>

<script setup name="Archives" lang="ts">
import { listDevice, getDevice, delDevice, addDevice, updateDevice } from '@/api/deviceManage/device';
import { listDeviceType } from '@/api/deviceManage/deviceType';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const deviceList = ref([]);
const buttonLoading = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const deviceFormRef = ref<ElFormInstance>();
const deviceScrapFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});
const qrDialog = ref(false);
const deviceTypeOptions = ref([]);
const { use_status } = toRefs<any>(proxy?.useDict('use_status'));
const bdmap = ref(null);
const scrapForm = ref<any>({
    reason: '',
    scrapDate: ''
});
const qrInfo = ref<any>({});
const initFormData = {
    id: undefined,
    deviceTypeId: undefined,
    xh: null,
    remark: undefined,
    brand: undefined,
    linkName: '',
    linkPhone: '',
    ext1: undefined,
    ext2: undefined
};
const formData = reactive({
    form: { ...initFormData },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        sn: undefined,
        status: undefined,
        params: {}
    }
});

const { queryParams, form } = toRefs(formData);
let ifEdit = computed(() => {
    return dialog.title.includes('修改');
});
const drawer = ref(false);
/** 查询设备类型信息列表 */
const getList = async () => {
    loading.value = true;
    const res = await listDevice(queryParams.value);
    deviceList.value = res.rows;
    deviceList.value = [
        {
            name: '设备一',
            deviceSystem: '制冷系统',
            sn: '1002301',
            brand: '格力',
            xh: 'GL18L',
            fixedId: '202410280101',
            useDate: '2024-10-28',
            qaDate: '2028-10-29',
            qaStatus: '在保',
            useStatus: '1',
            runningStatus: '在线'
        }
    ];
    total.value = res.total;
    loading.value = false;
};
const showQrCode = (row) => {
    qrDialog.value = true;
    Object.assign(qrInfo.value, row);
};
const initMap = () => {
    var map = new BMapGL.Map('map'); // 创建地图实例
    var point = new BMapGL.Point(118.879999, 32.016216); // 创建点坐标
    map.centerAndZoom(point, 20);
    map.enableScrollWheelZoom(true);
    map.addEventListener('click', (evt) => {
        bdmap.value.clearOverlays();
        const { lng, lat } = evt.latlng;
        const pt = new BMapGL.Point(lng, lat);
        const marker = new BMapGL.Marker(pt);
        bdmap.value.addOverlay(marker);
    });
    bdmap.value = map;
};
/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
    form.value = { ...initFormData };
    deviceFormRef.value?.resetFields();
};

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

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};

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

/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = '新增设备';
    setTimeout(() => {
        initMap();
    }, 100);
};

/** 修改按钮操作 */
const handleUpdate = async (row) => {
    reset();
    // const _id = row?.id || ids.value[0];
    // const res = await getDevice(_id);
    // Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = '修改设备';
    setTimeout(() => {
        initMap();
    }, 100);
};
const handleScrap = (row) => {
    drawer.value = true;
    deviceScrapFormRef.value?.resetFields();
    Object.assign(scrapForm.value, row);
};
/** 提交按钮 */
const submitForm = () => {
    deviceFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.id) {
                await updateDevice(form.value).finally(() => (buttonLoading.value = false));
            } else {
                await addDevice(form.value).finally(() => (buttonLoading.value = false));
            }
            proxy?.$modal.msgSuccess('操作成功');
            dialog.visible = false;
            await getList();
        }
    });
};

/** 删除按钮操作 */
const handleDelete = async (row) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除？').finally(() => (loading.value = false));
    await delDevice(_ids);
    proxy?.$modal.msgSuccess('删除成功');
    await getList();
};
const getDeviceTypeList = () => {
    listDeviceType({}).then(({ code, rows }) => {
        if (code === 200) {
            deviceTypeOptions.value = rows;
        }
    });
};
const confirmClick = () => {
    deviceScrapFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            drawer.value = false;
        }
    });
};
onMounted(() => {
    getList();
    getDeviceTypeList();
});
</script>
<style lang="scss" scoped>
.bdmap {
    width: 100%;
    height: 250px;
}
.custom-descriptions {
    :deep(.is-bordered-label) {
        width: 25%;
        font-weight: 500;
    }
}
.qrImg {
    position: absolute;
    bottom: 35px;
    right: 35px;
    height: 150px;
}
</style>
