<template>
    <div class="bigBox">
        <MOSTY.FromPage :title="props.title" @closeDialog="black">
            <template #content>
                <MOSTY.Assort :title="'基本信息'" />
                <div class="fromBox">
                    <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="148px" :model="formData"
                        :inline="true" :rules="rules" :disabled="!saveBtn">
                        <el-form-item label="发起单位:" prop="ssdwmc">
                            <el-input v-model="formData.ssdwmc" readonly clearable style="width: 335px"
                                :disabled="props.rowid">
                                <template #append>
                                    <el-button class='cursor' @click="ChooesDdld('02')">选择</el-button></template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="体检名称:" prop="title">
                            <el-input v-model="formData.title" clearable style="width: 335px" />
                        </el-form-item>
                        <el-form-item label="体检时间:" prop="addtime">
                            <el-date-picker v-model="formData.addtime" style="width: 335px" type="date"
                                format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                        </el-form-item>
                        <el-form-item label="体检类型：" prop="type">
                            <el-select v-model="formData.type" placeholder="请选择体检类型" style="width: 335px"
                                :disabled="props.rowid" @change="typeChange">
                                <el-option v-for="item in props.zdlist.D_BZ_ZYJKTJLB" :key="item.value"
                                    :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="危害因素：" prop="hazardousfactors" v-if="formData.type == '1'">
                            <el-select v-model="formData.hazardousfactors" placeholder="请选择危害因素" :disabled="props.rowid"
                                style="width: 335px" @change="hazardousChange">
                                <el-option v-for="item in props.zdlist.D_TB_ZYJK_WHYS" :key="item.value"
                                    :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="特殊作业类型：" prop="specialHomeworkCategories" v-if="formData.type == '2'">
                            <el-select v-model="formData.specialHomeworkCategories" placeholder="请选择特殊作业类型"
                                style="width: 335px" :disabled="props.rowid">
                                <el-option v-for="item in props.zdlist.D_BZ_TSZYLX" :key="item.value"
                                    :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="人员：" prop="username" v-if="!props.rowid" style="width: 100%">
                            <el-input v-model="formData.username" readonly type="textarea" autosize style="width:90%">
                            </el-input>
                            <el-button class='cursor ml30' @click="ChooesDdld('01')">选择</el-button>
                        </el-form-item>
                        <el-form-item label="备注：" style="width: 100%">
                            <el-input v-model="formData.bz" type="textarea" autosize show-word-limit maxlength="200"
                                style="width: 100%" />
                        </el-form-item>

                        <el-form-item label="附件：" style='width:100%;'>
                            <MOSTY.Upload :isAutoWidth="true" :limit="5" :nopicer="true" :isImg="false"
                             :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx','wps']"   :ShowfileList="true" v-model="formData.files" :showinput="true" :delrow="delrow">
                            </MOSTY.Upload>
                        </el-form-item>
                    </el-form>

                </div>
                <div v-if="props.rowid">
                    <MOSTY.Assort :title="'职业危害人员'" />
                    <div>
                        <el-button class="addbtn" type="primary" @click="ChooesDdld('03')" v-if='saveBtn'>
                            <el-icon>
                                <CirclePlus />
                            </el-icon>
                            <span>新增</span>
                        </el-button>
                    </div>
                    <el-table ref="multipleTableRef" stripe :data="tjjlList" style="width: 100%"
                        @selection-change="handleSelectionChange" border>
                        <el-table-column label="人员姓名" prop="username"></el-table-column>
                        <el-table-column label="所属单位名称" prop="ssdwmc" />
                        <el-table-column label="所属部门名称" prop="ssbmmc" />
                        <el-table-column label="体检状态" prop="files">
                            <template #default="{ row }">
                                <span>{{ row.files ? '已体检' : '未体检' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="上传时间" prop="addtime" />
                        <el-table-column label="是否有职业病" prop="ill" v-if="formData.type == '1'">
                            <template #default="{ row }">
                                <dict-tag :options="props.zdlist.D_BZ_SF" v-for="item in row.ill" :key="item"
                                    :value="item" />
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="250">
                            <template #default="{ row }">
                                <span class="operedit" @click="editInfo(row)">
                                    <el-icon>
                                        <EditPen />
                                    </el-icon>体检证明</span>
                                <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red"
                                    title="确定要删除?" @confirm="del(row)">
                                    <template #reference>
                                        <span class="operdel" style="color: yellowgreen" size="small">
                                            <el-icon>
                                                <Delete />
                                            </el-icon>删除</span>
                                    </template>
                                </el-popconfirm>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </template>
            <template #footer>

                <el-button type="primary" v-if="saveBtn" v-loading='loadingshow' @click="submit(ruleFormRef)">
                    <el-icon>
                        <DocumentChecked />
                    </el-icon>保存
                </el-button>
                <el-button @click="black">
                    <el-icon>
                        <DocumentDelete />
                    </el-icon>关闭
                </el-button>
            </template>
        </MOSTY.FromPage>
        <!-- 选择体检的人员  v-if="formData.type == '1'" -->
        <tjrytable v-if="showrybd2" v-model="showrybd2" :ssdwid='formData.ssdwid' :Single='singleShow'
            :hazardousfactors="formData.hazardousfactors" @choosedUsers="getSonValue" />
        <!-- 选择带队领导 -->
        <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :deptId="formData.ssdwid" :data="memberList"
            :leaderid="leaderid" @choosedUsers="getSonValue"></ChooseUser>
        <Dwhasbj v-if='showdwDept' :showDdld="showdwDept" @closezzjg="closezzjg" @listdata="getSonValue" :zzlx="zzlx"
            :searchType="'03'" :Isstrictly="true" />
        <!-- editInfo -->
        <el-dialog v-model="dialogVisible" :title="'体检证明'" :before-close="CloseEvent" width="650px">
            <div>
                <el-form :model="filFrom" label-width="129px" ref="frombt" :rules="rules2" :disabled="!saveBtn">
                    <el-form-item label="人员姓名：" prop="username">
                        <el-input v-model="filFrom.username" disabled clearable style="width: 335px" />
                    </el-form-item>
                    <el-form-item v-if="formData.type == '1'" label="是否有职业病:" prop="ill">
                        <MOSTY.DictRidioAndSelect :dictData="props.zdlist.D_BZ_SF" style="width: 335px"
                            v-model="filFrom.ill" selectType="radio" :disabled="false" />
                    </el-form-item>
                    <el-form-item label="上传附件：" prop="files" label-width="129px">
                        <MOSTY.Upload :widthNumber="438" :limit="5" :nopicer="true" :isImg="false" :ShowfileList="true"
                            v-model="filFrom.files" :showinput="true" :delrow="delrow" :keys="key"
                            @filehandleChange="changeFile1" :placeholder="'请上传图片或pdf,ofd, doc, docx,wps'"
                            :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'png', 'jpg', 'jpeg', 'bmp', 'gif','wps']">
                        </MOSTY.Upload>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" v-if="saveBtn" @click="searchfrom(frombt)" :loading="tjjlloading">
                        保存
                    </el-button>
                    <el-button @click="CloseEvent">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted, getCurrentInstance } from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import * as rule from "@/utils/rules.js";
import Dwhasbj from "@/components/MyComponents/ChooseDept/dwhasbj.vue";
import { ElMessage } from "element-plus";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import tjrytable from "./tjrytable.vue";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
const showrybd2 = ref(false)
const { proxy } = getCurrentInstance();
const tjjlloading = ref(false)
const props = defineProps({
    title: String,
    rowid: String,
    saveBtn: Boolean,
    zdlist: {
        type: Object,
        default: () => { }
    }
});
const filFrom = ref({})
const frombt = ref()
const dialogVisible = ref(false)
const loadingshow = ref(false)
const showdwDept = ref(false)
const chooseUserVisible = ref(false); //选择领导弹窗
const singleShow = ref(true); //单选多选
const memberList = ref([]); //成员选择的id回显
const leaderid = ref("");
const rowId = ref(null)
const tjjlList = ref([])
const showtjjlxq = ref(false);
const zzlx = ref(null);
const emit = defineEmits("closedial");
const ruleFormRef = ref();
const formData = ref({})
const saveBtn = ref(true);
const rules = reactive({
    ssdwmc: [{ required: true, message: "发起单位不能为空", trigger: "blur" }],
    title: [{ required: true, message: "体检名称不能为空", trigger: "blur" }],
    addtime: [{ required: true, message: "体检时间不能为空", trigger: "blur" }],
    hazardousfactors: [{ required: true, message: "危害因素不能为空", trigger: "blur" }],
    specialHomeworkCategories: [{ required: true, message: "特殊作业类型不能为空", trigger: "blur" }],
    type: [{ required: true, message: "体检类型不能为空", trigger: "blur" }],
    username: [{ required: true, message: "人员不能为空", trigger: "blur" }],
});
const rules2 = reactive({
    username: [{ required: true, message: "人员姓名不能为空", trigger: "blur" }],
    ill: [{ required: true, message: "请选择是否有职业病", trigger: "blur" }],
    files: [{ required: true, message: "请选择附件", trigger: "blur" }],

});
/** 清空选择的人员 */
const clearUser = ()=>{
    formData.value.username = ''
    formData.value.oprids = []
    formData.value.ids = []
}
const typeChange = () => {
    clearUser()
}
const hazardousChange = ()=>{
    clearUser()
}
onMounted(() => {
    saveBtn.value = props.saveBtn;
    formData.value = {}
    formData.value.files = null
    if (props.rowid) {
        gtdataxq(props.rowid)
        getjktjlist(props.rowid)
    }
})

//获取详情
function gtdataxq(id) {
    getApi({ id }, `/mosty-jcgl/health/queryById`).then(
        (res) => {
            formData.value = res;
        }
    );
}
//获取职业健康体检
function getjktjlist(id) {
    getApi({ healthId: id }, '/mosty-jcgl/health/getRecordsList').then(res => {
        if (res) {
            tjjlList.value = res
        }
    })
}


//点击带队领导选择按钮
function ChooesDdld(val) {
    zzlx.value = val;
    leaderid.value = "";
    // 人员选择
    if (val == '01') {
        /** 是否有 危害因素或者 特殊作业类型 */
        const isHadHazardousfactorsOrspecialHomeworkCategories = formData.value.type =='1' ? formData.value.hazardousfactors : formData.value.specialHomeworkCategories
        if (formData.value.ssdwid && formData.value.type && isHadHazardousfactorsOrspecialHomeworkCategories) {
            singleShow.value = false;
            if (formData.value.type == '1') {
                showrybd2.value = true
            } else {
                memberList.value = formData.value.ids
                chooseUserVisible.value = true;
            }
        } else {
            if(!formData.value.ssdwid) {
                ElMessage.warning('请先选择单位');
            } else if(!formData.value.type) {
                ElMessage.error("请先选择体检类型");
            } else {
                if (formData.value.type == '1') {
                    ElMessage.error("请先选择危害因素");
                } else {
                    ElMessage.error("请先选择特殊作业类型");
                }
            }
        }
        // 发起单位
    } else if (val == '02') {
        showdwDept.value = true;
        // 列表- 职业危害人员 03
    } else {
        singleShow.value = true
        if (formData.value.type == '1') {
            showrybd2.value = true
        } else {
            chooseUserVisible.value = true;
        }
    }

}
function closezzjg(val) {
    showdwDept.value = false;

}
//获取人员姓名
const getSonValue = (value) => {
    //  // 人员选择
    if (zzlx.value == '01') {
        // 体检类型 1
        if (formData.value.type == '1') {
            let arr1 = [];
            let arrid1 = [];
            for (let i = 0; i < value.length; i++) {
                const element = value[i];
                element.zzlx = zzlx.value;
                arr1.push(element.username);
                arrid1.push(element.id);
            }
            memberList.value = value.map((item) => {
                return item.id;
            });
            formData.value.username = arr1.toString(",");
            formData.value.oprids = arrid1
        } else {
            let arr = [];
            let arrid = [];
            for (let i = 0; i < value.length; i++) {
                const element = value[i];
                element.zzlx = zzlx.value;
                arr.push(element.userName);
                arrid.push(element.id);
            }
            memberList.value = value.map((item) => {
                return item.id;
            });
            formData.value.username = arr.toString(",");
            formData.value.ids = arrid
        }

    } else if (zzlx.value == '02') {
        formData.value.ssdwmc = value.orgname;
        formData.value.ssdwid = value.id.replace('XN', '');
        formData.value.username = null;
        formData.value.ids = null;
    } else {
        var params = {
            healthId: formData.value.id
        }
        if (formData.value.type == '1') {
            params.oprId = value[0].id
            getaddry(params)
        } else {
            params.userId = value[0].id
            getaddry(params)
        }


    }
};
//删除
function del(row) {
    postApi({}, `/mosty-jcgl/health/delPerson/${row.id}`).then(res => {
        ElMessage.success("删除成功");
        getjktjlist(formData.value.id)
    })
}
// 新增体检人员 - 单个新增
function getaddry(params) {
    postApi(params, '/mosty-jcgl/health/addRecords').then((res) => {
        ElMessage.success("新增成功");
        getjktjlist(formData.value.id)
    })
}
//体检证明
function editInfo(row) {
    filFrom.value.username = row.username
    filFrom.value.type = formData.value.type
    filFrom.value.id = row.id
    filFrom.value.files = row.files
    filFrom.value.ill = row.ill
    dialogVisible.value = true
}
//查看体检记录详情
function onloadflie(row) {
    rowId.value = row.id
    showtjjlxq.value = true

}
function CloseEvent() {
    if (saveBtn.value) {
        proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
            .then(() => {
                dialogVisible.value = false
                filFrom.value.username = null
                filFrom.value.id = null
                filFrom.value.files = null
                filFrom.value.ill = null
            })
            .catch(() => {
                // catch error
            })
    } else {
        dialogVisible.value = false
        filFrom.value.username = null
        filFrom.value.id = null
        filFrom.value.files = null
        filFrom.value.ill = null
    }

}
const searchfrom = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            tjjlloading.value = true
            filFrom.value.files = filFrom.value.files ? filFrom.value.files.toString() : null
            postApi(filFrom.value, '/mosty-jcgl/health/upFile').then(res => {
                ElMessage.success("上传成功");
                tjjlloading.value = false
                dialogVisible.value = false
                getjktjlist(formData.value.id)
            }).catch(err => {
                tjjlloading.value = false
            })
        }
    })
}
// 保存
const submit = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            loadingshow.value = true
            formData.value.files = formData.value.files ? formData.value.files.toString() : null;
            if (!formData.value.id) {
                postApi(formData.value, "/mosty-jcgl/health/add").then((res) => {
                    ElMessage.success("新增成功");
                    emit("closedial", "Main");
                    loadingshow.value = false
                }).finally(() => {
                    loadingshow.value = false
                })
            } else {
                postApi(formData.value, "/mosty-jcgl/health/update").then((res) => {
                    ElMessage.success("修改成功");
                    emit("closedial", "Main");
                    loadingshow.value = false
                }).finally(() => {
                    loadingshow.value = false
                })
            }
        }
    });
};

const black = () => {
    if (saveBtn.value) {
        proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
            .then(() => {
                // 关闭上一次的表单校验
                ruleFormRef.value.clearValidate();
                emit("closedial");
            })
            .catch(() => {
                // catch error
            })
    } else {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
        emit("closedial");
    }

};
</script>

<style lang="scss" scoped>
::-webkit-scrollbar {
    width: 0 !important;
    height: 0;
}

.box_cont {
    height: 80vh;
    overflow-y: scroll;
}

.fromBox {
    width: 100%;
    margin: 20px auto;
    padding: 15px 15px 0 15px;
    border-radius: 1px;
}

.ld_box {
    display: flex;
    margin-right: 20px;
}

.el-form {
    width: 100%;
    align-items: center;
    display: flex;
    flex-wrap: wrap;
    flex-wrap: wrap;
}

.el-form-item {
    display: flex;
    margin-right: 20px;
}

.addbtn {
    margin-bottom: 10px;
}

.bigBox {
    display: block !important;
    box-sizing: border-box;
}

.tabbox {
    max-height: 300px;
    overflow-y: scroll;

    .input {
        width: 100%;
        height: 100%;
    }
}

::v-deep .el-table .cell {
    padding: 0 0 !important;
}

::v-deep .el-table--border .el-table__cell .cell {
    padding-left: 0px !important;

    >input {
        width: 100%;
        height: 33px;
    }
}

::v-deep .el-upload-list {
    width: 50%;
}
</style>