<template>
    <div class="home-container layout-pd">
        <el-card shadow="hover" class="layout-padding-auto mb10">
            <template #header>
                <div class="card-header">
                    <span>{{ state.dialog.title }}</span>
                    <el-button type="primary" size="default" @click="goBack">返回</el-button>
                </div>
            </template>
            <el-form ref="userDialogFormRef" :model="state.ruleForm" size="default" label-width="80px" :rules="rules">
                <el-row>
                    <el-col :span="12" class="mb20">
                        <el-form-item label="报表类型" prop="type">
                            <el-select :disabled="state.dialog.type == '1'" v-model="state.ruleForm.type"
                                placeholder="请选择报表类型" style="width: 100%" @change="changeselect">
                                <el-option v-for="item in state.soption" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="mb20" v-if="state.ruleForm.type == 1">
                        <el-form-item label="日期" prop="date">
                            <el-date-picker :disabled="state.dialog.type == '1'" v-model="state.ruleForm.date"
                                style="width:100%" :disabled-date="disabledDate" type="date" placeholder="请选择日期"
                                size="default" value-format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="mb20"
                        v-if="state.ruleForm.type == 2 || state.ruleForm.type == 3 || state.ruleForm.type == 4">
                        <el-form-item label="日期" prop="date">
                            <el-date-picker :disabled="state.dialog.type == '1'" v-model="state.ruleForm.date"
                                style="width:100%" :disabled-date="disabledDate" type="month" placeholder="请选择日期"
                                size="default" value-format="YYYY-MM" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-col :xs="24" class="mb20" v-if="state.ruleForm.type == 1">
                    <dayform ref="dayformRef"></dayform>
                </el-col>
                <el-col :xs="24" class="mb20" v-if="state.ruleForm.type == 2">
                    <monthform ref="monthformRef"></monthform>
                </el-col>
                <el-col :xs="24" class="mb20" v-if="state.ruleForm.type == 3">
                    <constructform ref="constructformRef"></constructform>
                </el-col>
                <el-col :xs="24" class="mb20" v-if="state.ruleForm.type == 4">
                    <provincesform ref="provincesformRef"></provincesform>
                </el-col>
            </el-form>
            <div class="card-footer" v-if="state.ruleForm.type != ''">
                <el-button type="primary" @click="onSubmit" style="width: 30%;">{{
                    state.dialog.submitTxt
                }}</el-button>
            </div>
        </el-card>
    </div>
</template>
  
<script setup lang="ts" name="systemUserDialog">
import { reactive, ref, defineAsyncComponent, onMounted, nextTick, watch } from "vue";
import { ElAlert, ElMessage, ElLoading, ElNotification, rowProps } from "element-plus";
import { getApi } from "/@/api/district/index";
import { useCurrentInstance } from "/@/method/get";
import { useRoute, useRouter } from "vue-router";
const { proxy } = useCurrentInstance();
let loading: any;

const route = useRoute();
const router = useRouter();
import mittBus from "/@/utils/mitt";
onMounted(() => {
    state.ruleForm.id = route.query.id
    openDialog(route.query.form)
})
// 日报
const dayform = defineAsyncComponent(
    () => import("/@/views/district/components/day.vue")
);
// 月报
const monthform = defineAsyncComponent(
    () => import("/@/views/district/components/month.vue")
);

// 建设部报表
const constructform = defineAsyncComponent(
    () => import("/@/views/district/components/construct.vue")
);
// 建设部报表
const provincesform = defineAsyncComponent(
    () => import("/@/views/district/components/provinces.vue")
);


const dayformRef = ref()
const monthformRef = ref()
const constructformRef = ref()
const provincesformRef = ref()

// 定义子组件向父组件传值/事件
const emit = defineEmits(["refresh"]);
const userDialogFormRef = ref();

const disabledDate = (time: Date) => {
    return time.getTime() > Date.now()
}

const goBack = () => {
    if (loading != undefined) loading.close();
    router.go(-1);
    mittBus.emit(
        "onCurrentContextmenuClick",
        Object.assign({}, { contextMenuClickId: 1, ...route })
    );
};
// 定义变量内容
const state = reactive({
    ruleForm: {
        id: '',
        type: "" as number | string,
        date: '',
        years: '',
        month: ''
    } as any,
    soption: [] as any,
    dialog: {
        isShowDialog: false,
        type: "",
        title: "",
        submitTxt: "",
    },
    uid: ''
});
const changeselect = (e: any) => {
    state.ruleForm.date = "";
    state.ruleForm.years = "";
    state.ruleForm.month = "";
}
// 表单验证
const rules = reactive({
    type: [{ required: true, message: "请选择报表类型", trigger: "blur" }],
});

// 打开弹窗
const openDialog = (row?: any) => {
    if (row == undefined) {
        state.dialog.title = "新增报表";
        state.dialog.submitTxt = "新增报表";
        state.dialog.type = "0"
        state.ruleForm = {
            id: '',
            type: "" as number | string,
            date: '',
            years: '',
            month: ''
        }
        state.uid = ""
    } else {
        state.dialog.title = "修改报表";
        state.dialog.submitTxt = "修改/提交报表";
        state.dialog.type = "1"
        row = JSON.parse(row)
        state.uid = row.id;
        state.ruleForm.type = row.type
    }
    state.dialog.isShowDialog = true;
    loadshow()
};

async function loadshow() {
    // 获取type
    const item = await getApi().gettype();
    state.soption = item.data;
    if (state.uid != '') {
        if (state.ruleForm.type == 1) {
            const uday = await getApi().dayget(state.uid);
            state.ruleForm = Object.assign(uday.data.escalation, { type: state.ruleForm.type });
            setTimeout(() => {
                dayformRef.value.setvalue(state.ruleForm);
            }, 300)
        }
        if (state.ruleForm.type == 2) {
            const umonth = await getApi().monthget(state.uid);
            state.ruleForm = Object.assign(umonth.data.escalation, { type: state.ruleForm.type });
            setTimeout(() => {
                monthformRef.value.setvalue(state.ruleForm);
            }, 300)
        }
        if (state.ruleForm.type == 3) {
            const umonth = await getApi().jsget(state.uid);
            state.ruleForm = Object.assign(umonth.data.escalation, { type: state.ruleForm.type });
            setTimeout(() => {
                constructformRef.value.setvalue(state.ruleForm);
            }, 300)
        }
        if (state.ruleForm.type == 4) {
            const umonth = await getApi().stget(state.uid);
            state.ruleForm = Object.assign(umonth.data.escalation, { type: state.ruleForm.type });
            setTimeout(() => {
                provincesformRef.value.setvalue(state.ruleForm);
            }, 300)
        }
    }
}

// 关闭弹窗
const closeDialog = () => {
    // state.dialog.isShowDialog = false;
    goBack()
};
// 提交
const onSubmit = async () => {
    let valueform = {} as any
    let _form = state.ruleForm;
    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month: any = currentDate.getMonth() + 1;
    const day = currentDate.getDate();
    let nowdatemonth = year + "-" + (month < 10 ? "0" + month : month)
    if (_form.type == "") return ElMessage.error("请选择报表类型");
    // 判断日期
    if (_form.date == '') return ElMessage.error("请选择日期");
    // 判断日期月份之类
    if (_form.date == nowdatemonth) return ElMessage.error("请勿选择当月");
    // 日报
    if (_form.type == 1) valueform = dayformRef.value.getvalue();
    // 月报
    if (_form.type == 2) valueform = monthformRef.value.getvalue();
    // 建设部报表
    if (_form.type == 3) valueform = constructformRef.value.getvalue();
    // 省厅报表
    if (_form.type == 4) valueform = provincesformRef.value.getvalue();

    // 判断字段是否为空
    if (Object.values(valueform).every(item => item == '')) return ElMessage.error('请填写字段')

    // 判断字段是否是数字
    if (_form.type != 3 && _form.type != 4) {
        if (!Object.values(valueform).every(item => isNumber(item))) return ElMessage.error('请输入正确的数值')
    }

    if (_form.type == 1) {
        if (!isInteger(valueform.saleCount)) return ElMessage.error('套数请输入整数')
        if (!isInteger(valueform.secondCount)) return ElMessage.error('套数请输入整数')
    }

    if (_form.type == 2) {
        if (!isInteger(valueform.resApproveCount)) return ElMessage.error('套数请输入整数')
        if (!isInteger(valueform.resSaleDownCount)) return ElMessage.error('套数请输入整数')
        if (!isInteger(valueform.resSaleUpCount)) return ElMessage.error('套数请输入整数')
        if (!isInteger(valueform.resInventoryTotalCount)) return ElMessage.error('套数请输入整数')
    }

    function isInteger(obj: any) {
        return obj % 1 === 0
    }
    // 新增
    if (state.dialog.type == '0') add(valueform)
    if (state.dialog.type == '1') edit(valueform)
};

function isNumber(value: any) {
    return /^[0-9]+(\.[0-9]+)?$/.test(value);
}

async function add(form: object) {
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    let _form = Object.assign(state.ruleForm, form)
    // 新增日报
    if (state.ruleForm.type == 1) {
        let item = await getApi().dayAdd(_form)
        loading.close();
        if (item.code == 500) return ElMessage.error(item.msg)
        ElMessage.success(item.msg)
        closeDialog()
        emit('refresh')
    }
    // 新增月报
    if (state.ruleForm.type == 2) {
        let ar = _form.date.split('-')
        _form.years = ar[0]
        _form.month = ar[1]
        let item = await getApi().monthAdd(_form)
        loading.close();
        if (item.code == 500) return ElMessage.error(item.msg)
        ElMessage.success(item.msg)
        closeDialog()
        emit('refresh')
    }

    // 新增建设部报表
    if (state.ruleForm.type == 3) {
        let ar = _form.date.split('-')
        _form.years = ar[0]
        _form.month = ar[1]
        let item = await getApi().jsAdd(_form)
        loading.close();
        if (item.code == 500) return ElMessage.error(item.msg)
        ElMessage.success(item.msg)
        closeDialog()
        emit('refresh')
    }

    // 新增省厅报表
    if (state.ruleForm.type == 4) {
        let ar = _form.date.split('-')
        _form.years = ar[0]
        _form.month = ar[1]
        let item = await getApi().stAdd(_form)
        loading.close();
        if (item.code == 500) return ElMessage.error(item.msg)
        ElMessage.success(item.msg)
        closeDialog()
        emit('refresh')
    }
}

async function edit(form: object) {
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    let _form = Object.assign({ id: state.ruleForm.id, escalationId: state.uid }, form)
    // 修改日报
    if (state.ruleForm.type == 1) {
        let item = await getApi().dayput(_form)
        loading.close();
        if (item.code == 500) return ElMessage.error(item.msg)
        ElMessage.success(item.msg)
        closeDialog()
        emit('refresh')
    }
    // 修改月报
    if (state.ruleForm.type == 2) {
        let sform = Object.assign({ years: state.ruleForm.years, month: state.ruleForm.month, reportMonthId: state.ruleForm.reportMonthId, escalationId: state.uid }, _form)
        let item = await getApi().monthput(sform)
        loading.close();
        if (item.code == 500) return ElMessage.error(item.msg)
        ElMessage.success(item.msg)
        closeDialog()
        emit('refresh')
    }

    // 修改月报
    if (state.ruleForm.type == 3) {
        let sform = Object.assign({}, _form)
        let item = await getApi().jsput(sform)
        loading.close();
        if (item.code == 500) return ElMessage.error(item.msg)
        ElMessage.success(item.msg)
        closeDialog()
        emit('refresh')
    }

    // 修改省厅月报
    if (state.ruleForm.type == 4) {
        let sform = Object.assign({}, _form)
        let item = await getApi().stput(sform)
        loading.close();
        if (item.code == 500) return ElMessage.error(item.msg)
        ElMessage.success(item.msg)
        closeDialog()
        emit('refresh')
    }

}

// emit('refresh')

// 暴露变量
defineExpose({
    openDialog,
});
</script>
<style lang="scss">
.over {
    overflow-x: auto;
    width: 100%;
}

.card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 16px;
    font-weight: bold;
}

.card-footer {
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
  