<script lang="ts">
export default {
    name: "record",
};
</script>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import Eldialog from '@/components/seccmsdialog/eldialog.vue'
import Page from '@/components/Pagination/page.vue'
import { ElMessageBox, ElMessage, ElTable, ElProgress } from 'element-plus'
import { getSystemDevice, addSystemDevice, updateSystemDevice, deleteSystemDeviceById, deleteSystemDeviceByIds } from '@/api/systemmanage/index'
import { getDeviceByType } from '@/api/device'
import { useUserStore } from '@/store/modules/user';
const userStore = useUserStore();
onMounted(() => {
    getDeviceByType({ dictcode: 'deviceType' }).then((res) => {
        EquipmentType.value = res.data
    })
    getDeviceByType({ dictcode: 'deviceStatus' }).then((res) => {
        statusoption.value = res.data
    })
    getData()
})
function currency(list: any, itemcode: any) {
    let dictname = ''
    list.forEach((element: any) => {
        if (element.itemcode == itemcode) {
            dictname = element.dictname
        }
    })
    return dictname
}
const queryInfo: any = ref({
    size: 10,
    total: 0,
    current: 1,
    deviceName: '',
    deviceModel: '',
    deviceType: '',
    status: ''
})
const multipleSelection = ref([])
const loading = ref(false)
const tableData: any = ref([])
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val
}
const dialogVisible = ref(false)
const dialogtitle = ref('新增系统设备')
const manageFromm: any = ref({})
const Mainrules = ref({
    deviceName: [
        { required: true, message: '请输入设备名称', trigger: 'blur' },
    ],
    deviceCode: [
        { required: true, message: '请输入设备编号', trigger: 'blur' },
    ],
    deviceType: [
        { required: true, message: '请选择设备类型', trigger: 'change' }
    ],
    protocol: [
        { required: true, message: '请选择协议类型', trigger: 'change' }
    ],
})
const protocoloption = ref(['IEC104', 'IEC61850'])
const EquipmentType: any = ref([])
const statusoption: any = ref([])
function getData() {
    loading.value = true
    const params = {
        size: queryInfo.value.size,
        current: queryInfo.value.current,
        deviceName: queryInfo.value.deviceName,
        deviceModel: queryInfo.value.deviceModel,
        deviceType: queryInfo.value.deviceType,
        status: queryInfo.value.status
    }
    getSystemDevice(params).then((res: any) => {
        tableData.value = res.data.records
        queryInfo.value.total = res.data.total
        loading.value = false
    })

}
function editclick(row: any) {
    manageFromm.value = JSON.parse(JSON.stringify(row))
    dialogtitle.value = '修改系统设备'
    isSwitch.value = false
    dialogVisible.value = true
}
function delclick(row: any) {
    ElMessageBox.confirm("确定删除此系统设备信息吗?", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        let params = {
            id: row.id,
        };
        deleteSystemDeviceById(params).then((res: any) => {
            if (res.code == 0) {
                getData()
                ElMessage({
                    message: '删除成功',
                    type: 'success',
                })
            }
        })
    });
}
function addclick() {
    isSwitch.value = false
    dialogtitle.value = '新增系统设备'
    dialogVisible.value = true
    if (ruleFormRef.value != null) ruleFormRef.value.resetFields();
    manageFromm.value = {
        deviceCode: "",
        deviceName: "",
        deviceType: "",
        deviceDesc: "",
        deviceModel: "",
        productionNum: "",
        productionDate: "",
        manufacturer: "",
        madein: "",
        phyassetId: "",
        frequency: "",
        status: "02",
        urcb: "",
        brcb: "",
        protocol: 'IEC104'
    }
}
function delclicks() {
    let id = [] as any[];
    multipleSelection.value.forEach((item: any) => {
        id.push(item.id)
    })

    ElMessageBox.confirm("确定删除勾选的系统设备信息吗?", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        let params = {
            ids: id.join(','),
        };
        deleteSystemDeviceByIds(params).then((res: any) => {
            if (res.code == 0) {
                getData()
                ElMessage({
                    message: '删除成功',
                    type: 'success',
                })
            }
        })
    });
}
const isSwitch = ref(false)
function formsubmit(formEl: any) {
    formEl.validate((valid: any) => {
        if (valid) {
            if (manageFromm.value.protocol == 'IEC104') {
                if (manageFromm.value.iecAddr == '' || manageFromm.value.iecAddr == undefined) {
                    ElMessage({
                        message: "请填写104协议地址!",
                        type: "warning",
                    });
                    return
                }
            }
            if (manageFromm.value.protocol == 'IEC61850') {
                if (manageFromm.value.urcb == '' || manageFromm.value.urcb == undefined) {
                    ElMessage({
                        message: "请填写遥测类报告控制块!",
                        type: "warning",
                    });
                    return
                }
                if (manageFromm.value.brcb == '' || manageFromm.value.brcb == undefined) {
                    ElMessage({
                        message: "请填写遥信类报告控制块!",
                        type: "warning",
                    });
                    return
                }
            }
            if (isSwitch.value == true) {
                return
            }
            isSwitch.value = true
            manageFromm.value.stationId = userStore.stationId
            if (manageFromm.value.id) {
                updateSystemDevice(manageFromm.value).then((res: any) => {
                    if (res.code == 0) {
                        ElMessage({
                            message: "保存成功",
                            type: "success",
                        });
                        dialogVisible.value = false
                        getData()
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: "error",
                        });
                        isSwitch.value = false
                    }


                }).catch(() => {
                    isSwitch.value = false
                })
            } else {
                addSystemDevice(manageFromm.value).then((res: any) => {
                    if (res.code == 0) {
                        ElMessage({
                            message: "保存成功",
                            type: "success",
                        });
                        dialogVisible.value = false
                        getData()
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: "error",
                        });
                        isSwitch.value = false
                    }
                }).catch(() => {
                    isSwitch.value = false
                })
            }
            loading.value = false
        }
    })
}
const ruleFormRef: any = ref(null);
function handleClose() {
    if (ruleFormRef.value != null) ruleFormRef.value.resetFields();
    dialogVisible.value = false
}
function seletClick() {
    queryInfo.value.current = 1
    getData()
}
function clearClick() {
    queryInfo.value = {
        size: 10,
        total: 0,
        current: 1,
        deviceName: '',
        deviceModel: '',
        deviceType: '',
        status: ''
    }
    getData()
}
function editstatus(list: any, val: any) {
    manageFromm.value = list
    manageFromm.value.status = val
    let tipstext = '停用'
    if (val === '01') {
        tipstext = '连接'
    }
    updateSystemDevice(manageFromm.value).then((res: any) => {
        if (res.code == 0) {
            ElMessage({
                message: tipstext + "成功",
                type: "success",
            });
            getData()
        } else {
            ElMessage({
                message: tipstext + "失败",
                type: "error",
            });
        }
    }).catch(() => {

    })
}
const tableRowClassName = ({
    row,
    rowIndex,
}: {
    row: any
    rowIndex: number
}) => {
    if (rowIndex % 2 === 0) {
        return 'warning-row'
    } else if (rowIndex % 2 === 1) {
        return 'success-row'
    }
    return ''
}
</script>

<template>
    <div style=" padding: 17px 15px 8px 15px;">
        <div class="record-box">
            <div style="margin-bottom: 10px;display: flex;align-items: center;justify-content:space-between;">
                <div style=" display:flex;align-items: center;">
                    <el-input v-model="queryInfo.deviceName" placeholder="请输入设备名称" style="width: 220px;" clearable />
                    <el-input v-model="queryInfo.deviceModel" placeholder="请输入设备型号"
                        style="width: 220px;margin-left: 10px;" clearable />
                    <el-select v-model="queryInfo.deviceType" placeholder="请选择设备类型"
                        style="width: 220px;margin-left: 10px;" clearable @change="seletClick">
                        <el-option v-for="item in EquipmentType" :key="item.itemcode" :label="item.dictname"
                            :value="item.itemcode" />
                    </el-select>
                    <el-select v-model="queryInfo.status" placeholder="请选择设备状态" style="width: 220px;margin-left: 10px;"
                        clearable @change="seletClick">
                        <el-option v-for="item in statusoption" :key="item.itemcode" :label="item.dictname"
                            :value="item.itemcode" />
                    </el-select>
                    <el-button type="primary" class="searchButton" style="margin-left: 10px;"
                        @click="seletClick">搜索</el-button>
                    <el-button type="primary" class="searchButton" plain style="margin-left: 10px;"
                        @click="clearClick">重置</el-button>
                </div>

                <div style=" display:flex;align-items: center;">
                    <el-button class="searchButton" type="primary" style="margin-left: 10px;" @click="addclick">新增</el-button>
                    <el-button class="searchButton" :type="multipleSelection.length <= 0 ? '' : 'primary'"
                        :disabled="multipleSelection.length <= 0 ? true : false" style="margin-left: 10px;"
                        @click="delclicks">删除</el-button>
                </div>

            </div>
            <el-table ref="multipleTableRef" v-loading="loading" :data="tableData" row-key="id" border
                @selection-change="handleSelectionChange" style="width: 100%;height: calc(100vh - 285px)"
                :row-class-name="tableRowClassName"
                :header-cell-style="{ background: '#002b6a', color: '#B5D7FF', height: '50px' }">
                <el-table-column type="selection" align="center" width="55" />
                <el-table-column label="序号" align="center"  type="index" width="50" />
                <el-table-column label="设备编号" align="center"  prop="deviceCode" width="80" />
                <el-table-column label="设备名称" align="center"  prop="deviceName" width="180" />
                <el-table-column label="设备类型" align="center"  prop="deviceType" width="160">
                    <template #default="scope">
                        <span>{{ currency(EquipmentType, scope.row.deviceType) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="中文描述" align="left"  prop="deviceDesc" min-width="100" />
                <el-table-column label="设备型号" align="center"  prop="deviceModel" width="100" />
                <el-table-column label="出厂编号" align="center"  prop="productionNum" width="100" />
                <el-table-column label="出厂日期" prop="productionDate" width="100" align="center" />
                <el-table-column label="生产厂家" align="center" width="100" prop="manufacturer" min-width="100" />
                <el-table-column label="生产国家" prop="madein" width="100" align="center" />
                <el-table-column label="以太网IP地址" align="center"  prop="ipAddr" width="150" />
                <el-table-column prop="status" label="设备状态" width="100" align="center">
                    <template #default="scope">
                        <span v-if="scope.row.status === '00'" style="font-size: 14px;color:#FF3300;">停用</span>
                        <span v-else-if="scope.row.status === '01'" style="font-size: 14px;color: #00CC00;">已连接</span>
                        <span v-else-if="scope.row.status === '02'" style="font-size: 14px;color: #FFCC00;">离线</span>
                    </template>
                </el-table-column>
                <el-table-column align="center"  fixed="right" label="操作" width="110">
                    <template #default="scope">
                        <span
                            style="display: flex;display: -webkit-flex;justify-content: space-around; -webkit-justify-content: space-around; ">
                            <img  src="@/assets/newimg/ht_xg.png"  title="修改"
                                style="cursor: pointer;" @click="editclick(scope.row)">
                            <img v-if="scope.row.status === '02'" 
                                src="@/assets/newimg/lj.png" title="连接" style="cursor: pointer;"
                                @click="editstatus(scope.row, '01')">
                            <img v-if="scope.row.status === '02'" 
                                src="@/assets/newimg/ty.png" title="停用" style="cursor: pointer;"
                                @click="editstatus(scope.row, '00')">
                            <img src="@/assets/newimg/ht_sc.png"  title="删除"
                                style="cursor: pointer;" @click="delclick(scope.row)">
                        </span>
                    </template>
                </el-table-column>

            </el-table>
            <Page class="mt-[20px]" :total="queryInfo.total" v-model:size="queryInfo.size"
                v-model:current="queryInfo.current" @pagination="getData" />
        </div>
        <Eldialog v-if="dialogVisible" :title="dialogtitle" :zIndex="2000" :width="'50%'" @before-close="handleClose">
            <template v-slot:PopFrameContent>
                <el-form ref="ruleFormRef" :rules="Mainrules" :model="manageFromm" label-width="130px" style="margin-top:15px;">
                    <div style="display: flex;">
                        <el-form-item label="设备编号" prop="deviceCode" style="width: 50%;">
                            <el-input v-model="manageFromm.deviceCode" maxlength="40" show-word-limit
                                placeholder="请输入设备编号" clearable />
                        </el-form-item>
                        <el-form-item label="设备名称" prop="deviceName" style="width: 50%;">
                            <el-input v-model="manageFromm.deviceName" maxlength="100" show-word-limit
                                placeholder="请输入设备名称" clearable />
                        </el-form-item>
                    </div>
                    <div style="display: flex;">
                        <el-form-item label="设备类型" prop="deviceType" style="width: 50%;">
                            <el-select v-model="manageFromm.deviceType" placeholder="请选择设备类型" style="width: 100%;">
                                <el-option v-for="item in EquipmentType" :key="item.itemcode" :label="item.dictname"
                                    :value="item.itemcode" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="设备型号" style="width: 50%;">
                            <el-input v-model="manageFromm.deviceModel" maxlength="100" show-word-limit
                                placeholder="请输入设备型号" clearable />
                        </el-form-item>
                    </div>
                    <el-form-item label="中文描述">
                        <el-input v-model="manageFromm.deviceDesc" maxlength="100" show-word-limit placeholder="请输入中文描述"
                            clearable />
                    </el-form-item>
                    <div style="display: flex;">
                        <el-form-item label="出厂编号" style="width: 50%;">
                            <el-input v-model="manageFromm.productionNum" maxlength="40" show-word-limit
                                placeholder="请输入出厂编号" clearable />
                        </el-form-item>
                        <el-form-item label="出厂日期" style="width: 50%;">
                            <el-date-picker v-model="manageFromm.productionDate" type="date" value-format="YYYY-MM-DD"
                                style="width:100%" placeholder="请输入出厂日期" />
                        </el-form-item>
                    </div>
                    <div style="display: flex;">
                        <el-form-item label="生产厂家" style="width: 50%;">
                            <el-input v-model="manageFromm.manufacturer" maxlength="100" show-word-limit
                                placeholder="请输入生产厂家" clearable />
                        </el-form-item>
                        <el-form-item label="生产国家" style="width: 50%;">
                            <el-input v-model="manageFromm.madein" maxlength="100" show-word-limit placeholder="请输入生产国家"
                                clearable />
                        </el-form-item>
                    </div>
                    <div style="display: flex;">
                        <el-form-item label="实物ID" style="width: 50%;">
                            <el-input v-model="manageFromm.phyassetId" maxlength="40" show-word-limit
                                placeholder="请输入实物ID" clearable />
                        </el-form-item>
                        <el-form-item label="采集频率（秒）" style="width: 50%;">
                            <el-input v-model="manageFromm.frequency" placeholder="请输入采集频率" clearable />
                        </el-form-item>
                    </div>
                    <div style="display: flex;">
                        <el-form-item label="以太网Mac地址" style="width: 50%;">
                            <el-input v-model="manageFromm.macAddr" maxlength="40" show-word-limit
                                placeholder="请输入以太网Mac地址" clearable />
                        </el-form-item>
                        <el-form-item label="以太网IP地址" style="width: 50%;">
                            <el-input v-model="manageFromm.ipAddr" maxlength="40" show-word-limit
                                placeholder="请输入以太网IP地址" clearable />
                        </el-form-item>
                    </div>
                    <el-form-item label="协议类型" prop="protocol">
                        <el-select v-model="manageFromm.protocol" placeholder="请选择协议类型"  style="width: 100%;"  >
                            <el-option v-for="item in protocoloption" :key="item" :label="item" :value="item" />
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="manageFromm.protocol === 'IEC104'" label="104协议地址">
                        <el-input v-model="manageFromm.iecAddr" maxlength="40" show-word-limit placeholder="请输入104协议地址"
                            clearable />
                    </el-form-item>
                    <el-form-item v-if="manageFromm.protocol === 'IEC61850'" label="遥测类报告控制块">
                        <el-input v-model="manageFromm.urcb" maxlength="1000" show-word-limit type="textarea"
                            :autosize="{ minRows: 2 }" placeholder="请输入遥测类报告控制块" clearable />
                    </el-form-item>
                    <el-form-item v-if="manageFromm.protocol === 'IEC61850'" label="遥信类报告控制块">
                        <el-input v-model="manageFromm.brcb" maxlength="1000" show-word-limit type="textarea"
                            :autosize="{ minRows: 2 }" placeholder="请输入遥信类报告控制块" clearable />
                    </el-form-item>
                    <!-- <el-form-item v-if="dialogtitle === '修改系统设备'" label="设备状态">
            <el-radio-group v-model="manageFromm.status">
              <el-radio label="00">停用</el-radio>
              <el-radio label="02">离线</el-radio>
            </el-radio-group>
          </el-form-item> -->
                </el-form>
                <span class="dialog-footer" style="display: flex;justify-content: flex-end;">
                    <el-button class="searchButton" @click="handleClose">取消</el-button>
                    <el-button class="searchButton" type="primary" @click="formsubmit(ruleFormRef)">确定</el-button>
                </span>
            </template>
        </Eldialog>
    </div>
</template>

<style scoped>
.record-box {
    padding: 15px 8px 8px;
    width: 100%;
    height: calc(89vh);
    overflow: auto;
    background-color: rgba(255, 255, 255, 0);
    border: none;
    border-radius: 3px;
    box-sizing: border-box;
    background: url(@/assets/navigation/ty_1614x988.png);
    background-size: 100% 100%;
}
:deep(.el-input .el-input__count .el-input__count-inner){
    background-color: rgba(240, 248, 255, 0);
}
</style>
