<template>
    <div class="hc-page-layout-box">
        <div :style="`width:${leftWidth}px;`" class="hc-layout-left-box menu">
            <div class="hc-menu-header-box">
                <div class="text-xl name">自定义筛孔类型</div>
                <HcTooltip keys="tentative_parameter_sieve_menu_add">
                    <el-button _icon hc-btn size="small" type="primary" @click="addEditNodeFormModalClick">
                        <HcIcon name="add" />
                    </el-button>
                </HcTooltip>
            </div>
            <div class="hc-menu-contents-box">
                <el-scrollbar>
                    <HcMenuSimple
                        :datas="menus" :keys="menuKey" :menus="contextMenu" :props="menuProps"
                        @change="menuChange" @menuTap="contextMenuClick"
                    />
                </el-scrollbar>
            </div>
            <!-- 左右拖动 -->
            <div class="horizontal-drag-line" @mousedown="onmousedown" />
        </div>
        <div class="hc-page-content-box">
            <HcNewCard>
                <!-- <template #header>
                    <div class="w-72">
                        <el-input v-model="searchForm.queryValue" placeholder="请输入容器编号查询" clearable @keyup="keyUpEvent" size="large"/>
                    </div>
                    <div class="ml-2">
                        <el-button type="primary" @click="searchClick" size="large">
                            <HcIcon name="search-2"/>
                            <span>搜索</span>
                        </el-button>
                    </div>
                </template> -->
                <template #extra>
                    <HcTooltip keys="tentative_parameter_sieve_add">
                        <el-button :disabled="menus.length < 1 " hc-btn type="primary" @click="addFormModalClick">
                            <HcIcon name="add-circle" />
                            <span>新增</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_parameter_sieve_edit">
                        <el-button :disabled="tableCheckedKeys.length <= 0" hc-btn type="primary" color="#12C060" style="color: white;" @click="editFormModalClick">
                            <HcIcon name="edit" />
                            <span>编辑</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_parameter_sieve_del">
                        <el-button :disabled="tableCheckedKeys.length <= 0" hc-btn color="#e03997" @click="delNodeModalClick">
                            <HcIcon name="delete-bin-2" />
                            <span>删除</span>
                        </el-button>
                    </HcTooltip>
                </template>
                <HcTable
                    ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading"
                    is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
                    @selection-change="tableSelection"
                />
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange" />
                </template>
            </HcNewCard>
        </div>

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

        <!-- 新增/编辑 -->
        <hc-new-dialog
            v-model="addEditFormModal" :loading="addEditFormLoading" :title="`${addEditFormModel.id ? '编辑' : '新增'}筛孔尺寸信息`"
            widths="45rem" @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="sievePoreSize">
                        <el-input v-model="addEditFormModel.sievePoreSize" />
                    </el-form-item>
                    <el-form-item label="标准" prop="standard">
                        <el-input v-model="addEditFormModel.standard" />
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="下限" prop="lowerLimit">
                        <el-input v-model="addEditFormModel.lowerLimit" />
                    </el-form-item>
                    <el-form-item label="上限" prop="upperLimit">
                        <el-input v-model="addEditFormModel.upperLimit" />
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="限制区界限最大" prop="maxLimitBoundary">
                        <el-input v-model="addEditFormModel.maxLimitBoundary" />
                    </el-form-item>
                    <el-form-item label="限制区界限最小" prop="minLimitBoundary">
                        <el-input v-model="addEditFormModel.minLimitBoundary" />
                    </el-form-item>
                </div>
                <div class="hc-form-item">
                    <el-form-item label="控制点界限最大" prop="maxLimitControl">
                        <el-input v-model="addEditFormModel.maxLimitControl" />
                    </el-form-item>
                    <el-form-item label="控制点界限最小" prop="minLimitControl">
                        <el-input v-model="addEditFormModel.minLimitControl" />
                    </el-form-item>
                </div>
            </el-form>
        </hc-new-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { HcIsButton } from '~src/plugins/IsButtons'
import { arrToId, formValidate, getArrValue } from 'js-fast-way'
import dataApi from '~api/tentative/parameter/sieve'
import { delMessageV2 } from '~com/message/index.js'

//初始变量
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(() => {
    queryClassification()
    setContextMenu()
})

//左侧菜单
const menuKey = ref('')
const menus = ref([])
const menuProps = {
    key: 'id',
    label: 'name',
}
const queryClassification = async () => {
    const { data } = await dataApi.queryClassification({
        projectId: projectId.value,
        contractId: contractId.value,
    })
    const arr = getArrValue(data)
    menus.value = arr
    if (arr.length > 0) {
        menuChange(arr[0])
    }
}

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

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

//菜单的右键菜单被点击
const contextMenuItem = ref({})
const contextMenuClick = ({ key, item }) => {
    contextMenuItem.value = item
    if (key === 'edit') {
        addEditNodeFormModel.value = item
        addEditNodeFormModal.value = true
    } else if (key === 'del') {
        delMessageV2(async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                delClassification(item)
                instance.confirmButtonLoading = false
                done()
            } else {
                done()
            }
        })
    }
}

//搜索表单
const searchForm = ref({
    classId: null, queryValue: null,
    current: 1, size: 20, total: 0,
})

//回车搜索
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: 'sievePoreSize', name: '筛孔尺寸' },
    { key: 'lowerLimit', name: '下限' },
    { key: 'upperLimit', name: '上限' },
    { key: 'standard', name: '标准' },
    { key: 'maxLimitBoundary', name: '限制区最大' },
    { key: 'minLimitBoundary', name: '限制区最小' },
    { key: 'maxLimitControl', name: '控制点最大' },
    { key: 'minLimitControl', name: '控制点最小' },
])
const tableData = ref([])

//获取数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await dataApi.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
}

//新增/编辑 分类
const addEditNodeFormModal = ref(false)
const addEditNodeFormRef = ref(null)
const addEditNodeFormModel = ref({ name: '' })
const addEditNodeFormRules = {
    name: {
        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 dataApi.submitClassification({
            ...addEditNodeFormModel.value,
            projectId: projectId.value,
            contractId: contractId.value,
        })
        //处理数据

        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            addEditNodeFormModal.value = false
            addEditNodeFormLoading.value = false
            await queryClassification()
        }

        addEditFormLoading.value = false
        addEditNodeFormLoading.value = false
    }
}

//关闭分类编辑弹窗
const addEditNodeFormModalClose = () => {
    addEditNodeFormModal.value = false
}

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

//新增/编辑
const addEditFormModal = ref(false)
const addFormModalClick = () => {
    const { id } = menuItem.value
    addEditFormModel.value = {
        classId: id,
    }
    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
}

//新增/编辑 表单
const addEditFormRef = ref(null)
const addEditFormModel = ref({})
const addEditFormRules = {
    sievePoreSize: {
        required: true,
        trigger: 'blur',
        message: '请输入筛孔尺寸',
    },
    standard: {
        required: true,
        trigger: 'blur',
        message: '请输入标准',
    },
    upperLimit: {
        required: true,
        trigger: 'blur',
        message: '请输入上限',
    },
    lowerLimit: {
        required: true,
        trigger: 'blur',
        message: '请输入下限',
    },
    maxLimitBoundary: {
        required: true,
        trigger: 'blur',
        message: '请输入限制区界限最大',
    },
    minLimitBoundary: {
        required: true,
        trigger: 'blur',
        message: '请输入限制区界限最小',
    },
    maxLimitControl: {
        required: true,
        trigger: 'blur',
        message: '请输入控制点界限最小',
    },
    minLimitControl: {
        required: true,
        trigger: 'blur',
        message: '请输入标准',
    },
}

//新增/编辑 保存
const addEditFormLoading = ref(false)
const addEditFormClick = async () => {
    const validate = await formValidate(addEditFormRef.value)
    if (validate) {
        addEditFormLoading.value = true
        //发起请求
        const { error, code } = await dataApi.submitForm({
            ...addEditFormModel.value,
            projectId: projectId.value,
            contractId: contractId.value,
        })
        //处理数据

        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            addEditFormModal.value = false
            addEditFormLoading.value = false
            await getTableData()
        }
    }
}


//删除分类
const delNodeModalClick = () => {
    delMessageV2(async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                tableRemoveData()
                instance.confirmButtonLoading = false
                done()
            } else {
                done()
            }
     })
}

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

//左右拖动，改变树形结构宽度
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>
