<template>
    <div>
        <div class="bigBox">
            <MOSTY.FromPage :title="props.title" @closeDialog="handleClose">
                <template #content>
                    <div class="config">
                        <div class="box-big">
                            <div class="box-left">
                                <el-form class="elfrom" ref="ruleFormRef" :model="ruleForm" :rules="rules"
                                    label-width="100px" :disabled="props.isdisabled" :inline="true"
                                    style="display: block;">
                                    <el-form-item label="责任书名称:" prop="zrsmc">
                                        <el-input v-model="ruleForm.zrsmc" clearable style="width: 646px"></el-input>
                                    </el-form-item>
                                    <el-form-item label="责任书类型:" prop="lxs" style='width:100%;'>
                                        <el-radio-group v-model="ruleForm.lxs" size="small" @change="changeLxs"
                                            :disabled='ISbj'>
                                            <el-radio v-for="item in zslxlist" :value="item.value" :key="item.value"
                                                :label="item.value" border>{{ item.label }}</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                    <el-form-item :label="fqText + ':'" prop="fqdwid">
                                        <el-input v-model="ruleForm.fqdwmc" clearable style="width:260px" disabled>
                                            <template #append>
                                                <el-button disabled>选择</el-button>
                                            </template>
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item label="审批领导:">
                                        <el-input v-model="ruleForm.ldxm" clearable style="width:260px" disabled>
                                            <template #append>
                                                <el-button @click="inputClick('02')">选择</el-button>
                                            </template>
                                        </el-input>
                                    </el-form-item>

                                    <!-- 签订单位，被签订单位，签订部门 -->
                                    <el-form-item :label="bqdText + ':'" prop="rydwid">
                                        <el-input v-model="ruleForm.rydwmc" clearable style="width:260px"
                                            :placeholder="'请选择' + bqdText" :disabled='ISbj || bisab'>
                                            <template #append>
                                                <el-button @click="ChooesDdld">选择</el-button>
                                            </template>
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item label="签订人:">
                                        <el-input v-model="ruleForm.ryxm" placeholder="请选择签订人" clearable
                                            style="width:260px" :disabled='ISbj'>
                                            <template #append>
                                                <el-button @click="inputClick('01')">选择</el-button>
                                            </template>
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item label="责任书内容:" prop="files" style='width:100%;'>
                                        <MOSTY.Upload :limit="1" :nopicer="true" :isImg="false"
                                            nameshow="(注:只能上传一个文件,格式:pdf,doc,docx,wps,png,jpg,wps)"
                                            :gsgfList="['pdf', 'doc', 'docx', 'wps', 'png', 'jpg', 'wps']"
                                            :ShowfileList="true" v-model="ruleForm.files" :showinput="false"
                                            :delrow="delrow" :disabled="props.isdisabled"></MOSTY.Upload>
                                        <div style="color: red;">(注:只能上传一个文件,格式:pdf,doc,docx,wps,png,jpg)</div>
                                    </el-form-item>
                                </el-form>
                            </div>
                        </div>

                    </div>


                </template>
                <template #footer>

                    <el-button class="btn-clas" @click="showKKfile"
                        v-if="props.title.indexOf('查看') != -1 || props.title.indexOf('修改') != -1">
                        <el-icon>
                            <View />
                        </el-icon>
                        <span>附件预览</span>
                    </el-button>
                    <el-button class="btn-clas" @click="downloadFile"
                        v-if="props.title.indexOf('查看') != -1 || props.title.indexOf('修改') != -1">
                        <el-icon>
                            <Download />
                        </el-icon>
                        <span>附件下载</span>
                    </el-button>
                    <el-button type="primary" :loading="loading" @click="handleSave(ruleFormRef, '0')"
                        v-if="!props.isdisabled">
                        <el-icon>
                            <DocumentChecked />
                        </el-icon>
                        <span>保存</span>
                    </el-button>
                    <el-button class="btn-clas" @click="handleClose">
                        <el-icon>
                            <DocumentDelete />
                        </el-icon>
                        <span>关闭</span>
                    </el-button>
                </template>
            </MOSTY.FromPage>

            <!-- 选择部门 -->
            <Choosebm :showDdld="showDept" @closezzjg="closezzjg" :deptId="dwdeptId" :searchType="searchType"
                @listdata="getSonValues" :zzlx="zzlx" />
            <!-- 选择人员弹窗 -->
            <ChooseUser v-model="chooseUserVisible" :deptId="deptId" :Single="Single" :data="memberList" :zzlx="zzlx"
                :leaderid="leaderid" @choosedUsers="getSonValue" :key='keys'></ChooseUser>
            <!-- 预览 -->
            <div v-if="dialogVisible" class="dialog-box">
                <Kkfile :files="ruleForm.files" @changedialog="changedialog" />
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, reactive, getCurrentInstance } from "vue";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue";
import { getItem } from "@/utils/storage";
import { getApi, postApi, putApi } from "@/api/tobAcco_api.js";
import Kkfile from "../../../../components/MyComponents/kkfile/index.vue";
import { ElMessage } from "element-plus";
import { getFile } from "@/utils/getFile.js";
import * as MOSTY from "@/components/MyComponents/index";
const { proxy } = getCurrentInstance();
//新增保存按钮截流
const loading = ref(false);
const Single = ref(true);
const ISbj = ref(false);
const ruleFormRef = ref();
const leaderid = ref("");
const dialogVisible = ref(false);
const searchType = ref("02");
const zzlx = ref("");
const chooseUserVisible = ref(false);
// 删除文件列表
const delrow = ref({});
const showDept = ref(false);
const bisab = ref(false)
const deptId = ref(null)
const dwdeptId = ref(null)
const keys = ref(0)
const fqText = ref('发起单位')
const bqdText = ref('被签订单位')
const isdisabled = ref(false);
const memberList = ref([]); //成员选择的id回显
const zslxlist = ref([
    { value: "01", label: "单位对单位" },
    { value: "02", label: "班子成员对分管部门负责人" },
    { value: "03", label: "部门负责人对部门员工" },
    { value: "04", label: "主要领导对班子成员" },
]);
const emits = defineEmits(["changeAddVi"]);
//表单数据
const ruleForm = ref({
    signtype: "1",
    fqdwid: getItem("deptId").ssdwmc,
    fqsgsid: getItem("deptId").ssdwid,
    fqdwmc: getItem("deptId").ssbmmc,
    rydwid: getItem("deptId").ssdwid,
    rybmmc: getItem("deptId").ssdwmc,
});
//规则校验
const rules = reactive({
    zrsmc: [{ required: true, message: "责任书名称不能为空", trigger: "blur" }],
    lxs: [{ required: true, message: "责任书类型不能为空", trigger: "blur" }],
    fqdwid: [{ trigger: "blur", required: true, message: "发起单位不能为空" }],
    rydwid: [{ trigger: "change", required: true, message: "被签订单位不能为空" }],
    files: [{ trigger: "blur", required: true, message: "附件不能为空" }],
});
// 附件下载
async function downloadFile() {
    let data = await getFile(ruleForm.value.files)
    fileAjax(data.innerUrl, function (xhr) {
        _downloadFile(xhr.response, data.originalName)
    }, {
        responseType: 'blob'
    })
}

function fileAjax(url, callback, options) {
    let xhr = new XMLHttpRequest()
    xhr.open('get', url, true)
    if (options.responseType) {
        xhr.responseType = options.responseType
    }
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            callback(xhr)
        }
    }
    xhr.send()
}

function _downloadFile(content, filename) {
    window.URL = window.URL || window.webkitURL
    let a = document.createElement('a')
    let blob = new Blob([content])
    // 通过二进制文件创建url
    let url = window.URL.createObjectURL(blob)
    a.href = url
    a.download = filename
    a.click()
    // 销毁创建的url
    window.URL.revokeObjectURL(url)
}
const props = defineProps({
    rowdata: {
        type: Object,
        default: {}
    },
    title: String,
    xqId: {
        type: String,
        default: ""
    },
    isdisabled: {
        type: Boolean,
        default: false
    }
});

// 初始化
onMounted(() => {
    resetfrom()
    ruleForm.value.signtype = '2';
    ISbj.value = false
    let dept = getItem("deptId");
    // 安全部门
    if (dept.orgBizType == "04" || dept.orgBizType == "52") {
        if (dept.orgLevel.substring(0, 1) == '1' || dept.orgLevel.substring(0, 1) == '2') {
            ruleForm.value.lxs = "01";
        } else if (dept.orgLevel.substring(0, 1) == '3') {
            ruleForm.value.lxs = "02";
            zslxlist.value.splice(0, 1);
        } else {
            ruleForm.value.lxs = "03";
            zslxlist.value.splice(0, 1);
        }
        // 非安全部门
    } else {
        ruleForm.value.lxs = "03";
        // zslxlist.value.splice(2, 3);
        zslxlist.value = zslxlist.value.slice(2, 3) // 普通部门只有 部门对个人
    }
    if (props.xqId) {
        ISbj.value = true
        zrsxqdata(props.xqId)
    } else {
        ISbj.value = false
        changeLxs()
    }
});
// 责任书预览页面跳转
function showKKfile() {
    dialogVisible.value = true
}
//关闭预览
function changedialog() {
    dialogVisible.value = false;
}
// 切换责任书类型
const changeLxs = async () => {
    bisab.value = false
    let dept = getItem("deptId");
    let orgLevel = dept.orgLevel.substring(0, 1);
    dwdeptId.value = null
    searchType.value = null
    ruleForm.value.rydwid = '';
    ruleForm.value.rydwmc = '';
    ruleForm.value.ryid = null
    ruleForm.value.ryxm = null
    // 单位对单位
    if (ruleForm.value.lxs == '01') {
        dwdeptId.value = null

        if (orgLevel == '1') {
            searchType.value = "02";
        } else if (orgLevel == '2') {
            searchType.value = "03";
        }
        fqText.value = '发起单位'
        bqdText.value = '被签订单位'
        ruleForm.value.fqdwid = dept.ssdwid
        ruleForm.value.fqdwmc = dept.ssdwmc
        // 查询发起单位领导
        let ry = await getRy(ruleForm.value.fqdwid, null)
        ruleForm.value.ldid = ry.fqdwid
        ruleForm.value.ldxm = ry.fqdwname
    }
    // 单位对部门
    if (ruleForm.value.lxs == '02') {
        searchType.value = "01";
        fqText.value = '发起单位'
        bqdText.value = '签订部门'
        dwdeptId.value = dept.ssdwid
        ruleForm.value.fqdwid = dept.ssdwid
        ruleForm.value.fqdwmc = dept.ssdwmc
        let ry = await getRy(ruleForm.value.fqdwid, null)
        ruleForm.value.ldid = ry.fqdwid
        ruleForm.value.ldxm = ry.fqdwname
        timelist.value[1].czrname = ruleForm.value.ldxm
    }
    // 部门对个人
    if (ruleForm.value.lxs == "03") {
        fqText.value = '发起部门'
        bqdText.value = '签订人'
        bisab.value = true
        dwdeptId.value = dept.ssdwid
        ruleForm.value.fqdwid = dept.ssbmid
        ruleForm.value.fqdwmc = dept.ssbmmc
        ruleForm.value.rydwid = dept.ssbmid
        ruleForm.value.rydwmc = dept.ssbmmc
        let ry = await getRy(ruleForm.value.fqdwid, null)
        ruleForm.value.ldid = ry.fqdwid
        ruleForm.value.ldxm = ry.fqdwname
        let rys = await getRy(null, ruleForm.value.rydwid)
        ruleForm.value.ryid = rys.ryid
        ruleForm.value.ryxm = rys.ryxm
    }
    // "04", "主管领导对分管领导"
    if (ruleForm.value.lxs == "04") {
        fqText.value = '发起单位'
        bqdText.value = '签订人'
        bisab.value = true
        dwdeptId.value = dept.ssdwid
        ruleForm.value.fqdwid = dept.ssdwid
        ruleForm.value.fqdwmc = dept.ssdwmc
        ruleForm.value.rydwid = dept.ssdwid
        ruleForm.value.rydwmc = dept.ssdwmc
        let ry = await getRy(ruleForm.value.rydwid, ruleForm.value.rydwid)
        ruleForm.value.ldid = ry.fqdwid
        ruleForm.value.ldxm = ry.fqdwname
        ruleForm.value.ryid = ry.bqddwid
        ruleForm.value.ryxm = ry.bqddwname
    }
}
// 查询审核人员活被签订人员
const getRy = async (fqdwid, bqddwbmid) => {
    let data = {
        zrslx: ruleForm.value.lxs,
        fqdwid: fqdwid,
        bqddwbmid: bqddwbmid
    }
    return new Promise(ok => {
        getApi(data, '/mosty-jcgl/securitychild/getFgldByZrslx').then((res) => {
            ok(res)
        })
    })
}
//重置
function resetfrom() {
    isdisabled.value = false;
    ruleFormRef.value.clearValidate();
    ruleFormRef.value.resetFields()
    ruleForm.value.fqdwid = getItem("deptId").ssdwmc;
    ruleForm.value.fqsgsid = getItem("deptId").ssdwid;
}
//获取责任书详情
function zrsxqdata(id) {
    getApi({ id }, '/mosty-jcgl/zrs/getZrsInfo').then((res) => {
        ruleForm.value = res;
        ruleForm.value.lxs = res.zrslx
        ruleForm.value.fqxgsmc = getItem("deptId").ssdwmc
        ruleForm.value.fqsgsid = getItem("deptId").ssdwid
        ruleForm.value.ldspyj = ruleForm.value.ldspyj ? ruleForm.value.ldspyj : '无'
        ruleForm.value.zrzdContent = res.zrzd
        ruleForm.value.zrqdContent = res.zrqd
        /** 责任书类型 */
        const lxs = ruleForm.value.lxs
        let dept = getItem("deptId");
        let orgLevel = dept.orgLevel.substring(0, 1);
        switch (lxs) {
            case '01':
                dwdeptId.value = null
                if (orgLevel == '1') {
                    searchType.value = "02";
                } else if (orgLevel == '2') {
                    searchType.value = "03";
                }
                fqText.value = '发起单位'
                bqdText.value = '被签订单位'
                break;
            case '02':
                searchType.value = "01";
                fqText.value = '发起单位'
                bqdText.value = '签订部门'
                dwdeptId.value = dept.ssdwid
                break;
            case '03':
                fqText.value = '发起部门'
                bqdText.value = '签订部门'
                searchType.value = "01";
                bisab.value = true
                dwdeptId.value = dept.ssdwid
                break;
            case '04':
                fqText.value = '发起单位'
                bqdText.value = '签订单位'
                searchType.value = '03'
                bisab.value = true
                dwdeptId.value = dept.ssdwid
                break;
        }
    })
}


//选择部门
function ChooesDdld() {
    showDept.value = true;
}
//获取部门信息
const getSonValues = async (val) => {
    ruleForm.value.rydwid = val.id;
    ruleForm.value.rydwmc = val.orgName;
    deptId.value = val.id;
    // 02:单位对部门
    if (ruleForm.value.lxs == '02') {
        let ry = await getRy(null, ruleForm.value.rydwid)
        ruleForm.value.ryid = ry.bqddwid
        ruleForm.value.ryxm = ry.bqddwname
        let ld = await getRy(ruleForm.value.rydwid, null)
        ruleForm.value.ldid = ld.fqdwid
        ruleForm.value.ldxm = ld.fqdwname
    } else {
        let ry = await getRy(null, ruleForm.value.rydwid)
        ruleForm.value.ryid = ry.bqddwid
        ruleForm.value.ryxm = ry.bqddwname
    }
}
//关闭弹窗
const closezzjg = (val) => {
    showDept.value = val;
};
// 选择人员
function inputClick(val) {
    zzlx.value = val;
    deptId.value = null
    leaderid.value = null
    // 签订人
    if (val == "01") {
        Single.value = true
        deptId.value = ruleForm.value.rydwid
        leaderid.value = ruleForm.value.ryid ? ruleForm.value.ryid : null;
        chooseUserVisible.value = true;
        // 审批领导
    } else if (val == "02") {
        deptId.value = ruleForm.value.fqsgsid
        leaderid.value = ruleForm.value.ldid ? ruleForm.value.ldid : null;
        chooseUserVisible.value = true;
    }
}
//人员回显
const getSonValue = (value) => {
    if (zzlx.value == "01") {
        ruleForm.value.ryxm = value[0].userName;
        ruleForm.value.ryid = value[0].id;
    } else if (zzlx.value == "02") {
        ruleForm.value.ldxm = value[0].userName;
        ruleForm.value.ldid = value[0].id;
    }
};
// 关闭
const handleClose = () => {
    if (!props.isdisabled) {
        proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
            .then(() => {
                ISbj.value = false
                ruleForm.value = {}
                ruleFormRef.value.resetFields()
                emits("changeAddVi", false);
            })
            .catch(() => {
                // catch error
            })
    } else {
        ISbj.value = false
        ruleForm.value = {}
        ruleFormRef.value.resetFields()
        emits("changeAddVi", false);
    }

};
// 保存
const handleSave = async (formEl, val) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            loading.value = true;
            ruleForm.value.zrslx = ruleForm.value.lxs
            ruleForm.value.xfzt = val
            if (!ruleForm.value.files) {
                ElMessage.warning("请上传附件");
                return
            }
            ruleForm.value.files = ruleForm.value.files ? ruleForm.value.files.toString() : null
            if (!ruleForm.value.id) {
                postApi(ruleForm.value, "/mosty-jcgl/zrs/addZrs").then(() => {
                    loading.value = false;
                    ElMessage.success("新增成功");
                    emits("changeAddVi", false);
                    ISbj.value = false
                    ruleForm.value = {}
                    ruleFormRef.value.resetFields()
                }).catch((err) => {
                    loading.value = false;
                })
            } else {
                postApi(ruleForm.value, "/mosty-jcgl/zrs/editZrs").then(() => {
                    loading.value = false;
                    ElMessage.success("修改成功");
                    ISbj.value = false
                    ruleForm.value = {}
                    emits("changeAddVi", false);
                    ruleFormRef.value.resetFields()
                }).catch((err) => {
                    loading.value = false;
                })
            }
        } else {
            ElMessage.warning('请输入必填项！！！')
        }
    })
}
</script>
<style lang="scss" scoped>
.top-btn {
    margin: 10px;
}

.btn-clas {
    padding: 10px 25px;
}

.config {
    background-color: #fff;
    margin: 10px;
    padding: 20px;
}

.box-big {
    display: flex;
    margin: 20px;
}

.box-left {
    width: 840px;
    margin: 0 auto;
    padding: 20px;
    height: 71vh;
}

.top-word {
    display: flex;
    justify-content: space-between;
}


::v-deep .el-radio.is-bordered.is-checked {
    background-color: var(--el-color-primary) !important;
    color: #fff !important;
}

::v-deep .el-radio__input.is-checked+.el-radio__label {
    color: #fff !important;
}

::v-deep .el-radio__input.is-checked .el-radio__inner {
    border-color: #fff !important;
}

::v-deep .el-timeline-item__wrapper {
    width: 400px !important;
}

.time-top {
    display: flex;
    justify-content: space-between;
}

.name-box {
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: bold;
    font-size: 14px;
    color: #191919;
}

.lable-time {
    display: inline-block;
    padding: 0px 10px;
    border-radius: 2px 2px 2px 2px;
    color: #fff;
    margin: 0px 10px;
}

.gren {
    background: #07877E;
}

.reds {
    background-color: #E91717;
}

.yess {
    background: #EBD0A1;
}

.time-ri {
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: #191919;
}

.ldxm {
    font-weight: 400;
    font-size: 12px;
    margin: 10px;
}

::v-deep .el-card {
    background: #F0F3F4 !important;
    border-radius: 2px 2px 2px 2px !important;
}
</style>
