<template>
    <div class="modal">
        <el-dialog v-model="dialogVisible" title="批量费用生成" width="40%" center :close-on-click-modal="false"
            @close="handleExcel(ruleFormRef)">
            <div class="form">
                <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm" :label-width="'160px'" size="large">
                    <template v-for="(item, index) in formData[formIndex]" :key="index">
                        <el-form-item :label="item.label" :prop="item.prop">
                            <!-- 输入框数据 -->
                            <template v-if="item.type === 'input'">
                                <el-input v-model="item.data[item.prop]" :placeholder="item.placeholder"
                                    disabled="false" />
                            </template>
                            <!-- 费用总计 -->
                            <template v-if="item.type === 'number'">
                                <el-input v-model="item.data[item.prop]" type="number" :min="0.00"
                                    :max="999999999999.00" :disabled="item.disabled" :placeholder="item.placeholder"
                                    @blur="onBlur(item.data[item.prop], item.prop, item.numberType)" />
                            </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]"
                                    @change="handleSelect(item.prop)" :disabledDate="disabledDateFun"
                                    :default-value="defaultDates" :disabled="item.disabled"
                                    style="flex:3;width: 25%;" />
                                <el-popover v-if="numTable.globalList != null" :visible="popoverVisible"
                                    placement="right" :width="400" trigger="click" ref="myPopover">
                                    <template #reference>
                                        <el-button @click="popoverVisible = true"
                                            style="width: 15%;margin-left: 16px">{{ formData.totalDays }}</el-button>

                                    </template>
                                    <el-table :data="numTable.globalList">
                                        <template v-for="item in numTable.heading">
                                            <el-table-column :label="item.name" :prop="item.field"
                                                show-overflow-tooltip>
                                                <template #default="scope" v-if="item.name === '天数'">
                                                    <el-input v-model="scope.row.between" :disabled="true"></el-input>
                                                </template>
                                            </el-table-column>
                                        </template>
                                    </el-table>
                                    <div class='flex-cc mt15'>
                                        <!-- <el-button type="primary"
                                            @click="confirmAndClose(numTable.globalList)">确定</el-button> -->
                                        <el-button @click="cancelAndClose">取消</el-button>
                                    </div>
                                </el-popover>
                                <el-input v-else style="margin-left: 10px; margin-right: 10px;flex:1"
                                    v-model="formData.totalDays" type="number" :min="1" :max="999999999999"
                                    :maxlength="12" @change="dataBlur(formData.totalDays)" />天
                            </template>
                        </el-form-item>
                    </template>
                </el-form>

            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button v-if="nextShow == true" @click="onLastStep()">上一步</el-button>
                    <el-button v-if="closeAccountShow == true" @click="handleConfirmClick(ruleFormRef)">关账</el-button>
                    <el-button @click="handleExcel(ruleFormRef)">取消</el-button>
                    <el-button v-if="lastShow == true" @click="onNext()">下一步</el-button>
                    <slot name="button"></slot>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="modal">
import { onMounted, ref, watch } from 'vue';
import { parseTime } from '@/utils/ruoyi';
import type { FormInstance } from 'element-plus';
import useSystemStore from '@/store/main';
import { outTypeList } from '@/libs/commonMeth';

// 定义props
interface IProps {
    repFlag: Boolean,
    operateFlage: Boolean,
    dialogShows: boolean,
    pageName: string,
    moneyPageName: string,
    listIds: [],
    closeAccountPageName: string,
    startDates: string,
    endDates: string,
}
const nextShow = ref(false);
const lastShow = ref(false);
const closeAccountShow = ref(false);
const props = defineProps<IProps>();
const isEdit = ref(false);
const systemStore = useSystemStore();

const { pageDetailInfo } = storeToRefs(systemStore);

import { operateRep } from '@/api/propertyFees';
import { getMoneyTotalByChooseMonthData, fetchRoomItReport } from '@/api/technicalServiceFees';
import request from '@/utils/request';
import { fa } from 'element-plus/es/locale';

const ruleFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
const costData = ref({});
const formData = ref([]);
const listIds = ref([]);
const pageName = ref('');
const closeAccountPageName = ref('');
const emit = defineEmits(['dialogClick']);
watch(() => props.dialogShows, async (newVal) => {
    if (newVal) {
        formData.value = [];
        formIndex.value = 0;
        nextShow.value = false;
        lastShow.value = false;
        closeAccountShow.value = false;
        await getInitialize();
        dialogVisible.value = newVal;
        listIds.value = props.listIds;
        pageName.value = props.pageName;
        closeAccountPageName.value = props.closeAccountPageName;
        // getMoneyMeth();


    }
}, { immediate: true },);

const costData2 = ref({
    labelName: ['公司名称', '公司人数'],
    labelValue: ['name', 'count', 'id'],
    data: [{
        name: '东航计费',
        count: '1000',
        id: 100,
    }, {
        name: '东航计费2',
        count: '2000',
        id: 101,
    }]
});
interface RestaurantItem {
    label: string
    prop: string
    type: string
    numberType?: string
    disabled: boolean
}
// 定义数据绑定
const initialForm: any = {};
const formIndex = ref(0);
// const formData = ref<RestaurantItem[]>([]);
// 选择月份接口初始化
const getMoneyDate = () => {
    const data = {
        startDate: formData.value?.chooseMonth[0],
        endDate: formData.value?.chooseMonth[1],
        ids: listIds.value,
        totalDays: formData.value.totalDays ? formData.value.totalDays : 0,
    };
    return request({
        url: '/business/' + pageName.value,
        method: 'post',
        data: data,
    });
};
// 批量关账接口初始化
const getCloseAccount = () => {
    let dataInfo = formData.value.slice(1);
    let dataItem = {};
    let items = [];
    dataInfo.map((item: any) => {
        item.map((m: any) => {
            if (m.prop === 'moneyTotal') {
                dataItem = {
                    id: m.data.id,
                    moneyTotal: m.data.moneyTotal,
                    calculationFormulaNumber: m.data.calculationFormulaNumber
                };
                items.push(dataItem);
            };

        });
    });
    const data = {
        startDate: formData.value?.chooseMonth[0],
        endDate: formData.value?.chooseMonth[1],
        items: items,
    };
    return request({
        url: '/business/' + closeAccountPageName.value,
        method: 'post',
        data: data,
    });
};
// 上一步点击事件
function onLastStep() {
    if (formIndex.value > 0) {
        formIndex.value--;
        if (formIndex.value === 0) {
            nextShow.value = false;
            lastShow.value = true;
        } else {
            lastShow.value = true;
        }
    }
    //
}
// 下一步点击事件
function onNext() {
    let allLength = formData.value.length - 1;
    if (formIndex.value >= 0) {
        formIndex.value++;
        nextShow.value = true;
        if (formIndex.value >= allLength) {
            formIndex.value = allLength;
            nextShow.value = true;
            lastShow.value = false;
        }
    }
}
// 初始化数据
function getInitialize() {
    const formMonth = [{
        label: '选择月份',
        prop: 'chooseMonth',
        type: 'date-picker',
        disabled: false
    }];
    formData.value.push(formMonth);
}
// 下一步插入数据
function nextDetails() {
    formData.value.length = 1;
    if (costData.value) {
        costData.value?.data.map((m: any) => {
            let list: any = [];
            costData.value.labelName.map((name: any, nameIndex: any) => {
                costData.value.labelValue.map((value: any, valueIndex: any) => {
                    if (nameIndex === valueIndex) {
                        list.push({
                            label: name,
                            prop: value,
                            type: 'input',
                            disabled: true,
                            data: { ...m }
                        });
                    }

                });
            });
            list.map((item: any) => {
                if (item.label === '费用总计(元)') {
                    item.type = 'number';
                    item.disabled = false;
                }
            });
            formData.value.push(list);
        });
    }
}

// ---------------------------------------
onMounted(async () => {

});

// ------------处理选择月份 开始-------------
// 根据日期获取金额总数
const numTable = ref({} as any);
const getMoneyMeth = () => {
    getMoneyDate().then(res => {
        costData.value = res.data;
        // formData.value.moneyTotal = res.data.moneyTotal;
        formData.value.totalDays = res.data.totalDays;
        numTable.value = res.data;
        nextDetails();
        lastShow.value = true;
        closeAccountShow.value = true;
    });
};
// 确认按钮点击时关闭气泡卡片
const myPopover = ref(null);
const popoverVisible = ref(false);
// 取消按钮点击时关闭气泡卡片
const cancelAndClose = () => {
    popoverVisible.value = false;

};
// 下拉框的change事件
const handleSelect = async (custom) => {
    await nextTick();
    if (custom === 'chooseMonth') {
        if (formData.value.chooseMonth) {
            formData.value.chooseMonth[0] = parseTime(formData.value.chooseMonth[0])?.slice(0, 10);
            formData.value.chooseMonth[1] = parseTime(formData.value.chooseMonth[1])?.slice(0, 10);
            let data = {} as any
            await getMoneyMeth(data);
        } else {
            numTable.value = {};
            formData.value.totalDays = 0;
        }
    }
};
// 选择月份后数字框的blur事件
const dataBlur = (e: any) => {
    // 处理根据天数计算费用总计
    if (!formData.value.totalDays) {
        formData.value.totalDays = 0;
    }
    getMoneyMeth({ totalDays: formData.value.totalDays });
};
// ------------处理选择月份 结束---------------

// 日期筛选器
const startDate = ref();
const endDate = ref();
let defaultDates;
// 监听 formData 的变化，更新 startDate 和 endDate
watch(
    () => [props.startDates, props.endDates],
    ([newStartDate, newEndDate]) => {
        startDate.value = newStartDate ? new Date(newStartDate).setHours(0, 0, 0, 0) : null;
        formData.value.startDate = newStartDate ? new Date(newStartDate).setHours(0, 0, 0, 0) : null;
        endDate.value = newEndDate ? new Date(newEndDate).setHours(0, 0, 0, 0) : null;
        formData.value.endDate = newEndDate ? new Date(newEndDate).setHours(0, 0, 0, 0) : null;
    },
);
// disabledDate 函数逻辑
const disabledDateFun = (time) => {
    const inputTime = new Date(time);
    defaultDates = computed(() => {
        return [startDate.value, endDate.value];
    });
    if (!startDate.value || !endDate.value) return false;
    // 判断 inputTime 是否在 startDate 和 endDate 之间
    return !(inputTime >= startDate.value && inputTime <= endDate.value);
};

// 新建或者编辑
async function setDialogVisible(isNew: boolean = true, check: boolean = false) {
    dialogVisible.value = true;
    ruleFormRef.value?.resetFields();
    numTable.value = {};
    if (!isNew) {
        watch(pageDetailInfo, async (newVal) => {
            formData.value = pageDetailInfo.value;
            formData.value.moneyTotal = formData.value.moneyTotal ? formData.value.moneyTotal : 0
        });

        // 判断如果不是新增的话就获取store中的详情
        if (check) {
            systemStore.getDetailType('detail');
        } else {
            systemStore.getDetailType('edit');
        }
    } else {
        formData.value = JSON.parse(JSON.stringify(initialForm));
        systemStore.detailPageEval(initialForm);
        systemStore.getDetailType('add');
    }
    isEdit.value = !isNew;
}
// 点击确定
function handleConfirmClick(formEl: FormInstance | undefined, status) {
    if (!formEl) return;
    formEl.validate(async (valid, fields) => {
        if (valid) {
            getCloseAccount().then((res: any) => {
                if (res.msg === '该数据已存在是否要覆盖') {
                    ElMessageBox.confirm(
                        '该月费用已生成，是否覆盖？',
                        '提示',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }
                    )
                        .then(() => {
                            data.checkFees = 2;
                            operateRep(data).then((res: any) => {
                                if (res.code === 200) {
                                    ElMessage.success('操作成功');
                                    dialogVisible.value = false;
                                }
                            });
                        })
                        .catch(() => {
                            ElMessage({
                                type: 'info',
                                message: '已取消',
                            });
                        });
                } else {
                    if (res.code === 200) {
                        ElMessage.success(res.msg);
                    } else {
                        ElMessage.error(res.msg);
                    }
                    dialogVisible.value = false;
                }
            });
        } else {
        }
    });

}
const dialogVisibleShow = ref(false);
// 取消
function handleExcel(formEl: FormInstance | undefined) {
    dialogVisible.value = false;
    emit('dialogClick', dialogVisible.value);
    if (!formEl) return;
    formEl.resetFields();
}

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

function onBlur(e: any, prop: any, type: any) {
    let a = 0;
    if (e < 0) {
        e = 0.00;
    } else if (e > 999999999999999) {
        e = 999999999999999.00;
    }
    a = Number(Number(e).toFixed(2));
    formData.value.map((m: any) => {
        m.map((item: any) => {
            if (prop === item.prop) {
                if (e === item.data[item.prop]) {
                    item.data[item.prop] = a;
                }
            }

        });

    });
}
defineExpose({
    setDialogVisible,
    onPageDetail,
});
interface RuleForm {
    chooseMonth: [] | string | undefined;
    totalDays: number;
    moneyTotal: number;
}
const ruleForm = reactive<RuleForm>({
    chooseMonth: [],
    totalDays: 0,
    moneyTotal: 0.00
});
const rules = reactive<FormRules<RuleForm>>({

});
</script>

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

.infinite-list {
    height: 300px;
    padding: 0;
    margin: 0;
    list-style: none;
}

.infinite-list .infinite-list-item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
    background: #eceff7;
    margin: 10px 0;
    /* color: var(--el-color-primary); */
}

.infinite-list .infinite-list-item+.list-item {
    margin-top: 10px;
}
</style>
