<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_parameter_container_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 :datas="menus" :props="menuProps" :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>
                    <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_container_add">
                        <el-button type="primary" hc-btn @click="addFormModalClick">
                            <HcIcon name="add-circle"/>
                            <span>新增</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_parameter_container_edit">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="editFormModalClick">
                            <HcIcon name="edit"/>
                            <span>编辑</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_parameter_container_del">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0" @click="delTableModalClick">
                            <HcIcon name="delete-bin-2"/>
                            <span>删除</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_parameter_container_printer">
                        <el-button hc-btn :disabled="tableCheckedKeys.length <= 0">
                            <HcIcon name="printer"/>
                            <span>打印</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_parameter_container_import">
                        <el-button hc-btn @click="importModalClick">
                            <HcIcon name="folder-upload"/>
                            <span>导入</span>
                        </el-button>
                    </HcTooltip>
                </template>
                <HcTable ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading" isCheck @selection-change="tableSelection"/>
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange"/>
                </template>
            </HcCard>
        </div>

        <!--新增/编辑 节点-->
        <HcDialog :show="addEditNodeFormModal" :title="`${addEditNodeFormModel.id?'编辑':'新增'}试验容器`" widths="30rem" isRowFooter @close="addEditNodeFormModalClose">
            <el-form :model="addEditNodeFormModel" label-width="auto" label-position="top" size="large">
                <el-form-item label="试验容器名称">
                    <el-input v-model="addEditNodeFormModel.containerName" placeholder="请输入试验容器名称"/>
                </el-form-item>
                <template v-for="(item, index) in addEditNodeFormModel.fieldList">
                    <div class="hc-form-item">
                        <el-form-item class="w-32" label="数据类型" style="flex: initial;">
                            <el-select v-model="item.fieldType" block>
                                <el-option label="文本" :value="1"/>
                                <el-option label="日期框" :value="2"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="字段名">
                            <template #label>
                                <div class="solt-label">
                                    <span class="mr-1">字段名</span>
                                    <span class="text-xs text-slate-400" v-if="index === 0">第一个作为编号,是唯一的</span>
                                </div>
                                <div class="solt-extra">
                                    <el-button type="primary" plain size="small" @click="addEditNodeDataDel(item,index)">删除</el-button>
                                </div>
                            </template>
                            <el-input v-model="item.fieldName" block/>
                        </el-form-item>
                    </div>
                </template>
            </el-form>
            <template #leftRowFooter>
                <el-button size="large" @click="addEditNodeDataAdd">
                    <HcIcon name="add"/>
                    <span>加字段</span>
                </el-button>
            </template>
            <template #rightRowFooter>
                <el-button size="large" @click="addEditNodeFormModalClose">
                    <HcIcon name="close"/>
                    <span>取消</span>
                </el-button>
                <el-button type="primary" hc-btn :loading="addEditNodeFormLoading" @click="addEditNodeFormModalSave">
                    <HcIcon name="check"/>
                    <span>提交</span>
                </el-button>
            </template>
        </HcDialog>

        <!--新增/编辑-->
        <HcDialog :show="addEditFormModal" :title="`${addEditFormModel.id?'编辑':'新增'}数据`" widths="30rem" :loading="addEditFormLoading" @close="addEditFormModalClose" @save="addEditFormClick">
            <el-form ref="addEditFormRef" :model="addEditFormModel" :rules="addEditFormRules" label-width="auto" size="large">
                <template v-for="(item, index) in tableColumn">
                    <el-form-item :label="item.name" :prop="item.key">
                        <el-input v-model="addEditFormModel[item.key]" :placeholder="`${index===0?'作为编号，是唯一的':'请输入' + item.name}`" v-if="item.type === 1"/>
                        <el-date-picker type="date" v-model="addEditFormModel[item.key]" class="block" value-format="YYYY-MM-DD" :clearable="false" v-if="item.type === 2"/>
                    </el-form-item>
                </template>
            </el-form>
        </HcDialog>

        <!--导入-->
        <HcDialog :show="importModal" title="导入" widths="38rem" isRowFooter @close="importModalClose">
            <HcDragUpload/>
            <template #leftRowFooter>
                <el-button size="large">
                    <HcIcon name="download-2"/>
                    <span>下载模板</span>
                </el-button>
            </template>
            <template #rightRowFooter>
                <el-button size="large" @click="importModalClose">
                    <HcIcon name="close"/>
                    <span>取消导入</span>
                </el-button>
                <el-button type="primary" hc-btn :loading="importModalLoading" @click="importModalYesClick">
                    <HcIcon name="folder-upload"/>
                    <span>确认导入</span>
                </el-button>
            </template>
        </HcDialog>

    </div>
</template>

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

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

//左侧菜单
const menuProps = {
    key: 'id',
    label: 'containerName',
}
const menus = ref([]);
const getMenusData = async () => {
    const { data } = await dataApi.queryClassification({
        projectId: projectId.value,
        contractId: contractId.value
    })
    const arr = getArrValue(data)
    menus.value = arr
    if (arr.length > 0) {
        const item = arr[0]
        menuItem.value = item
        menuKey.value = item?.id
        setMenuTableColumn(item?.fieldList)
    }
}

//菜单被点击
const menuKey = ref('')
const menuItem = ref({})
const menuChange = (item) => {
    menuItem.value = item
    menuKey.value = item?.id
    setMenuTableColumn(item?.fieldList)
}

//设置表格头
const setMenuTableColumn = (data) => {
    let newArr = [];
    for (let i = 0; i < data.length; i++) {
        newArr.push({
            key: data[i].fieldKey,
            name: data[i].fieldName,
            type: data[i].fieldType
        })
    }
    newArr.push({
        key: 'field_calibration_time',
        name: '校准日期',
        type: 2
    })
    tableColumn.value = newArr
    //取列表数据
    searchClick()
    setAddEditFormRules(newArr)
}

//菜单的右键菜单
const contextMenu = ref([])
const setContextMenu = () => {
    let newArr = [];
    if (HcIsButton('tentative_parameter_container_menu_edit')) {
        newArr.push({icon: 'draft', label: '编辑容器', key: "edit"})
    }
    if (HcIsButton('tentative_parameter_container_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({
    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([])
const tableData = ref([])

//获取数据
const tableLoading = ref(false)
const getTableData = async () => {
    const {id, fieldList} = menuItem.value
    const fieldLists = getArrValue(fieldList)
    if (fieldLists.length > 0) {
        tableLoading.value = true
        const { error, code, data } = await dataApi.queryPage({
            projectId: projectId.value,
            contractId: contractId.value,
            containerId: id,
            ...searchForm.value,
            fieldKey: fieldList[0].fieldKey,
            id: id
        })
        //处理数据
        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
        }
    } else {
        window.$message.warning('请先设置容器字段')
    }
}

//多选
const tableCheckedKeys = ref([]);
const tableSelection = (rows) => {
    tableCheckedKeys.value = rows
}

//新增/编辑 分类
const addEditNodeFormModal = ref(false)
const addEditNodeFormModel = ref({
    containerName: '', fieldList: [{
        fieldType: 1,
        fieldName: ''
    }]
})
const addEditNodeFormModalClick = () => {
    addEditNodeFormModel.value = {
        containerName: '', fieldList: [{
            fieldType: 1,
            fieldName: ''
        }]
    }
    addEditNodeFormModal.value = true
}

//加字段
const addEditNodeDataAdd = () => {
    if( addEditNodeFormModel.value.fieldList.length>4){
        window.$message?.warning('最多只能添加5个字段');
    }else{
        addEditNodeFormModel.value.fieldList.push({
        fieldType: 1,
        fieldName: ''
    })
    }
   
    
}
//删除当前行
const addEditNodeDataDel = async ({fieldId}, index) => {
    if (!fieldId) {
        addEditNodeFormModel.value.fieldList.splice(index, 1);
    } else {
        const { error, code } = await dataApi.removeField({fieldId})
        if (!error && code === 200) {
            addEditNodeFormModel.value.fieldList.splice(index, 1);
        }
    }
}

//保存节点信息
const addEditNodeFormLoading = ref(false)
const addEditNodeFormModalSave = () => {
    const form = addEditNodeFormModel.value
    if (!form.containerName) {
        window.$message.warning('请输入容器名称')
    } else if (form.fieldList.length <= 0) {
        window.$message.warning('请添加容器字段')
    } else {
        //判断是否满足条件
        const result = form.fieldList.every(({fieldName})=> {
            return fieldName !== ''
        })
        if (!result) {
            window.$message.warning('请先完善字段数据')
        } else {
            form.projectId = projectId.value
            form.contractId = contractId.value
            submitClassification(form)
        }
    }
}

//提交保存分类
const submitClassification = async (form) => {
    addEditNodeFormLoading.value = true
    const { error, code } = await dataApi.submitClassification(form)
    //处理数据
    addEditNodeFormLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success('操作成功')
        addEditNodeFormModal.value = false
        await getMenusData()
    }
}

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

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

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

//新增/编辑 表单
const addEditFormRef = ref(null)
const addEditFormModel = ref({})
const addEditFormRules = ref({})

//处理表单校验
const setAddEditFormRules = (fieldList) => {
    let newArr = {};
    for (let i = 0; i < fieldList.length; i++) {
        const item = fieldList[i];
        if (i === 0) {
            newArr[item.key] = {
                required: true,
                validator: async (rule, value, callback) => {
                    if (!value) {
                        callback(new Error("请输入" + item.name))
                    } else {
                        const ver = await verification(item.key, value)
                        if (!ver) {
                            callback(new Error(item.name + '必须是惟一的'))
                        } else {
                            callback()
                        }
                    }
                },
                trigger: 'blur'
            }
        } 
        // else if (item.type === 1) {
        //     newArr[item.key] = {
        //         required: true,
        //         trigger: 'blur',
        //         message: "请输入" + item.name
        //     }
        // } else if (item.type === 2) {
        //     newArr[item.key] = {
        //         required: true,
        //         trigger: 'blur',
        //         message: "请选择" + item.name
        //     }
        // }
    }
    addEditFormRules.value = newArr
}

//校验材料编号是否唯一
const verification = async (key, val) => {
    const { containerInitTabName } = menuItem.value
    const form = addEditFormModel.value
    const { error, code, data } = await dataApi.verification({
        projectId: projectId.value,
        contractId: contractId.value,
        id:form['id'] ?? '',
        bean: {
            fieldKey: key,
            fieldValue: val
        },
        containerInitTabName: containerInitTabName
    })
    if (!error && code === 200) {
        return data === '编号可以使用';
    } else {
        return false
    }
}

//新增/编辑
const addEditFormModal = ref(false)
const addFormModalClick = () => {
    addEditFormModel.value = {}
    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 addEditFormLoading = ref(false)
const addEditFormClick = async () => {
    const validate = await formValidate(addEditFormRef.value)
     
    if (validate) {
        const { containerInitTabName } = menuItem.value
        const form = addEditFormModel.value
        addEditFormLoading.value = true
        //处理数据格式
        let beanList = [];
        Object.keys(form).forEach(key => {
            if (key !== 'field_calibration_time') {
                beanList.push({
                    fieldKey: key,
                    fieldValue: form[key]
                })
            }
        })
        //发起请求
        const { error, code } = await dataApi.submitForm({
            projectId: projectId.value,
            contractId: contractId.value,
            beanList,
            containerInitTabName,
            fieldCalibrationTime: form['field_calibration_time'],
            id: form['id'] ?? ''
        })
        //处理数据
      
        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            addEditFormModal.value = false
            
            addEditFormLoading.value = false
      
            await getTableData()
            console.log(addEditFormLoading.value,'addEditFormLoading.value');
        }
    }
}

//删除数据
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 { containerInitTabName } = menuItem.value
        //删除请求
        const { error, code } = await dataApi.removeData({
            projectId: projectId.value,
            contractId: contractId.value,
            containerInitTabName: containerInitTabName,
            ids: ids,
        })
        //处理数据
        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            searchClick()
        }
    }
}

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

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

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

//拼接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>
