
<script lang="ts">
import { Component, Watch } from 'vue-property-decorator';
import template from './common.component.html'
import BaseRecordComponent from "hbt-common/components/common/baseRecord.component.vue";
import FormComponent from "hbt-common/components/common/form.component.vue";
import TableComponent from "hbt-common/components/common/table.component.vue";
import ManagementSystemService from "@/service/managementSystem.service";
import FormOption from "hbt-common/models/formOptions";
import BtnOption from "hbt-common/models/btnOptions";
import { Base64 } from 'js-base64';

@Component({
    template,
    components: {
        FormComponent,
        TableComponent,
    },
})
export default class ManagementSystem extends BaseRecordComponent<any> {
    public tableService = new ManagementSystemService();

    public params = {
        areaId: null,
        unitId: null,
    } as any;

    public showProtable = false;

    public tableColumn = [] as any;

    public subTableColumn = [] as any;

    public showUpdate = false;

    public updateParams = {} as any;

    public subUpdateParams = {} as any;

    public selectData = [];

    public subIsReadonly = false;

    public isReadonly = false;

    public showDetailsTable = false;

    public subTitle = null;

    public currentDetailsTableData = { datas: [] } as any;

    public showFileModal = false;

    public showFileList = [] as any;

    public fileList = [] as any;

    public showFile = false;
    public currentUrl = null;

    public subShowUpdate = false;

    public subUpdateActions = [] as any;

    public formActions = [{
        name: "查询",
        value: "search",
        icon: "el-icon-search",
        type: "primary"
    }, {
        name: "清空",
        icon: "el-icon-tickets",
        value: "reset"
    }];

    public tableActions = [{
        name: "添加",
        value: "add",
        icon: "el-icon-plus",
        type: "primary"
    }, {
        name: "批量删除",
        value: "delete",
        plain: true,
        icon: "el-icon-delete",
        type: "danger"
    }];

    public footerActions = [{
        name: "选择全部",
        value: "selectAll",
        type: "primary"
    }, {
        name: "反向选择",
        value: "reverse"
    }];

    public formOptions: FormOption<BtnOption>[] = [] as any;

    public buildFormOptions() {
        this.formOptions = [{
            name: "制度名称",
            key: "name",
            type: "text",
        }, {
            name: "适用部门",
            key: "suitDeptId",
            type: "treeSelect",
            datas: this.$store.state.deptTreeList,
            expandLevel: Infinity,
            width: "280px"
        }, {
            name: "发布时间",
            key: "publishTime",
            type: "date",
            format: "yyyy-MM-dd"
        }];
    }

    public subActions = [{
        name: "取消",
        value: "cancel"
    }];


    public updateActions = [] as any;

    public updateOptions: FormOption<BtnOption>[] = [] as any;

    public subUpdateOptions: FormOption<BtnOption>[] = [] as any;
    public buildUpdateForm() {
        this.subUpdateOptions = [{
            name: "制度编号",
            type: "text",
            key: "number",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            disable: true,
        },
        {
            name: "制度名称",
            type: "text",
            key: "name",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "内容摘要",
            type: "textarea",
            key: "content",
            require: true,
            width: "100%",
            showError: false,
        },
        {
            name: "适用部门",
            key: "suitDeptId",
            format: "suitDeptName",
            type: "treeSelect",
            width: "calc(50% - 20px)",
            require: true,
            expandLevel: Infinity,
            showError: false,
            datas: this.$store.state.deptTreeList
        },
        {
            name: "发布时间",
            type: "date",
            key: "publishTime",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            format: "yyyy-MM-dd"
        },
        {
            name: "编制人",
            type: "select",
            key: "compileUserId",
            format: "compileUserName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.userList,
        },
        {
            name: "编制时间",
            type: "date",
            key: "compileTime",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            format: "yyyy-MM-dd"
        },
        {
            name: "附件",
            key: "resourceId",
            ref: "file",
            type: "upload",
            width: "100%",
            showError: false,
            onSucess: this.onSuccess,
            onMove: this.onRemove,
            onPreview: this.onPreview,
            autoUpload: true,
            accept: "image/png, image/jpeg,.doc,.docx,.xls,.xlsx,.pdf",
            listType: "text",
            tip: this.subIsReadonly ? "" : "请上传.pdf,.png,.jpg,.doc.docx,.xls,.xlsx格式文件",
            fileList: this.fileList,
            btn: [{
                name: "上传附件",
                value: "upload",
                hide: this.subIsReadonly,
                size: "small",
                type: "primary"
            }]
        }, {
            name: "发布部门",
            type: "treeSelect",
            key: "publishDeptId",
            format: "publishDeptName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            expandLevel: Infinity,
            datas: this.$store.state.deptTreeList
        }, {
            name: "状态",
            type: "select",
            key: "status",
            format: "statusName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: [{
                name: "在用",
                value: 1
            }, {
                name: "废除",
                value: 0
            }]
        },
        ];
        this.subUpdateActions = [{
            name: "取消",
            value: "cancel"
        }, {
            name: "保存并继续添加",
            value: "saveAndContinue",
            type: "primary",
            hide: this.subUpdateParams.id
        }, {
            name: "保存",
            value: "save",
            type: "primary"
        }];
    }



    created() {
        //
        this.buildFormOptions();
    }
    @Watch("$store.state.deptTreeList", { immediate: true, deep: true })
    onChanges() {
        this.buildFormOptions();
    }



    public buildTable() {
        this.tableColumn.push({ name: '制度名称', key: "name", width: "200px" });
        this.tableColumn.push({ name: '适用部门', key: "suitDeptName", width: "200px" });
        this.tableColumn.push({ name: '内容摘要', key: "content", width: "150px", showTip: true, });
        this.tableColumn.push({ name: '发布部门', key: "publishDeptName", width: "100px", });
        this.tableColumn.push({ name: '发布时间', key: "publishTime", width: "150px", });
        this.tableColumn.push({
            name: '附件', width: "300px", key: "resourceName", showTip: true, render: (data) => {
                if (data.resourceName) {
                    return `<span class="link">${data.resourceName}</span>`
                }
            }
        });
        this.tableColumn.push({
            name: '状态', key: "status", width: "80px", render: (data) => {
                if (data.status === 1) {
                    return `<span class="color_1">${'在用'}</span>`
                } else if (data.status === 0) {
                    return `<span class="color_0">${'废除'}</span>`
                }
            }
        });
        this.tableColumn.push({ name: '编制人', key: "compileUserName" });
        this.tableColumn.push({ name: '编制时间', key: "compileTime", width: "110px" });
    }

    public callback(data, type) {
        if (type) {
            if (type === 'pageSize' || type === 'pageNum') {
                this.params[type] = data;
            }
            this.getTableData();
            return
        }
        // 查询
        if (data.value === "search") {
            this.getTableData()
            // 重置
        } else if (data.value === "reset") {
            this.reset()
            // 反选
        } else if (data.value === "reverse") {
            this.toggleAll()
            // 全选
        } else if (data.value === "selectAll") {
            this.selectAll()
        } else if (data.value === "delete") {
            this.deleteData(this.selectData.map((item: any) => item.id))
        } else if (data.value === 'add') {
            this.subUpdateParams = {} as any;
            this.fileList = [] as any;
            this.subIsReadonly = false;
            this.getNumber()
        }
    }
    //获取制度编号
    public getNumber() {
        this.tableService.getNumber({}).then((res: any) => {
            if (res.code === 200) {
                this.subUpdateParams.number = res.data
            } else {
                this.$message.error(res.msg)
            }
            this.buildUpdateForm()
            if (this.subShowUpdate === false) {
                this.subShowUpdate = true
            }
        })
    }

    // 分页数据
    public getTableData() {
        this.tableService.selectByPage(this.params).then(res => {
            this.tableData = res.data as any;
        })
    }
    // 重置数据
    public reset() {
        this.params = {
            pageNum: 1,
            pageSize: 20,
        } as any;
    }

    public showUpdateModel(id) {
        this.subShowUpdate = true
    }

    public handleClose() {
        this.subShowUpdate = false;
        //清除附件缓存数据
        this.clearFileListMethod();
    }


    public toggleAll() {
        this.tableData.datas.forEach((item, index) => {
            (this.$refs.multipleTable as any).toggleRowSelection(item);
        })
    }
    public selectAll() {
        if (!this.selectData.length) {
            this.toggleAll()
        } else {
            this.tableData.datas.forEach((item, index) => {
                const find = this.selectData.find((data: any) => data.id === item.id);
                if (!find) {
                    (this.$refs.multipleTable as any).toggleRowSelection(item);
                }
            })
        }
    }

    public handleSelectionChange(data) {
        this.selectData = data;
    }


    public handleSubSelectionChange(data) {
        //
    }

    public onSuccess(res, file, fileList) {
        if (res.code === 200) {
            this.fileList.push({
                name: res.data.originalName,
                url: res.data.url,
                type: res.data.type,
                id: res.data.id
            })
        } else {
            this.$message.error(res.msg);
        }

    }

    public onRemove(file, fileList) {
        this.fileList.splice(this.fileList.findIndex(item => item.id === file.id), 1)
    }

    public onPreview(file) {
        if (file.type.indexOf("png") >= 0 || file.type.indexOf("jp") >= 0) {
            this.currentUrl = file.url;
            this.showFile = true;
        } else {
            window.open(file.url, "_blank")
        }
    }

    public subCallback(data) {
        //
    }

    public handleTableClose() {
        //
    }

    public triCallback(data) {
        if (data.value === "cancel") {
            this.subShowUpdate = false;
            //清除附件缓存数据
            this.clearFileListMethod();
        } else if (data && data.value.indexOf("save") >= 0) {
            this.doSave(data.value !== "save")
        }
    }

    public doSave(goOn?) {
        // 新增清单
        if (this.fileList.length > 0) {
            let resourceId = this.fileList.map((item) => {
                return item.id
            })
            let resourceName = this.fileList.map((item) => {
                return item.name
            })
            this.subUpdateParams.resourceId = resourceId.join(",")
            this.subUpdateParams.resourceName = resourceName.join(",")
        } else {
            this.subUpdateParams.resourceId = '';
            this.subUpdateParams.resourceName = '';
        }
        this.subUpdateParams.compileUserName = this.$store.getters.user_map[this.subUpdateParams.compileUserId];
        this.subUpdateParams.publishDeptName = this.$store.getters.dept_map[this.subUpdateParams.publishDeptId]
        this.subUpdateParams.suitDeptName = this.$store.getters.dept_map[this.subUpdateParams.suitDeptId]
        this.tableService.addOrUpdate(this.subUpdateParams, this.subUpdateParams.id ? false : true).then((res) => {
            this.$message.success(!this.subUpdateParams.id ? "新增成功！" : "编辑成功！");
            this.subUpdateParams = {} as any
            this.subShowUpdate = !!goOn;
            this.getTableData();
            //清除附件缓存数据
            this.clearFileListMethod();
            if (goOn === true) {
                this.getNumber()
            }

        })
    }

    public showModal(row, isReadonly) {
        if (isReadonly) {
            this.subIsReadonly = true

        } else {
            this.subIsReadonly = false
        }

        this.tableService.getListDetail({ id: row.id }).then((res: any) => {
            if (res.code === 200) {
                this.subUpdateParams = res.data
                if (isReadonly) {
                    this.subUpdateParams.statusName = res.data.status == 1 ? '在用' : '废除'
                }
                if (res.data.resourceId) {
                    this.tableService.getFileUrls({ ids: res.data.resourceId.split(",") }).then((files: any) => {
                        this.fileList = files.data.map(item => {
                            return {
                                name: item.originalName,
                                url: item.url,
                                type: item.type,
                                id: item.id
                            }
                        })
                        this.subUpdateParams.resourceId = ''
                        this.buildUpdateForm()
                    })
                }
                this.buildUpdateForm()
                this.subShowUpdate = true
            } else {
                this.$message.error(res.msg);
            }

        })
    }

    public changes(data, item) {
        //
    }

    //查看附件
    public showDetails(el, data) {
        const isTarget = el.target.classList.contains("link");
        if (isTarget) {
            if (data.resourceId) {
                this.tableService.getFileUrls({ ids: data.resourceId.split(",") }).then((files: any) => {
                    this.showFileList = files.data.map(item => {
                        return {
                            name: item.originalName,
                            url: item.url,
                            type: item.type,
                            id: item.id
                        }
                    })
                    this.showFileModal = true
                })
            }
        }
    }

    //预览附件
    public previewFile(url, file) {
        if (file.type.indexOf("png") >= 0 || file.type.indexOf("jp") >= 0) {
            this.currentUrl = file.url;
            this.showFile = true;
        } else {
            window.open('http://119.45.186.133:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(url)), "_blank")
        }
    }

    //下载附件
    public downLoadFile(url, file) {
        let DownUrl = url;
        fetch(DownUrl)
            .then((response) => response.blob())
            .then((res) => {
                //获取文件格式
                var index = DownUrl.lastIndexOf(".");
                //获取文件后缀判断文件格式
                var fileType = DownUrl.substr(index + 1);
                let blob = new Blob([res]);

                const href = window.URL.createObjectURL(blob); //创建下载的链接
                const downloadElement = document.createElement("a");
                downloadElement.href = href;
                downloadElement.target = "_blank";
                downloadElement.download = file.name;
                document.body.appendChild(downloadElement);
                downloadElement.click(); // 点击下载
                document.body.removeChild(downloadElement); // 下载完成移除元素
                window.URL.revokeObjectURL(href); // 释放掉blob对象
            });
    }
    /**
    * 清除附件数据
    */
    public clearFileListMethod() {
        this.fileList = [];
        const option = this.subUpdateOptions.find(item => item.key === "resourceId") as any;
        option.fileList = [];
    }

}
</script>
<style lang="scss" scoped src="../common.component.scss"></style>
<style  lang="scss" scoped>
.file-common-list {
    width: 100%;
    padding-bottom: 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
}

.column-cell-render {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.file-common-list:hover {
    .el-icon-document {
        color: #409eff
    }

    .file-list-name {
        color: #409eff
    }
}
</style>