<template>

    <el-card shadow="never" class="list-card">

        <template #header>
            <el-tabs v-model="queryParams.dictType"  @tab-change="changeTab">
                <el-tab-pane name="" label="全部" ></el-tab-pane>
                <el-tab-pane name="1" label="业务字典" ></el-tab-pane>
                <el-tab-pane name="0" label="系统字典"></el-tab-pane>
            </el-tabs>
            <div class="search" v-show="showSearch">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                    <el-form-item  prop="code">
                        <el-input v-model="queryParams.code" placeholder="请输入字典code" clearable style="width: 240px" @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item  prop="name">
                        <el-input v-model="queryParams.name" placeholder="请输入字典名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>

        <Table ref="dictTable"
               :tableParams="tableParams"
               :btnRole="leftBtn"
               @handleAdd="handleAdd"
               @handleEdit="handleUpdate"
               @selectionChange="handleSelectionChange"
        >


        </Table>
    </el-card>

    <!-- 添加或修改字典组对话框 -->
    <el-dialog :title="detailDialog.title" v-model="detailDialog.visible" width="1200px" append-to-body>
        <indexDetail ref="dictDetailref" :pDictId="pDictId"></indexDetail>
    </el-dialog>

    <!-- 添加或修改字典组对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
        <el-form ref="dictFormRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="字典类型" prop="dictType">

            <el-radio-group v-model="form.dictType">
                <el-radio :label="0">系统字典</el-radio>
                <el-radio :label="1" >业务字典</el-radio>
            </el-radio-group>

            </el-form-item>
            <el-form-item label="字典code" prop="code">
                <el-input v-model="form.code" placeholder="请输入字典code" />
            </el-form-item>
            <el-form-item label="字典名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入字典名称" />
            </el-form-item>
            <el-form-item label="描述" >
                <el-input v-model="form.description" placeholder="请输入描述" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">提交</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="Dict" lang="ts">
import { listDict, getDict, delDict, addDict, updateDict } from '@/api/system/dict';
import { DictVO, DictQuery, DictForm } from '@/api/system/dict/types';
import auth from '@/plugins/auth'
import Table from '@/components/Table/index.vue'
import indexDetail from './indexDetail.vue'
import { tableTypes } from '@/components/Table/types'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const dictDetailref = ref()
const dictList = ref<DictVO[]>([]);
const pDictId = ref<number | string>();
const buttonLoading = ref(false);
const dictType = ref('');
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
// const leftBtn = ref<Array<string | number>>(
//     ['system:dict:remove',
//         'system:dict:add',
//         'system:dict:edit',
//         'system:dict:import',
//         'system:dict:export',
//     ]);

const leftBtn = ref([
    { type: 'add', hasPermi: `system:dict:add` },
    { type: 'edit', hasPermi: `system:dict:edit` },
    { type: 'remove', hasPermi: `system:dict:remove` },
    { type: 'import', hasPermi: `system:dict:import` },
    { type: 'export', hasPermi: `system:dict:export` }
])
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const dictFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});
const detailDialog = reactive<DialogOption>({
    visible: false,
    title: '字典详情'
});


const tableParams = reactive<tableTypes<DictQuery, DictVO>>({
    tableColumn: [
        {show: true, label: '主键ID', prop: 'dictId', sortable: false},
        {show: true, label: '字典code', prop: 'code', sortable: false},
        {show: true, label: '字典名称', prop: 'name', sortable: false},
        {show: true, label: '字典类型', prop: 'dictType', sortable: false, render: ({ column }: { column: DictVO }) => {
                return [
                    h(ElTag, {}, column.dictType == 1 ? '业务字典' : '系统字典'),
                ]
            },
        },
        // {show: true, label: '是否启用', prop: 'enabled', render: ({ column }: { column: DictVO }) => {
        //         return [
        //             h(ElSwitch, {value: column.enabled, onChange: async (v)=>{
        //                     let ids: Array<number | string> = []
        //                     if(column?.dictId) {
        //                         ids.push(column.dictId)
        //                     }
        //                     //TODO
        //                     column.enabled = v
        //                 }}),
        //         ]
        //     }
        // },
        {
            show: true, label: '操作', width: 200, prop: 'operation', disabledMove: true, render: ({ column }: { column: DictVO }) => {
                return [
                   h(ElButton, {link: true, type: 'primary', onClick:() => {
                           pDictId.value = column.dictId
                           detailDialog.visible = true
                           nextTick(()=>{
                               console.log(dictDetailref.value)
                               dictDetailref.value.getList()
                           })

                       }},  '详情'),
                ]
            }
        },
    ],
    keyId: 'dictId',
    queryParams: {
        code: undefined,
        name: undefined,
    },
    listFn: listDict,
    delFn: delDict,
})


const initFormData: DictForm = {
    dictId: undefined,
    code: undefined,
    name: undefined,
    description: undefined,
    dictType: 1,
    ownerBy: undefined,
    isDelete: undefined,
    enabled: undefined,
    sort: undefined
}
const data = reactive<PageData<DictForm, DictQuery>>({
    form: {...initFormData},
    rules: {
        code: [
            { required: true, message: "字典code不能为空", trigger: "blur" }
        ],
        name: [
            { required: true, message: "字典名称不能为空", trigger: "blur" }
        ],

        dictType: [
            { required: true,  message: "字典类型不能为空", trigger: "change" }
        ],

    }
});

const {  form, rules } = toRefs(data);

const { queryParams } = toRefs(tableParams);
/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
}
/** 字典类型 */
const changeTab = (v: string | number ) => {
   console.log(">>>>>", v)
   queryParams.value.dictType = v
   handleQuery()
}

/** 表单重置 */
const reset = () => {
    form.value = {...initFormData};
    dictFormRef.value?.resetFields();
}

const dictTable = ref()
/** 搜索按钮操作 */
const handleQuery = () => {
    dictTable.value.getData()
}

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: DictVO[]) => {
    ids.value = selection.map(item => item.dictId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加字典组";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: DictVO) => {
    reset();
    console.log(row, ">>>>>>>>>>...fdsfs")
    // const _dictId = row?.dictId || ids.value[0]
    // const res = await getDict(_dictId);
    Object.assign(form.value, row);
    console.log(form.value, ">>>>>>>>>")
    dialog.visible = true;
    dialog.title = "修改字典组";
}
const getList = () => {
    dictTable.value.getData()
}
/** 提交按钮 */
const submitForm = () => {
    dictFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            await addDict(form.value).finally(() =>  buttonLoading.value = false);
            proxy?.$modal.msgSuccess("修改成功");
            dialog.visible = false;
            await getList();
        }
    });
}


onMounted(() => {
});
</script>
