<template>
    <div class="bigBox" :style="{ height: bigHeight }">
        <MOSTY.FromPage :title="props.title" @closeDialog="CloseEvent">
            <template #content>
                <MOSTY.Assort :title="'基本信息'" />
                <div style="width: 100%;height: 77vh; overflow-y: scroll;">
                    <el-form ref="ruleFormRef" :model="data.addForm" :rules="rules" :disabled="!props.saveBtnShow"
                        label-width="150px" :size="formSize" status-icon :inline="true">
                        <el-form-item label="年度:" prop="year">
                            <el-select v-model="data.addForm.year" filterable style="width: 400px" disabled>
                                <el-option v-for="item in filterYear(7)" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="上/下半年:" prop="quarter">
                            <el-select v-model="data.addForm.quarter" clearable placeholder="请选择上/下半年"
                                style="width: 400px" :disabled="isEdit" @change="retrievalTimes">
                                <el-option label="上半年" value='1' />
                                <el-option label="下半年" value='2' />
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="isFirstAdd" label="会议次数:" prop="frequency">
                            <el-select v-model="data.addForm.frequency" clearable placeholder="请选择会议次数"
                                style="width: 400px" :disabled="isEdit">
                                <el-option v-if="data.addForm.frequencyNum"
                                    :label="`第${data.addForm.frequencyNum || 'XX'}次会议`"
                                    :value="data.addForm.frequencyNum" />
                                <el-option v-else :label="`-`" :value="''" />
                            </el-select>
                        </el-form-item>
                        <el-form-item v-else label="会议次数:" prop="frequency">
                            <el-input style="width: 400px;" v-model="frequencyDisplay" disabled />
                        </el-form-item>
                        <el-form-item label="参会日期:" prop="time">
                            <el-date-picker v-model="data.addForm.time" type="date" value-format="YYYY-MM-DD"
                                style="width: 400px" placeholder="请选择参会日期" />
                        </el-form-item>
                        <el-form-item label="会议名称:" prop="meetingname">
                            <el-input v-model="data.addForm.meetingname" autocomplete="off" style="width:400px" />
                        </el-form-item>
                        <el-form-item label="参会人员:" prop="username">
                            <el-input v-model="data.addForm.username" type="textarea" :autosize="{ minRows: 3 }"
                                readonly style="width:917px;margin-right:5px;"></el-input>
                            <el-button type="primary" @click="ChooesDdld('05')">选择</el-button>
                        </el-form-item>
                        <el-form-item label="签到表:">
                            <MOSTY.Upload v-model="data.addForm.signin" :widthNumber="984" :showinput="true" :limit="1"
                                :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx', 'wps']" :delrow="delrow"
                                :showbut="true" :nopicer="true" :isEdit="fileEdit" @filehandleChange="changeFile1"
                                :ShowfileList="true" :isImg="false" />
                        </el-form-item>
                        <el-form-item label="会议记录/纪要:" style="display: flex; width: 100%">
                            <div style="display: flex; width: 100%">
                                <MOSTY.Upload v-model="data.addForm.files" :widthNumber="984" :nopicer="true"
                                    :showinput="true" :limit="1" :delrow="delrow" :showbut="true" :isEdit="fileEdit"
                                    @filehandleChange="changeFile" :ShowfileList="true" :isImg="false"
                                    :placeholder="'请上传pdf,ofd, doc, docx,wps'"
                                    :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'wps']" />
                            </div>
                        </el-form-item>
                        <el-form-item label="会议图片:">
                            <MOSTY.Upload :width="917" :limit="3" :nopicer="false" :isImg="true" :ShowfileList="false"
                                v-model="data.addForm.pics" :nameshow='true' :gsgfList="['jpg', 'png']"
                                :disabled="!props.saveBtnShow">
                            </MOSTY.Upload>
                        </el-form-item>
                        <el-form-item label="备注:">
                            <el-input v-model="data.addForm.bz" type="textarea" :autosize="{ minRows: 3 }"
                                autocomplete="off" style="width:984px" />
                        </el-form-item>
                    </el-form>
                </div>
            </template>
            <template #footer>

                <el-button style="margin-left: 10px" type="primary" v-if="props.saveBtnShow" :loading="loading"
                    @click="searchHander(ruleFormRef)">
                    <el-icon>
                        <DocumentChecked />
                    </el-icon>
                    <span>保存</span>
                </el-button>
                <el-button type="primary" @click="CloseEvent">
                    <el-icon>
                        <DocumentDelete />
                    </el-icon>
                    <span>关闭</span>
                </el-button>
            </template>
        </MOSTY.FromPage>

        <!-- 选择带队领导 -->
        <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :leaderid="leaderid"
            :deptId="props.orgcode" @choosedUsers="getSonValue"></ChooseUser>
    </div>
</template>

<script setup>
import { onMounted, ref, defineEmits, reactive, getCurrentInstance, watchEffect, computed } from "vue";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import { filterYear } from "@/utils/auth.js";
import { ElMessage } from "element-plus";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi } from "@/api/tobAcco_api.js";
const { proxy } = getCurrentInstance();
// const { D_BZ_QUARTER } = proxy.$dict("D_BZ_QUARTER");
const emits = defineEmits(["close"]);
const chooseUserVisible = ref(false);
const ruleFormRef = ref();
const leaderid = ref(null);
const filename = ref("");
const hyjyname = ref("");
const singleShow = ref(true); //单选多选
const fileEdit = ref(true);
const zzlx = ref(null);
const memberList = ref([]); //成员选择的id回显
const props = defineProps({
    orgcode: String,
    ywid: String,
    saveBtnShow: {
        default: true,
        type: Boolean
    },
    isFirstAdd: {
        default: false,
        type: Boolean
    },
    frequencyNum: {
        type: Number,
    },
    title: String,
    rowId: String,
    orgcode: String,
    isEdit: {
        default: false,
        type: Boolean
    },
    rowData: Object
});
const data = reactive({
    addForm: {
        type: "1",
        year: new Date().getFullYear()
    }
});
//规则校验
const rules = reactive({
    year: [{ required: true, message: "年度不能为空", trigger: "blur" }],
    time: [{ required: true, message: "参会日期不能为空", trigger: "blur" }],
    quarter: [{ required: true, message: "上/下半年不能为空", trigger: "blur" }],
    frequency: [{ required: true, message: "会议次数不能为空", trigger: "blur" }],
    meetingname: [{ required: true, message: "会议名称不能为空", trigger: "blur" }],
    files: [{ required: true, message: "会议纪要不能为空", trigger: "blur" }],
    username: [{ required: true, message: "参会人员不能为空", trigger: "blur" }]
});
const listQuery = reactive({});
const loading = ref(false); //新增保存按钮截流
// 初始化
onMounted(() => {
    if (props.rowId) {
        xqData(props.rowId)
    }
    if (!props.isFirstAdd) {
        data.addForm.frequency = props.frequencyNum;
        data.addForm.frequencyNum = props.frequencyNum;
    }
    data.addForm.orgcode = props.orgcode;
    data.addForm.deptId = props.orgcode;
    listQuery.orgCode = data.addForm.orgcode;
})
const frequencyDisplay = computed(() => {
    return `第${data.addForm.frequency || 'XX'}次会议`;
});
// 其他安全机构
const typeNum = ref('1')
// 获取第几次
const retrievalTimes = (row) => {
    if (row) {
        let dataFrom = {
            orgcode: props.orgcode,
            quarter: row,
            type: typeNum.value
        };
        data.addForm.frequency = null;
        postApi(dataFrom, "/mosty-jcgl/meeting/selectYearMeetingCount")
            .then((res) => {
                res = res + 1;
                // frequency 用来提交接口（数字）
                data.addForm.frequency = res;
                // frequencyNum 用来渲染 option
                data.addForm.frequencyNum = res;
            })
            .catch(() => {
                console.log("获取失败");
            });
    } else {
        data.addForm.frequency = '';
        data.addForm.frequencyNum = 0;
    }
};
// 新的文件上传返回
const changeFile1 = (row) => {
    hyjyname.value = row[0].name;
};
const changeFile = (row) => {
    filename.value = row[0].name;
};
function ChooesDdld(val) {
    zzlx.value = val;
    if (val == "05" && data.addForm.userid) {
        memberList.value = data.addForm.userid.split(',')
    }
    chooseUserVisible.value = true;
    singleShow.value = false;
}
const getSonValue = (value) => {
    if (zzlx.value == "05") {
        let arr = [];
        let arrid = [];
        for (let i = 0; i < value.length; i++) {
            const element = value[i];
            element.zzlx = zzlx.value;
            arr.push(element.userName + "(" + element.deptName + ")");
            arrid.push(element.id);
        }
        memberList.value = value.map((item) => {
            return item.id;
        });
        data.addForm.usernamelist = value.map((item) => {
            return {
                userid: item.id,
                username: item.userName
            };
        });
        data.addForm.username = arr.join(",");
        data.addForm.userid = arrid.join(",");
    }
};
const CloseEvent = () => {
    if (props.saveBtnShow) {
        proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
            .then(() => {
                data.addForm = {};
                emits("close");
            })
            .catch(() => {
                // catch error
            })
    } else {
        data.addForm = {};
        emits("close");
    }

};
function xqData(id) {
    getApi({}, "/mosty-jcgl/meeting/getTbMeetingById/" + id).then((res) => {
        if (res) {
            data.addForm = res;
        }
    });
}
const searchHander = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            loading.value = true;
            data.addForm.pics = data.addForm.pics ? data.addForm.pics.toString() : null
            data.addForm.signin = data.addForm.signin ? data.addForm.signin.toString() : null;
            data.addForm.files = data.addForm.files ? data.addForm.files.toString() : null;
            data.addForm.type = "1";
            data.addForm.orgcode = props.orgcode
            data.addForm.ywid = props.ywid
            if (!data.addForm.id) {
                postApi(data.addForm, "/mosty-jcgl/meeting/addMeeting").then(() => {
                    loading.value = false;
                    ElMessage.success("新增成功");
                    emits("close");
                }).catch(() => {
                    loading.value = false;
                });
            } else {
                postApi(data.addForm, "/mosty-jcgl/meeting/editMeeting").then(() => {
                    loading.value = false;
                    ElMessage.success("修改成功");
                    emits("close");
                }).catch(() => {
                    loading.value = false;
                });
            }
        } else {
            ElMessage.warning('请输入必填项！！！')
        }
    })
};

watchEffect(() => {
    if (props.rowData) {
        data.addForm = props.rowData
    } else {
        data.addForm.year = new Date().getFullYear()
    }
});
</script>

<style lang="scss" scoped>
.el-form {
    display: block;
    padding: 20px 0;
    width: 1200px;
    margin: 0 auto;
}

.right {
    width: 100%;
}

.bigBox {
    display: block !important;
    box-sizing: border-box;
}
</style>