<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_container_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" @menu-tap="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" clearable placeholder="请输入容器编号查询" @keyup="keyUpEvent" />
                    </div>
                    <div class="ml-2">
                        <el-button type="primary" @click="searchClick">
                            <HcIcon name="search-2" />
                            <span>搜索</span>
                        </el-button>
                    </div>
                </template>
                <template #extra>
                    <HcTooltip keys="tentative_parameter_container_add">
                        <el-button hc-btn type="primary" @click="addFormModalClick">
                            <HcIcon name="add-circle" />
                            <span>新增</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_parameter_container_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_container_del">
                        <el-button v-del-com:[delTableModalClick] :disabled="tableCheckedKeys.length <= 0" hc-btn color="#e03997">
                            <HcIcon name="delete-bin-2" />
                            <span>删除</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_parameter_container_printer">
                        <el-button :disabled="tableCheckedKeys.length <= 0" hc-btn color="#567722">
                            <HcIcon name="printer" />
                            <span>打印</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="tentative_parameter_container_import">
                        <el-button hc-btn color="#A16222" @click="importModalClick">
                            <HcIcon name="folder-upload" />
                            <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" :title="`${addEditNodeFormModel.id ? '编辑' : '新增'}试验容器`"
            is-row-footer widths="30rem" @close="addEditNodeFormModalClose"
        >
            <el-form :model="addEditNodeFormModel" label-position="top" label-width="auto" 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 :value="1" label="文本" />
                                <el-option :value="2" label="日期框" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="字段名">
                            <template #label>
                                <div class="solt-label">
                                    <span class="mr-1">字段名</span>
                                    <span
                                        v-if="index === 0"
                                        class="text-xs text-slate-400"
                                    >第一个作为编号,是唯一的</span>
                                </div>
                                <div class="solt-extra">
                                    <el-button
                                        plain size="small" type="primary"
                                        @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 :loading="addEditNodeFormLoading" hc-btn type="primary" @click="addEditNodeFormModalSave">
                    <HcIcon name="check" />
                    <span>提交</span>
                </el-button>
            </template>
        </hc-new-dialog>

        <!-- 新增/编辑 -->
        <hc-new-dialog
            v-model="addEditFormModal" :loading="addEditFormLoading" :title="`${addEditFormModel.id ? '编辑' : '新增'}数据`"
            widths="30rem" @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-if="item.type === 1"
                            v-model="addEditFormModel[item.key]"
                            :placeholder="`${index === 0 ? '作为编号，是唯一的' : `请输入${item.name}`}`"
                        />
                        <el-date-picker
                            v-if="item.type === 2" v-model="addEditFormModel[item.key]" :clearable="false"
                            class="block" type="date" value-format="YYYY-MM-DD"
                        />
                    </el-form-item>
                </template>
            </el-form>
        </hc-new-dialog>

        <!-- 导入 -->
        <hc-new-dialog v-model="importModal" is-row-footer title="导入" widths="38rem" @close="importModalClose">
            <HcDragUpload ref="uploadRef" :datas="uploadData" action="/api/blade-business/container/data/import-excel" @finished="uploadFinished" @progress="uploadprogress" />
            <template #leftRowFooter>
                <el-button size="large" :loading="downloadLoading" @click="download">
                    <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 :loading="importModalLoading" hc-btn type="primary" @click="importModalYesClick">
                    <HcIcon name="folder-upload" />
                    <span>确认导入</span>
                </el-button>
            </template>
        </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, downloadBlob, formValidate, getArrValue } from 'js-fast-way'
import HcDragUpload from './components/HcDragUpload.vue'
import dataApi from '~api/tentative/parameter/container'
import { HcDelMsg } from 'hc-vue3-ui'

//初始变量
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, msg } = await dataApi.submitClassification(form)
    //处理数据
    addEditNodeFormLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success('操作成功')
        addEditNodeFormModal.value = false
        await getMenusData()
    } else {
        window?.$message?.error(msg)
    }
}

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

//删除分类
const delNodeModalClick = (id) => {
    HcDelMsg( async ( resolve) => {
        await removeClassification(id)
        resolve() //关闭弹窗的回调
    })
}

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

//新增/编辑 表单
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, msg } = await dataApi.submitForm({
            projectId: projectId.value,
            contractId: contractId.value,
            beanList,
            containerInitTabName,
            fieldCalibrationTime: form['field_calibration_time'],
            id: form['id'] ?? '',
        })
        //处理数据
        addEditFormLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            addEditFormModal.value = false

          

            await getTableData()
            console.log(addEditFormLoading.value, 'addEditFormLoading.value')
        } else {
            window?.$message?.error(msg)
        }
    }
}

//删除数据
const delTableModalClick = async (_, resolve) => {
    await tableRemoveData()
    resolve()
}

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

//导入
const importModal = ref(false)
const uploadData = ref({})
const importModalClick = () => {
    const { containerInitTabName } = menuItem.value
    importModal.value = true
    importModalLoading.value = false
    uploadData.value = {
        containerInitTabName: containerInitTabName,
    }
}
const uploadRef = ref(null)
//上传完成
const uploadFinished = (res) => {
    importModalLoading.value = false
    importModal.value = false

    getTableData()
}
//上传进度
const uploadprogress = (res) => {

    importModalLoading.value = res
}

//确认导入
const importModalLoading = ref(false)
const importModalYesClick = async () => {
     uploadRef.value?.submit()






}

//关闭导入
const importModalClose = () => {
    importModal.value = false
}
const downloadLoading = ref(false)
const download = async ()=>{
    downloadLoading.value = true
    const { error, disposition, res } = await dataApi.downloadTemplate({ id: menuKey.value })
      //处理数据
      downloadLoading.value = false
    if (!error) {
        if (disposition) {
            downloadBlob(res, disposition)
        } else {
            window.$message?.error('数据异常')
        }
    }
}
//左右拖动，改变树形结构宽度
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>
