<template>
    <hc-new-dialog v-model="isShow" widths="800px" is-table :footer="false" :is-close="false">
        <template #header>
            <div class="hc-flex">
                <div class="hc-flex flex-1">
                    <div class="w-60">
                        <hc-search-input v-model="searchForm.packageName" placeholder="产品包名" @search="getTableData" />
                    </div>
                </div>
                <div class="hc-flex">
                    <el-button hc-btn type="primary" @click="addClick">新增</el-button>
                    <el-button hc-btn type="danger" @click="delClick">删除</el-button>
                    <el-button hc-btn @click="configDialogClose">关闭</el-button>
                </div>
            </div>
        </template>
        <hc-table
            ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading"
            is-new is-check :check-style="{ width: 29 }" :index-style="{ width: 60 }"
            @selection-change="tableCheckChange"
        >
            <template #action="{ row }">
                <el-link type="warning" @click="editRowClick(row)">修改</el-link>
                <el-link v-del-com:[delRowClick]="row" type="danger">删除</el-link>
            </template>
        </hc-table>
    </hc-new-dialog>

    <!-- 新增/修改 -->
    <hc-new-dialog v-model="isDialogShow" widths="450px" is-footer-center :title="dialogTitle" @close="dialogClose">
        <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" label-width="auto">
            <el-form-item label="产品包名：" prop="packageName">
                <el-input v-model="formModel.packageName" placeholder="请输入产品包名称" />
            </el-form-item>
            <el-form-item label="菜单列表：" prop="menuIds">
                <el-tree-select
                    v-model="formModel.menuIds" :data="menuData" :render-after-expand="false" node-key="id"
                    :props="menuTreeProps" multiple show-checkbox clearable block placeholder="请选择菜单列表"
                />
            </el-form-item>
            <el-form-item label="备注：">
                <el-input v-model="formModel.remark" placeholder="请输入备注" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button hc-btn @click="dialogClose">取消</el-button>
            <el-button hc-btn type="primary" :loading="submitLoading" @click="dialogSubmit">提交</el-button>
        </template>
    </hc-new-dialog>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { arrToId, formValidate, getArrValue } from 'js-fast-way'
import { HcDelMsg } from 'hc-vue3-ui'
import mainApi from '~api/system/tenant-package'
import menuApi from '~api/system/menu'

//事件
const emit = defineEmits(['close'])

//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})

//搜索表单
const searchForm = ref({
    packageName: null, current: 1, size: 200,
})

//监听显示
watch(isShow, (val) => {
    if (val) {
        getTableData()
        getMenuTreeApi()
    }
})

//表格数据
const tableRef = ref(null)
const tableColumn = ref([
    { key: 'packageName', name: '产品包名' },
    { key: 'remark', name: '备注' },
    { key: 'action', name: '操作', width: 100, align: 'center' },
])

//获取表格数据
const tableLoading = ref(true)
const tableData = ref([])
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const { data } = await mainApi.page(searchForm.value)
    tableData.value = getArrValue(data['records'])
    tableLoading.value = false
}

//表格被选择
const tableCheckKeys = ref([])
const tableCheckChange = (rows) => {
    tableCheckKeys.value = rows
}

//新增/修改 弹窗
const isDialogShow = ref(false)
const dialogTitle = ref('')

//菜单表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    packageName: {
        required: true,
        trigger: 'blur',
        message: '请输入产品包名称',
    },
    menuIds: {
        required: true,
        trigger: 'blur',
        message: '请选择菜单',
    },
}

//菜单列表
const menuData = ref([])
const getMenuTreeApi = async () => {
    const { data } = await menuApi.getMenuTree()
    menuData.value = getArrValue(data)
}
//菜单树
const menuTreeProps = {
    label: 'title',
}

//新增
const addClick = () => {
    dialogTitle.value = '新增产品包'
    formModel.value = {}
    //显示表单弹窗
    nextTick(() => {
        isDialogShow.value = true
    })
}

//修改菜单
const editRowClick = (row) => {
    formModel.value = {}
    dialogTitle.value = '修改产品包'
    formModel.value = { ...row }
    formModel.value.menuIds = row?.menuId?.split(',') ?? []
    //显示表单弹窗
    nextTick(() => {
        isDialogShow.value = true
    })
}

//删除菜单
const delRowClick = async ({ item }, resolve) => {
    const { code, msg } = await mainApi.del(item.id)
    if (code === 200) {
        resolve()
        window.$message.success('删除成功')
        getTableData().then()
    } else {
        resolve()
        window.$message.error(msg ?? '删除失败')
    }
}

//批量删除菜单
const delClick = () => {
    const rows = tableCheckKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请选择要删除的菜单')
        return false
    }
    //确认删除
    HcDelMsg({}, async (instance, resolve) => {
        instance.confirmButtonLoading = true
        instance.confirmButtonText = '删除中...'
        //发起请求
        const ids = arrToId(rows)
        const { code, msg } = await mainApi.del(ids)
        //关闭弹窗的回调
        resolve()
        instance.confirmButtonLoading = false
        //处理结果
        if (code === 200) {
            window.$message.success('删除成功')
            getTableData().then()
        } else {
            window.$message.error(msg ?? '删除失败')
        }
    })
}

//提交表单
const submitLoading = ref(false)
const dialogSubmit = async () => {
    const formRes = await formValidate(formRef.value)
    if (!formRes) return false
    submitLoading.value = true
    //处理数据
    const form = formModel.value
    form.menuId = form.menuIds?.join(',') ?? ''
    //发起请求
    const { error, code, msg } = await mainApi.submit(form)
    submitLoading.value = false
    if (!error && code === 200) {
        dialogClose()
        window?.$message?.success('操作成功')
        getTableData().then()
    } else {
        window?.$message?.error(msg ?? '操作失败')
    }
}

//关闭弹窗
const dialogClose = () => {
    isDialogShow.value = false
    submitLoading.value = false
    formModel.value = {}
}

//关闭字典配置弹窗
const configDialogClose = () => {
    isShow.value = false
    tableData.value = []
    emit('close')
}
</script>
