<template>
    <div class="modal">
        <el-dialog
            v-model="dialogVisible"
            :title="dialogTitle"
            :width="modalConfig.dialogWidth || '40%'"
            center
            @close="handleExcel(ruleFormRef)"
            :close-on-click-modal="false"
        >
            <div class="form">
                <el-form
                    ref="ruleFormRef"
                    :rules="modalConfig.formRules"
                    :model="formData"
                    :label-width="modalConfig.labelWidth || '100px'"
                    size="large"
                >
                    <template v-for="item in modalConfig.formItems" :key="item.prop">
                        <el-form-item :label="item.label" :prop="item.prop">
                            <template v-if="item.type === 'input'">
                                <el-input
                                    :disabled="item.disabled"
                                    v-model="formData[item.prop]"
                                    :placeholder="item.placeholder"
                                />
                            </template>
                            <template v-if="item.type === 'number'">
                                <el-input
                                v-model="formData[item.prop]"
                                    type="number"
                                    :min="0"
                                    :max="999999999999"
                                    :disabled="item.disabled"
                                    :placeholder="item.placeholder"
                                    @blur="onBlur(formData[item.prop],item.prop)"
                                />
                            </template>
                            <template v-if="item.type === 'password'">
                                <el-input
                                    show-password
                                    v-model="formData[item.prop]"
                                    :placeholder="item.placeholder"
                                    :disabled="item.disabled"
                                />
                            </template>
                            <template v-if="item.type === 'select'">
                                <el-select
                                    v-model="formData[item.prop]"
                                    :placeholder="item.placeholder"
                                    style="width: 100%"
                                    :disabled="item.disabled"
                                >
                                    <template v-for="(val, index) in item.options" :key="index">
                                        <el-option :value="val.value" :label="val.label" />
                                    </template>
                                </el-select>
                            </template>
                            <template v-if="item.type === 'date-picker'">
                                <el-date-picker
                                    :type="item.dateType || 'daterange'"
                                    range-separator="-"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    v-model="formData[item.prop]"
                                    :disabled="item.disabled"
                                />
                            </template>
                            <template v-if="item.type === 'textArea'">
                                <el-input
                                    :disabled="item.disabled"
                                    v-model="formData[item.prop]"
                                    :rows="item.rows || 2"
                                    type="textarea"
                                    :placeholder="item.placeholder"
                                />
                            </template>

                            <template v-if="item.type === 'custom'">
                                <slot v-bind="formData" :name="item.slotName"></slot>
                            </template>
                        </el-form-item>
                    </template>
                </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleExcel(ruleFormRef)">取消</el-button>
                    <el-button type="primary" @click="handleConfirmClick(ruleFormRef)">确定</el-button>
                    <slot name="button"></slot>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="modal">
import { reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import useSystemStore from '@/store/main';

// 定义props
interface IProps {
    modalConfig: {
        pageName: string;
        addTitle: string;
        editTitle: string;
        detailTitle: string;
        dialogWidth: string;
        labelWidth: string;
        formItems: any[];
        formRules: object;
        pageListParams?: object; //新增一个对象，用来传给特殊的列表接口刷新页面（非必传）
    };
    otherInfo?: any;
}

const props = defineProps<IProps>();

const dialogVisible = ref(false);
const isEdit = ref(false);

const ruleFormRef = ref<FormInstance>();

const systemStore = useSystemStore();

const { pageDetailInfo,pageOperateType } = storeToRefs(systemStore);

const pageDetailInfo2 = ref()
watch(pageDetailInfo,(newVal)=>{
    pageDetailInfo2.value = newVal
});

// 定义数据绑定
const initialForm: any = {};
for (const item of props.modalConfig.formItems) {
    initialForm[item.prop] = item.initialValue ?? '';
}

let formData =ref(JSON.parse(JSON.stringify(initialForm)));

const dialogTitle = ref();
// 新建或者编辑
function setDialogVisible(isNew: boolean = true, check: boolean = false) {
    dialogVisible.value = true;
    ruleFormRef.value?.resetFields();

    if (!isNew) {
        watch(pageDetailInfo,(newVal)=>{
            formData.value = pageDetailInfo2.value;
        });
        // 判断如果不是新增的话就获取store中的详情
        if (check) {
            dialogTitle.value = props.modalConfig.detailTitle;
            systemStore.getDetailType('detail');
        } else {
            dialogTitle.value = props.modalConfig.editTitle;
            systemStore.getDetailType('edit');
        }
    } else {
        props.modalConfig.formItems.map((m:any) => {
            if(m.type === "number") {
                if(m.porp === initialForm[m.porp]) {
                    initialForm[m.prop] = 0.00.toFixed(2);
                }
            }
        });
        formData.value = initialForm;
        formData.value = JSON.parse(JSON.stringify(initialForm));
        dialogTitle.value = props.modalConfig.addTitle;
        systemStore.detailPageEval(initialForm);
        systemStore.getDetailType('add');
    }
    isEdit.value = !isNew;
}
// 点击确定
function handleConfirmClick(formEl: FormInstance | undefined) {
    formData.value = Object.assign(formData.value,props.otherInfo);
    if (!formEl) return;
    formEl.validate((valid, fields) => {
        if (valid) {
            dialogVisible.value = false;
            let data = { ...formData.value };
            if (props.otherInfo) {
                data = { ...data, ...props.otherInfo };
            }
            if (!isEdit.value) {
                systemStore.newPageDataAction(props.modalConfig.pageName, data, props.modalConfig.pageListParams);
            } else {
                if(pageOperateType.value === 'edit'){
                    systemStore.editPageDataAction(props.modalConfig.pageName, data, props.modalConfig.pageListParams);
                }
            }
        } else {
            console.log('error submit!', fields);
        }
    });

}
// 取消
function handleExcel(formEl: FormInstance | undefined) {
    dialogVisible.value = false;
    if (!formEl) return;
    formEl.resetFields();
}

// 获取详情
function onPageDetail(urlId: number | [] | string) {
    systemStore.detailPageDataAction(props.modalConfig.pageName, urlId);
}

function onBlur(e:any,prop:any) {
    if(e < 0) {
        e = 0.00;
    }
    let a = Number(e).toFixed(2);
    for (const item of props.modalConfig.formItems) {
        if(item.type === 'number') {
            if(prop === item.prop) {
                formData.value[item.prop] = a;
            }
        }
    }
}
defineExpose({
    setDialogVisible,
    onPageDetail,
});
</script>

<style scoped lang="scss">
.form {
    padding: 10px 30px;
}
</style>
