<template>
    <div class="hc-page-layout-box">
        <div class="hc-layout-left-box menu" :style="'width:' + leftWidth + 'px;'">
            <div class="hc-menu-header-box">
                <div class="text-xl name">设备分类</div>
                <HcTooltip keys="tentative_device_approach_menu_add">
                    <el-button type="primary" hc-btn _icon size="small" @click="addEditNodeFormModalClick">
                        <HcIcon name="add"/>
                    </el-button>
                </HcTooltip>
            </div>
            <div class="hc-menu-contents-box">
                <el-scrollbar>
                    <HcMenuSimple :props="menusProps" :datas="menus" :keys="menuKey" :menus="contextMenu" @change="menuChange" @menuTap="contextMenuClick"/>
                </el-scrollbar>
            </div>
            <!--左右拖动-->
            <div class="horizontal-drag-line" @mousedown="onmousedown"/>
        </div>
        <div class="hc-page-content-box">
            <HcCard>
                <template #header>
                    <HcTooltip keys="tentative_device_approach_add">
                        <el-button type="primary" hc-btn @click="addFormModalClick">
                            <HcIcon name="add-circle"/>
                            <span>新增</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_device_approach_edit">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="editFormModalClick">
                            <HcIcon name="edit"/>
                            <span>编辑</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_device_approach_del">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="delTableModalClick">
                            <HcIcon name="delete-bin-2"/>
                            <span>删除</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_device_approach_printer">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" :loading="printerLoading" @click="printerClick">
                            <HcIcon name="printer"/>
                            <span>打印</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_device_approach_import">
                        <el-button hc-btn @click="importModalClick">
                            <HcIcon name="folder-upload"/>
                            <span>导入</span>
                        </el-button>
                    </HcTooltip>
                </template>
                <template #search>
                    <div class="w-32">
                        <el-select v-model="searchForm.isCalibration" placeholder="是否需要效验" clearable>
                            <el-option label="是" :value="1"/>
                            <el-option label="否" :value="0"/>
                        </el-select>
                    </div>
                    <div class="w-32 ml-2">
                        <el-select v-model="searchForm.status" placeholder="状态" clearable>
                            <el-option label="启用中" :value="1"/>
                            <el-option label="已停用" :value="0"/>
                        </el-select>
                    </div>
                    <div class="w-64 ml-2">
                        <HcDatePicker :dates="betweenTime" clearable @change="betweenTimeUpdate"/>
                    </div>
                    <div class="w-72 ml-2">
                        <el-input v-model="searchForm.queryValue" placeholder="请输入设备名称\设备型号查询" clearable @keyup="keyUpEvent"/>
                    </div>
                    <div class="ml-2">
                        <el-button type="primary" @click="searchClick">
                            <HcIcon name="search-2"/>
                            <span>搜索</span>
                        </el-button>
                    </div>
                </template>
                <HcTable ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading" isCheck @selection-change="tableSelection">
                    <template #status="{row}">
                        {{row.status === 1?'启用中':'已停用'}}
                    </template>
                    <template #isCalibration="{row}">
                        {{row.isCalibration === 1?'是':'否'}}
                    </template>
                </HcTable>
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange"/>
                </template>
            </HcCard>
        </div>

        <!--新增/编辑 节点-->
        <HcDialog :show="addEditNodeFormModal" :title="`${addEditNodeFormModel.id?'编辑':'新增'}分类`" widths="30rem" :loading="addEditNodeFormLoading" @save="addEditNodeFormModalSave" @close="addEditNodeFormModalClose">
            <el-form ref="addEditNodeFormRef" :model="addEditNodeFormModel" :rules="addEditNodeFormRules" label-width="auto" label-position="top" size="large">
                <el-form-item class="mb-0" label="分类名称" prop="className">
                    <el-input v-model="addEditNodeFormModel.className" placeholder="请输入分类名称"/>
                </el-form-item>
            </el-form>
        </HcDialog>

        <!--新增/编辑-->
        <HcDialog :show="addEditFormModal" :title="`${addEditFormModel.id?'编辑':'新增'}设备信息`" widths="50rem" :loading="addEditFormLoading" @close="addEditFormModalClose" @save="addEditFormClick">
            <el-form ref="addEditFormRef" :model="addEditFormModel" :rules="addEditFormRules" label-width="auto" size="large">
                <div class="hc-form-item">
                    <el-form-item label="设备名称" prop="deviceName">
                        <el-input v-model="addEditFormModel.deviceName"/>
                    </el-form-item>
                    <el-form-item label="进场日期">
                        <el-date-picker type="date" v-model="addEditFormModel.mobilizationDate" class="block" value-format="YYYY-MM-DD" :clearable="false"/>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="设备分类" prop="deviceClassId">
                        <el-select v-model="addEditFormModel.deviceClassId" block>
                            <el-option v-for="item in typeData" :label="item.className" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="测量范围">
                        <el-input v-model="addEditFormModel.measuringRange"/>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="设备编号">
                        <el-input v-model="addEditFormModel.deviceNumber"/>
                    </el-form-item>
                    <el-form-item label="精准度">
                        <el-input v-model="addEditFormModel.accuracy"/>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="设备型号">
                        <el-input v-model="addEditFormModel.deviceModel"/>
                    </el-form-item>
                    <el-form-item label="效验周期">
                        <HcCounter v-model="addEditFormModel.calibrationCycle" text="(月)" size="large" block/>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="生产厂家">
                        <el-input v-model="addEditFormModel.manufacturer"/>
                    </el-form-item>
                    <el-form-item label="最近效验时间">
                        <el-date-picker type="date" v-model="addEditFormModel.lastCalibrationTime" class="block" value-format="YYYY-MM-DD" :clearable="false"/>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="出厂日期">
                        <el-date-picker type="date" v-model="addEditFormModel.factoryDate" class="block" value-format="YYYY-MM-DD" :clearable="false"/>
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-select v-model="addEditFormModel.status" placeholder="状态" block>
                            <el-option label="启用中" :value="1"/>
                            <el-option label="已停用" :value="0"/>
                        </el-select>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="出厂编号">
                        <el-input v-model="addEditFormModel.factoryNumber"/>
                    </el-form-item>
                    <el-form-item label="管理人员">
                        <hcAutoComplete v-model="addEditFormModel.managerName" :datas="userListData" keys="userName" placeholder="请选择或输入试验人员名称"/>
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="设备采集编号">
                        <el-input v-model="addEditFormModel.equipmentAcquisitionNumber"/>
                    </el-form-item>
                    <el-form-item label="是否需要效验">
                        <el-select v-model="addEditFormModel.isCalibration" block disabled>
                            <el-option label="是" :value="1"/>
                            <el-option label="否" :value="0"/>
                        </el-select>
                    </el-form-item>
                </div>
                <el-form-item label="备注">
                    <el-input v-model="addEditFormModel.remarks" type="textarea" placeholder="备注" :autosize="{ minRows: 3}"/>
                </el-form-item>
            </el-form>
        </HcDialog>

        <!--导入-->
        <HcDialog :show="importModal" title="导入设备数据" widths="70rem" isTable isFooterCenter :loading="importModalLoading" @save="importModalYesClick" @close="importModalClose">
            <div class="text-orange mb-6">
                <span>请先下载模板模板表格 (</span>
                <span class="text-link">范例试验设备文件</span>
                <span>) ,按模板样式编辑试验容器后，在点击“选择文件”按钮选择编辑好的文件，点击确认即可导入成功！</span>
            </div>
            <HcDragUpload/>
            <div class="hc-import-modal-table-box">
                <HcTable ref="tableImportRef" :column="tableColumn" :datas="tableImportData" :loading="tableImportLoading" isCheck @selection-change="tableImportSelection"/>
            </div>
        </HcDialog>

    </div>
</template>

<script setup>
import {ref, onMounted, watch} from "vue";
import {useAppStore} from "~src/store";
import {HcIsButton} from "~src/plugins/IsButtons";
import HcDragUpload from "./components/HcDragUpload.vue"
import approachApi from "~api/tentative/device/approach";
import {formValidate, getArrValue} from "vue-utils-plus"
import {getContractUserList} from "~api/other";

//初始变量
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);
const isCollapse = ref(useAppState.getCollapse)

//监听
watch(() => [
    useAppState.getCollapse
], ([Collapse]) => {
    isCollapse.value = Collapse
})

//渲染完成
onMounted(() => {
    getClassListData()
    setContextMenu()
    getTableData()
    getUserListData()
})

//获取用户列表
const userListData = ref([])
const getUserListData = async () => {
    const { data } = await getContractUserList({
        contractId: contractId.value
    })
    userListData.value = getArrValue(data)
}

//左侧菜单
const menuKey = ref('0')
const menuItem = ref({})
const menusProps = ref({
    key: 'id',
    label: 'className'
})
//获取菜单数据
const menus = ref([]);
const typeData = ref([]);
const getClassListData = async () => {
    const { data } = await approachApi.getClassList({
        contractId: contractId.value
    })
    const arr = getArrValue(data)
    typeData.value = arr
    menus.value = [{id: '0', className: '全部', isNoContextMenu: true}, ...arr]
}

//菜单被点击
const menuChange = (item) => {
    menuItem.value = item
    menuKey.value = item?.id
    searchForm.value.deviceClassId = item?.id
    searchForm.value.current = 1;
    getTableData()
}

//菜单的右键菜单
const contextMenu = ref([])
const setContextMenu = () => {
    let newArr = [];
    if (HcIsButton('tentative_device_approach_menu_edit')) {
        newArr.push({icon: 'draft', label: '编辑分类', key: "edit"})
    }
    if (HcIsButton('tentative_device_approach_menu_del')) {
        newArr.push({icon: 'delete-bin', label: '删除分类', key: "del"})
    }
    contextMenu.value = newArr
}

//菜单的右键菜单被点击
const contextMenuClick = ({key, item}) => {
    if (key === 'edit') {
        addEditNodeFormModel.value = item
        addEditNodeFormModal.value = true
    } else if (key === 'del') {
        delNodeModalClick(item.id)
    }
}

//搜索表单
const searchForm = ref({
    deviceClassId: '', isCalibration: null, status: null, startTime: null, endTime: null, queryValue: null,
    current: 1, size: 20, total: 0
})

//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({arr}) => {
    betweenTime.value = arr
    if (arr.length > 0) {
        searchForm.value.startTime = arr[0]
        searchForm.value.endTime = arr[1]
    }
}

//回车搜索
const keyUpEvent = (e) => {
    if (e.key === "Enter") {
        searchForm.value.current = 1;
        getTableData()
    }
}

//搜索
const searchClick = () => {
    searchForm.value.current = 1;
    getTableData()
}

//分页被点击
const pageChange = ({current, size}) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//表格数据
const tableRef = ref(null)
const tableColumn = ref([
    {key:'deviceName', name: '设备名称', width: '200'},
    {key:'deviceClassName', name: '设备分类', width: '160'},
    {key:'deviceNumber', name: '设备编号', width: '160'},
    {key:'deviceModel', name: '设备型号', width: '180'},
    {key:'manufacturer', name: '生产厂家', width: '200'},
    {key:'factoryDate', name: '出厂日期', width: '160'},
    {key:'factoryNumber', name: '出厂编号', width: '160'},
    {key:'mobilizationDate', name: '进场日期', width: '160'},
    {key:'measuringRange', name: '测量范围', width: '120'},
    {key:'accuracy', name: '精准度', width: '120'},
    {key:'calibrationCycle', name: '校准周期(月)', width: '120'},
    {key:'lastCalibrationTime', name: '最近效验时间', width: '160'},
    {key:'status', name: '状态', width: '100'},
    {key:'isCalibration', name: '是否需要效验', width: '120'},
    {key:'equipmentAcquisitionNumber', name: '设备采集编号', width: '160'},
    {key:'managerName', name: '设备管理人员', width: '120'},
    {key:'remarks', name: '备注', width: '160'},
])
const tableData = ref([])

//获取数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await approachApi.queryPage({
        projectId: projectId.value,
        contractId: contractId.value,
        ...searchForm.value,
    })
    //处理数据
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data.total || 0
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}

//多选
const tableCheckedKeys = ref([]);
const tableSelection = (rows) => {
    tableCheckedKeys.value = rows.filter((item) => {
        return (item??'') !== '';
    })
}

//新增/编辑 分类
const addEditNodeFormRef = ref(null)
const addEditNodeFormModal = ref(false)

//分类表单
const addEditNodeFormModel = ref({
    className: ''
})
const addEditNodeFormRules = {
    className: {
        required: true,
        trigger: 'blur',
        message: "请输入分类名称"
    },
}

//新增分类弹窗打开
const addEditNodeFormModalClick = () => {
    addEditNodeFormModel.value = {}
    addEditNodeFormModal.value = true
}

//保存节点信息
const addEditNodeFormLoading = ref(false)
const addEditNodeFormModalSave = async () => {
    const validate = await formValidate(addEditNodeFormRef.value)
    if (validate) {
        addEditNodeFormLoading.value = true
        const { error, code } = await approachApi.getClassSubmit({
            ...addEditNodeFormModel.value,
            projectId: projectId.value,
            contractId: contractId.value
        })
        //处理数据
        addEditNodeFormLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            addEditNodeFormModal.value = false
            await getClassListData()
        }
    }
}
//关闭分类编辑弹窗
const addEditNodeFormModalClose = () => {
    addEditNodeFormModel.value = {}
    addEditNodeFormModal.value = false
}

//删除分类
const delNodeModalClick = (id) => {
    window?.$messageBox?.alert('请谨慎考虑后，确认是否需要删除？', '删除提醒', {
        showCancelButton: true,
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        callback: (action) => {
            if (action === 'confirm') {
                setClassRemove(id)
            }
        }
    })
}

//删除分类
const setClassRemove = async (id) => {
    const { error, code } = await approachApi.setClassRemove({
        projectId: projectId.value,
        contractId: contractId.value,
        id: id
    })
    //处理数据
    if (!error && code === 200) {
        window?.$message?.success('操作成功')
        await getClassListData()
    }
}

//删除表格数据
const delTableModalClick = () => {
    window?.$messageBox?.alert('请谨慎考虑后，确认是否需要删除？', '删除提醒', {
        showCancelButton: true,
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        callback: (action) => {
            if (action === 'confirm') {
                tableRemoveData()
            }
        }
    })
}

//批量删除
const tableRemoveData = async () => {
    const rows = tableCheckedKeys.value
    if (rows.length > 0 ) {
        const ids = rowsToId(rows)
        //删除请求
        const { error, code } = await approachApi.removeData({
            contractId: contractId.value,
            ids: ids,
        })
        //处理数据
        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            searchClick()
        }
    }
}

//打印
const printerLoading = ref(false)
const printerClick = async () => {
    const rows = tableCheckedKeys.value
    if (rows.length > 0 ) {
        printerLoading.value = true
        const ids = rowsToId(rows)
        //删除请求
        const { error, code, data } = await approachApi.exportPdf({
            projectId: projectId.value,
            contractId: contractId.value,
            ids: ids,
        })
        //处理数据
        printerLoading.value = false
        if (!error && code === 200) {
            window.open(data,'_blank')
        }
    }
}


//导入
const importModal = ref(false)
const importModalClick = () => {
    importModal.value = true
}

//确认导入
const importModalLoading = ref(false)
const importModalYesClick = () => {
    importModal.value = false
}

//关闭导入
const importModalClose = () => {
    importModal.value = false
}

//表格数据
const tableImportRef = ref(null)
const tableImportLoading = ref(false)
const tableImportData = ref([])

//多选
const tableImportKeys = ref([]);
const tableImportSelection = (rows) => {
    tableImportKeys.value = rows.filter((item) => {
        return (item??'') !== '';
    })
}


//新增/编辑 表单
const addEditFormRef = ref(null)
const addEditFormModel = ref({})
const addEditFormRules = {
    deviceName: {
        required: true,
        trigger: 'blur',
        message: "请输入设备名称"
    },
    deviceClassId: {
        required: true,
        trigger: 'blur',
        message: "请选择设备分类"
    },
}

//新增 设备信息
const addEditFormModal = ref(false)
const addFormModalClick = () => {
    addEditFormModel.value = {
        isCalibration: 0,
        status: 1,
    }
    addEditFormModal.value = true
}

//编辑 设备信息
const editFormModalClick = () => {
    const keys = tableCheckedKeys.value
    if (keys.length === 1) {
        addEditFormModel.value = keys[0]
        addEditFormModal.value = true
    } else if (keys.length > 1) {
        window?.$message?.warning('只能选择一条数据编辑')
    }
}

//关闭新增/编辑的弹窗
const addEditFormModalClose = () => {
    addEditFormModal.value = false
    addEditFormModel.value = {
        isCalibration: 0,
        status: 1
    }
}

//新增/编辑 保存
const addEditFormLoading = ref(false)
const addEditFormClick = async () => {
    const validate = await formValidate(addEditFormRef.value)
    if (validate) {
        addEditFormLoading.value = true
        const { error, code } = await approachApi.submitForm({
            ...addEditFormModel.value,
            projectId: projectId.value,
            contractId: contractId.value
        })
        //处理数据
        addEditFormLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            addEditFormModal.value = false
            await getTableData()
        }
    }
}

//拼接ID
const rowsToId = (rows) => {
    return rows.map((obj) => {
        return obj.id;
    }).join(",")
}

//左右拖动，改变树形结构宽度
const leftWidth = ref(240);
const onmousedown = () => {
    const leftNum = isCollapse.value ? 142 : 272
    document.onmousemove = (ve) => {
        let diffVal = ve.clientX - leftNum;
        if(diffVal >= 220 && diffVal <= 400) {
            leftWidth.value = diffVal;
        }
    }
    document.onmouseup = () => {
        document.onmousemove = null;
        document.onmouseup = null;
    }
}
</script>

<style lang="scss" scoped>
.hc-import-modal-table-box {
    position: relative;
    height: calc(100% - 228px);
    margin-top: 25px;
}
</style>
