<template>
    <hc-body split>
        <template #left>
            <div class="hc-menu-contents-box">
                <el-scrollbar>
                    <HcMenuSimple
                        :datas="menuOptions" 
                        :keys="menuKey" 
                        :props="menuProps"
                        @change="handleMenuValue"
                    />
                </el-scrollbar>
            </div>
        </template>
        <hc-card>
            <template #header>
                <span class="text-orange">*编号更改后，所有已生成的资料删除编号内容，保存后重新自动生成。</span>
            </template>
            <template #extra>
                <HcTooltip keys="tentative-basic-code-add">
                    <el-button
                        hc-btn
                        type="primary"
                        @click="handleAdd()"
                    >
                        <HcIcon name="add-circle" />
                        <span>新增</span>
                    </el-button>
                </HcTooltip>
              
                <HcTooltip keys="tentative-basic-code-sort">
                    <el-button hc-btn type="primary" color="#12C060" style="color: white;">
                        <HcIcon name="arrow-up-down" />
                        <span>排序</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="tentative-basic-code-resign">
                    <el-button
                        hc-btn
                        color="#e03997" style="color: white;" 
                        :loading="resetLoad"
                        @click="resetModalClick"
                    >
                        <HcIcon name="restart" />
                        <span>重置编号</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="tentative-basic-code-delete">
                    <el-button hc-btn color="red" :loading="delModalLoad" @click="delModalClick">
                        <HcIcon name="delete-bin-2" />
                        <span>删除</span>
                    </el-button>
                </HcTooltip>
            </template>
           

            <HcTable
                ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoad"
                is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
                @selection-change="tableSelection"
            >
                <template #type="{ row }">
                    <el-select v-if="row.isEdit" v-model="row.type" placeholder="请选择">
                        <el-option
                            v-for="item in typeOptions"
                            :key="item.key"
                            :label="item.label"
                            :value="item.key"
                        />
                    </el-select>
                    <span v-else>{{ getTypeLabel(row.type) }}</span>
                </template>
                <template #data="{ row }">
                    <el-input v-if="row.isEdit" v-model="row.data" placeholder="请输入数据" />
                    <span v-else>{{ row.data }}</span>
                </template>
                <template #isAutoIncrement="{ row }">
                    <el-checkbox v-if="row?.type === '6'" v-model="row.isAutoIncrement" :disabled="!row.isEdit">是否自增</el-checkbox>
                </template>
                <template #action="{ row }">
                    <el-button 
                        v-if="!row.isEdit"
                        type="primary" 
                        link
                        @click="handleEdit(row)"
                    >
                        <HcIcon name="edit-2" />
                        编辑
                    </el-button>
                    <el-button 
                        v-if="row.isEdit"
                        type="success" 
                        link
                        :loading="row.saveLoading"
                        @click="handleSave(row)" 
                    >
                        <HcIcon name="save-3" />
                        保存
                    </el-button>
                    <el-button 
                        v-del-com:[handleDelete]="row" 
                        type="danger"
            
                        link
                    >
                        <HcIcon name="delete-bin-2" />
                        删除
                    </el-button>
                </template>
            </HcTable>
        </hc-card>
    </hc-body>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { getDictionary } from '~api/other'
import { arrToId, getArrValue } from 'js-fast-way'
import dataApi from '~api/basic/code'
import { useAppStore } from '~src/store'
import { HcDelMsg } from 'hc-vue3-ui'
const store = useAppStore()
const projectId = ref(store.getProjectId)
const contractId = ref(store.getContractId)
onMounted(()=>{
    getTypeOptions()
    getTableData()
})
//左侧菜单
const menuKey = ref('1')
const menuOptions = ref([
    { key: '1', label: '材料编号' },
    { key: '2', label: '样品编号' },
    { key: '3', label: '委托单编号' },
    { key: '4', label: '记录表编号' },
    { key: '5', label: '报告表编号' },
])
//左侧菜单
const menuProps = {
    key: 'key',
    label: 'label',
}
const typeOptions = ref([])
const getTypeOptions = async ()=>{
        const { data } = await getDictionary({
        code: 'trial_number_rule',
    })
    //处理数据
    let newArr = []
    const newData = getArrValue(data)
    for (let i = 0; i < newData.length; i++) {
        newArr.push({
            label: newData[i]['dictValue'],
            key: newData[i]['dictKey'],
        })
    }
    typeOptions.value = newArr
}
// 查找typeOptions中对应的label
const getTypeLabel = (typeKey) => {
    return typeOptions.value.find(item => item.key === typeKey)?.label || '未知类型'
}
const handleMenuValue = (item) => {

    menuKey.value = item.key
    getTableData()
}



//获取数据
const tableLoad = ref(true)
const tableData = ref([])
const tableRef = ref(null)
const tableColumn = ref([
     { key: 'type', name: '规则' },
     { key: 'data', name: '数据填充' },
      { key: 'isAutoIncrement', name: '是否自增' },
      { key: 'action', name: '操作' },
   
])
const getTableData = async () => {
    tableLoad.value = true
    const { error, code, data } = await dataApi.getTrialNumberRule({
        projectId: projectId.value,
        contractId: contractId.value,
       type: menuKey.value,
    })
    //处理数据
    tableLoad.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
      
    } else {
        tableData.value = []
      
    }
}

//多选
const tableCheckedKeys = ref([])
const tableSelection = (rows) => {
    tableCheckedKeys.value = rows
}
// 编辑行
const handleEdit = (row) => {
    row.isEdit = true
}
const saveLoading = ref(false)

// 保存行
const handleSave = async (row) => {
        saveLoading.value = true
    const { error, code, msg } = await dataApi.save({
      ...row,
        projectId: projectId.value,
        contractId: contractId.value,
    })
    //处理数据
    saveLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success(msg)
        row.isEdit = false
     
    
     getTableData()
      
    } 
}


const handleDelete = async ({ item }, resolve) => {
    await delData(item.id)
    resolve()
}
//删除请求
const delData = async (id) => {
    const { error, code, msg } = await dataApi.delData({
        contractId: contractId.value,
        pkeyId: id,
       
    }, false)
    //判断状态
    if (!error && code === 200) {
        window?.$message?.success(msg)
        getTableData()
    } else {
        window?.$message?.error(msg)
    }
}
//删除节点
const delModalLoad = ref(false)
const delModalClick = () => {
    delModalLoad.value = true
     const rows = tableCheckedKeys.value
    const ids = arrToId(rows)
    HcDelMsg(async (resolve) => {
        await delData(ids)
         delModalLoad.value = false
        resolve() //关闭弹窗的回调
    })
}
const handleAdd = () => {
    tableData.value.push({
        isEdit: true,
    })
}
const resetLoad = ref(false)
const resetModalClick = async () => {
    // getTableData()
        resetLoad.value = true
    const { error, code, data, msg } = await dataApi.reTrialNumberRule({
        projectId: projectId.value,
        contractId: contractId.value,
       type: menuKey.value,
    })
    //处理数据
    resetLoad.value = false
    if (!error && code === 200) {
        window?.$message?.success(msg)
        getTableData()
      
    } 
    
}
</script>