<template>
    <div>
        <pro-dialog :visible="$attrs.visible" @close="$emit('close:modal')" :title="title" width="70%" :closable="true"
            :destroyOnClose="true" :maskClosable="true">
            <template v-slot:footer="">
                <pro-button id="f3dd65a2-c52b-11ea-87c3-ff36a904ecf1" @click="$emit('close:modal')"
                    :icon="h(CloseOutlined)">关闭</pro-button>
                <pro-button id="f3dd65a4-c52b-11ea-87c3-ff36a904ecf2" @click="save"
                    :icon="h(SaveOutlined)">保存</pro-button>
            </template>

            <pro-form ref="formRef" :model="dialogData" :rules="formRules" label-width="120px">
                <pro-form-grid :header="{ title: '基本信息' }" colNum="4">
                    <pro-input v-show="false" :formItemProps="{ label: 'no', prop: 'no' }" v-model:value="dialogData.no"
                        placeholder="请输入" :allowClear="true">
                    </pro-input>

                    <pro-input :formItemProps="{ label: '层级编号:', prop: 'key' }" v-model:value="dialogData.key"
                        placeholder="请输入" :allowClear="true">
                    </pro-input>
                    <pro-input :formItemProps="{ label: '层级名称:', prop: 'name' }" v-model:value="dialogData.name"
                        placeholder="请输入" :allowClear="true">
                    </pro-input>
                    <pro-input :formItemProps="{ label: '用途:', prop: 'use' }" v-model:value="dialogData.use"
                        placeholder="请输入" :allowClear="true">
                    </pro-input>
                    <pro-select :formItemProps="{ label: '启用标志', prop: 'use_yn' }" disabled="true"
                        v-model:value="dialogData.use_yn" placeholder="请选择启用标志" :allowClear="true"
                        tableName="com_usertype_info" colName="use_yn">
                    </pro-select>
                </pro-form-grid>

                <pro-form-grid :header="{ title: '层级信息' }" colNum="3">
                    <div>
                        <pro-table ref="tableRef" :columns="columns" :dataSource="dialogData.departLevelInfoData">
                            <template v-slot:header="">
                                <pro-button id=" 4b7facf0-94a4-11ee-9af3-e137392c498c" text="增加一行"
                                    :icon="h(PlusOutlined)" icon="plus" type="primary" @click="addRows"
                                    style="margin-right: 10px;">增加一行</pro-button>
                                <pro-button id=" 4b7facf0-94a4-11ee-9af3-e137392c498d" text="删除" :icon="h(PlusOutlined)"
                                    icon="plus" type="primary" @click="deleteRows2">删除</pro-button>
                            </template>
                        </pro-table>
                    </div>
                </pro-form-grid>
            </pro-form>
        </pro-dialog>
    </div>
</template>

<script setup lang="jsx">
import * as service from './services';
import { ref, onUnmounted, computed, h, reactive, onMounted, watch } from 'vue';
import { useStore } from 'vuex';
import { CloseOutlined, SaveOutlined, DeleteOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { Modal, message } from "ant-design-vue";
//const emit = defineEmits(['close:modal'])
const emit = defineEmits(['addDataDemo']);

const store = useStore();
// 表单组件的引用
const formRef = ref();
const tableRef = ref();
const title = computed(() => store.state.DepartLevel.dialogData.title);
const dialogData = computed(() => store.state.DepartLevel.dialogData);
const originalKeyValue = dialogData.value.key;
// 表单验证规则
const formRules = ref({
    key: [
        { required: true, trigger: 'blur' },
        {
            validator: async (rule, value, callback) => {
                try {
                    if (originalKeyValue !== value) {
                        const resp = await service.validateRecord({
                            sql: `select * from Com_depart_level_info where key = ? `,
                            param: value
                        });
                        if (resp === '0000') {
                            console.log("wyq-------code2", resp);
                            return Promise.resolve();
                        } else {
                            return Promise.reject(new Error('编号已存在'));
                        }
                    }
                } catch (error) {
                    message.error('处理失败' + error);
                    return Promise.reject(new Error('处理失败' + error));
                }
            },
            trigger: 'blur'
        }
    ],
    brf: [
        { required: true, trigger: 'blur' },
        // 其他校验规则
    ]
});

const columns = ref([
    {
        prop: "ActionColumn",
        label: "操作",
        width: "120px",
        align: "center",
        render: (scope) => {
            return <div>
                <pro-button id="deleteId" onClick={() => deleteRows(scope)} icon={h(DeleteOutlined)}>删除</pro-button>
            </div>
        }
    },
    {
        prop: "key", label: "层级编号", align: "center", width: "120px", editing: true,
        rules: [
            { required: true, message: '请输入层级编号', trigger: 'blur' },
            {
                validator: (rule, value, callback) => {
                    if (!isNumber(value)) {
                        return Promise.reject(new Error('层级编号请填写大于0的整数'));
                    } else {
                        return Promise.resolve();

                    }
                }
            }
        ]

    },
    { prop: "name", label: "层级名称", align: "center", width: "120px", editing: true },
    {
        prop: "brf", label: "层级功能描述", align: "center", width: "240px", editing: true,
        rules: [
            { required: true, message: '请输入层级功能描述', trigger: 'blur' }
        ]
    },
]);

function isNumber (value) {
    // 判断是否为数字、整数、大于0
    return /^\d+(\.\d+)?$/.test(value) && /^\d+$/.test(value) && value > 0;
}
function addRows () {
    store.dispatch("DepartLevel/addDepartLevelInfoData");
}

function deleteRows2 (scope) {
    console.log('wyq------deleteRows1', scope);
    console.log('wyq------deleteRows2', tableRef.value.getChecked());
    console.log('wyq------dialogData', dialogData.value.departLevelInfoData.records);


    dialogData.value.departLevelInfoData.records = dialogData.value.departLevelInfoData.records.filter(item => !tableRef.value.getChecked().includes(item));

    // tableRef.value.getChecked().forEach(item => {
    //     console.log('wyq------deleteRows3', item.no);

    //     dialogData.value.departLevelInfoData.records = dialogData.value.departLevelInfoData.records.filter(item1 => item1.no !== item.no);

    // });
    console.log('wyq------dialogData', dialogData.value.departLevelInfoData.records);


}


function deleteRows (scope) {
    Modal.confirm({
        title: '删除确认',
        content: '确认删除选中的记录',
        cancelText: '取消',
        onOk () {
            store.dispatch('DepartLevel/deleteDepartLevelInfoData', { ...scope });
        }
    });
}

function save () {
    console.log('wyqq------save', dialogData.value);
    console.log('wyq------调用addDataDemo11');
    emit('addDataDemo');
    //this.$emit('addDataDemo');
    // 表单校验成功
    formRef.value.getOrignRef().validate().then(() => {
        // 保存数据
        store.dispatch('DepartLevel/saveDepartLevelInfoData', {
            closeMethod: () => { emit("close:modal") }
        });
    }).catch((error) => {
        //console.log('error', error);
        //console.log('error', error.errorFields[0].errors[0]);
        message.error('提交失败：' + error.errorFields[0].errors[0]);
    });

}
</script>
