<!--
 * @Author: yanLu xgktv007@163.com
 * @Date: 2023-09-05 10:21:34
 * @LastEditors: mk 2403457699@qq.com
 * @LastEditTime: 2024-01-09 13:55:37
 * @Description: 事件转办表单
 * 
-->
<template>
    <div class="search">
        <el-form ref="ref_form5" :inline="false" :model="formData" :rules="dataRule">
            <el-form-item label="事件分类" label-width="150px" :class="{ 'form-item': source === 'visiual' }"
                prop="categoryList">
                <div :class="{ 'visiual-form': source === 'visiual' }">
                    <el-cascader class="cell-width-2" ref="myCascader" v-model.trim="selCategoryArray" :key="iscascaderShow"
                        :options="casOptions" :props="optionProps" :show-all-levels="false" clearable
                        @change="handleChangeCate"></el-cascader>
                </div>
            </el-form-item>
            <el-form-item label="处理部门" prop="deptId" label-width="150px" :class="{ 'form-item': source === 'visiual' }">
                <el-cascader class="cell-width-2" ref="agencyIdArray" v-model.trim="agencyIdArray" :options="orgOptions"
                    :props="orgOptionProps" :show-all-levels="false" @change="handleChangeAgency"></el-cascader>
            </el-form-item>
            <el-form-item label="转办意见" prop="content" label-width="150px" :class="{ 'form-item': source === 'visiual' }"
                style="display: block">
                <div :class="{ 'visiual-form': source === 'visiual' }">
                    <el-input class="cell-width-area" type="textarea" maxlength="500" show-word-limit :rows="5"
                        placeholder="请输入转办意见，不超过500字" v-model.trim="formData.content"></el-input>
                </div>
            </el-form-item>
            <el-form-item style="display: block" label="附件" label-width="150px" prop="attach">
                <el-upload :headers="$getElUploadHeaders()" class="upload-demo" :action="uploadUlr"
                    accept=".doc,.pdf,.xls,.docx,.xlsx,.jpg,.png,.jpeg,.bmp,.mp4,.wma,.m4a,.mp3"
                    :on-success="handleFileSuccess" :on-remove="handleFileRemove" :on-preview="handleFileDownload"
                    :limit="3" :before-upload="beforeUpload" :file-list="fileList">
                    <el-button size="small" :disabled="fileList.length === 3" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">支持图片、word、pdf</div>
                </el-upload>
            </el-form-item>
            <el-form-item label="办结时限" prop="timeLimit" label-width="150px" :class="{ 'form-item': source === 'visiual' }"
                style="display: block">
                <div :class="{ 'visiual-form': source === 'visiual' }">
                    <el-date-picker v-model.trim="formData.timeLimit" class="cell-width-1" type="datetime" placeholder="办结时限"
                        value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { Loading } from "element-ui"; // 引入Loading服务
import { requestPost } from "@/js/dai/request";
let loading; // 加载动画
export default {
    data() {
        return {
            btnDisable: false,
            formData: {
                operationType: "5", //处理方式[0:已回复 5、指派  6、完成并回复]
                content: "",//转办意见
                timeLimit: "",//办结时限
                categoryId: "",//事件分类
                deptId: "", //指派部门
                deptName: "",
                categoryList: [],
                files: [] //附件
            },
            orgOptions: [],
            orgOptionProps: {
                multiple: false,
                value: 'agencyId',
                label: 'agencyName',
                children: 'subAgencyList',
                checkStrictly: true
            },
            agencyIdArray: [],
            status: false,
            okflag: false,
            eventDetailCopy: {},
            selCategoryArray: [],
            casOptions: [],
            fileList: [],
            uploadUlr: window.SITE_CONFIG["apiURL"] + "/oss/file/uploadvariedfile",
            iscascaderShow: 0,
            optionProps: {
                multiple: false,
                value: "id",
                label: "categoryName",
                children: "children",
                checkStrictly: true
            },
            dataRule: {
                content: [
                    { required: true, message: "回复内容不能为空", trigger: "blur" },
                ],
                categoryId: [
                    { required: true, message: "事件分类不能为空", trigger: "blur" },
                ],
                deptId: [
                    { required: true, message: "处理部门不能为空", trigger: "blur" },
                ],
                timeLimit: [
                    { required: true, message: "办结时限不能为空", trigger: "blur" },
                ],
                categoryList: [
                    { required: true, message: '事件分类不能为空', trigger: 'blur' },
                ]
            },
            selCateObj: {
                id: ""
            },
        };
    },
    components: {},
    computed: {},
    props: {
        eventId: {
            type: String,
            default: "",
        },
        eventDetailData: {
            type: Object,
            default() {
                return {};
            },
        },
        source: {
            //展示来源：manage  管理平台    visiual  可视化平台
            type: String,
            default: "manage",
        },
    },
    created() {

    },
    async mounted() {
        const { user } = this.$store.state;
        this.agencyId = user.agencyId;
        this.getOrgTreeList();
        this.getCategoryList();
        if (this.eventId) {
            this.eventDetailCopy = JSON.parse(JSON.stringify(this.eventDetailData));
            // 这一步接收到eventDetailCopy在这里回填
            if (this.eventDetailCopy.parentCategoryId && this.eventDetailCopy.categoryId) {
                this.selCategoryArray = this.eventDetailCopy.parentCategoryId.split(",");
                this.selCategoryArray.push(this.eventDetailCopy.categoryId);
                this.handleChangeCate(this.selCategoryArray)
            }
        }
    },
    methods: {
        //组织机构树
        async getOrgTreeList() {
            const url = "/gov/org/customeragency/agencyGridDepttree"
            let params = {
                agencyId: this.agencyId,
                purpose: "query"
            }
            const { data, code, msg } = await requestPost(url, params)
            if (code === 0) {
                this.orgOptions = []
                this.orgOptions.push(data)
            } else {
                this.$message.error(msg)
            }
        },
        async getCategoryList() {
            const url = '/governance/icEvent/getCategoryTree';
            let params = {};
            const { data, code, msg } = await requestPost(url, params);
            if (code === 0) {
                let treeDataNew = this.deepTree(data, "children");
                ++this.iscascaderShow;
                this.casOptions = [];
                this.casOptions = treeDataNew;
            } else {
                this.$message.error(msg);
            }
            if (this.eventDetailCopy.parentCategoryId) {
                const pids = this.eventDetailCopy.parentCategoryId.split(',');
                pids.push(this.eventDetailCopy.categoryId);
                let nodes = this.casOptions;
                for (let i = 0; i < pids.length; i++) {
                    nodes = this.buildNode(nodes, pids[i])
                }
                if (nodes) {
                    this.formData.categoryList.push(nodes)
                    this.selCateObj = nodes
                }
            }
        },
        buildNode(nodes, treeId) {
            for (let i = 0; i < nodes.length; i++) {
                if (nodes[i].id === treeId) {
                    if (nodes[i].children) {
                        return nodes[i].children
                    } else {
                        return nodes[i]
                    }
                }
            }
        },
        handleChangeAgency(val) {
            let obj = this.$refs["agencyIdArray"].getCheckedNodes()[0].data
            if (obj) {
                this.formData.orgType = obj.level === 'grid' ? 'grid' : 'agency'
                this.formData.deptId = obj.agencyId
                this.formData.deptName = obj.agencyName
            } else {
                this.form.orgType = ''
                this.form.orgId = ''
            }
        },
        handleChangeCate() {
            if (this.selCateObj = this.$refs["myCascader"].getCheckedNodes()[0]) {
                this.selCateObj = this.$refs["myCascader"].getCheckedNodes()[0].data
                this.formData.categoryList = this.selCateObj
                this.formData.categoryId = this.selCateObj.id
            } else {
                this.selCateObj = {}
            }
        },
        //重构树，去除网格
        deepTree(arr, children) {
            if (Array.isArray(arr) && arr.length > 0) {
                return arr.map((item) => {
                    return {
                        ...item,
                        [children]:
                            (item[children] &&
                                item[children].length > 0 &&
                                this.deepTree(item[children], children)) ||
                            null,
                    };
                });
            }
        },
        async getReplayInfo() {
            this.okflag = false;
            this.$refs["ref_form5"].validate((valid, messageObj) => {
                if (!valid) {
                    app.util.validateRule(messageObj);
                } else {
                    if (!this.selCateObj || !this.selCateObj.id) {
                        this.$message.error("请选择事件分类");
                        return false;
                    }
                    if (this.fileList) {
                        this.formData.files = this.fileList
                    }
                    this.operationType = '5'
                    this.formData.status = "processing";
                    this.formData.categoryId = this.selCateObj.id;
                    this.formData.categoryList = [];
                    this.formData.categoryList.push(this.selCateObj);
                    this.okflag = true;
                }
            });
        },
        resetData() {
            this.agencyIdArray = []
        },
        beforeUpload(file) {
            const array = file.name.split(".");
            const extension = array[array.length - 1];
            const formatarray = [
                "jpg",
                "png",
                "jpeg",
                "bmp",
                "mp4",
                "wma",
                "m4a",
                "mp3",
                "doc",
                "docx",
                "xls",
                "xlsx",
                "pdf",
            ];
            if (formatarray.indexOf(extension) === -1) {
                this.$message.error("只支持图片、word、pdf");
                return false;
            }
        },
        handleFileRemove(file) {
            if (file && file.status === "success") {
                this.fileList.splice(
                    this.fileList.findIndex((item) => item.uid === file.uid),
                    1
                );
            }
        },
        handleFileSuccess(res, file) {
            if (res.code === 0 && res.msg === "success") {
                const array = file.name.split(".");
                const fileType = array[array.length - 1];
                const picArray = ["jpg", "png", "jpeg", "bmp"];
                const videoarray = ["mp4", "wma", "m4a"];
                const docArray = ["doc", "docx", "xls", "xlsx", "pdf"];
                const mp3Array = ["mp3"];

                if (picArray.indexOf(fileType) > -1) {
                    file.attachmentFormat = "image";
                } else if (videoarray.indexOf(fileType) > -1) {
                    file.attachmentFormat = "video";
                } else if (docArray.indexOf(fileType) > -1) {
                    file.attachmentFormat = "doc";
                } else if (mp3Array.indexOf(fileType) > -1) {
                    file.attachmentFormat = "voice";
                }

                file.url = res.data.url;
                file.type = fileType;

                file.attachmentName = file.name;
                file.attachmentType = file.type;
                file.attachmentUrl = file.url;

                this.fileList.push(file);
            } else this.$message.error(res.msg);
        },
        //下载
        handleFileDownload(file) {
            var a = document.createElement("a");
            var event = new MouseEvent("click");
            a.download = file.name;
            a.href = file.url;
            a.dispatchEvent(event);
        },
        // 开启加载动画
        startLoading() {
            loading = Loading.service({
                lock: true, // 是否锁定
                text: "正在加载……", // 加载中需要显示的文字
                background: "rgba(0,0,0,.7)", // 背景颜色
            });
        },
        // 结束加载动画
        endLoading() {
            // clearTimeout(timer);
            if (loading) {
                loading.close();
            }
        },
    },
};
</script>

<style lang='scss' scoped>
@import "@/assets/scss/modules/visual/a_customize.scss";
@import "@/assets/scss/modules/shequzhili/event-info.scss";

.el-dialog__body {
    padding: 0 10px 20px !important;
}
</style>
