<script lang="ts">
import { Component } 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 LeaderService from "@/service/leader.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 LeadershipStructure extends BaseRecordComponent<any> {
    public tableService = new LeaderService();

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

    public showProtable = false;

    public tableColumn = [] as any;

    public subTableColumn = [] as any;

    public showUpdate = false;

    public updateParams = {
        members: []
    } as any;

    public subUpdateParams = {} as any;

    public selectData = [];

    public subSelectData = [];

    public isReadonly = false;

    public subIsReadonly = false;

    public subUpdateActions = [] as any;

    public fileList = [] as any;

    public showFile = false;
    public currentUrl = null;

    public subShowUpdate = false;

    public subTitle = '成员信息'

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

    public showDetailsTable = false;

    public showFileModal = false;

    public showFileList = [] 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>[] = [{
        name: "机构名称",
        key: "name",
        type: "text",
    }, {
        name: "负责人",
        key: "chargeUserId",
        type: "select",
        datas: this.$store.state.userList,
    }, {
        name: "成立时间",
        key: "establishTime",
        type: "date",
        format: "yyyy-MM-dd"
    }];

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




    public updateActions = [] as any;

    public updateOptions: FormOption<BtnOption>[] = [] as any;
    public buildUpdateForm() {
        this.updateOptions = [{
            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: "duty",
            require: true,
            width: "100%",
            showError: false,
        },
        {
            name: "成立时间",
            type: "date",
            key: "establishTime",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            format: "yyyy-MM-dd"

        },
        {
            name: "负责人",
            type: "select",
            key: "chargeUserId",
            format: 'chargeUserName',
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.userList,
        },
        {
            name: "单位名称",
            key: "orgId",
            format: "orgName",
            type: "treeSelect",
            width: "calc(50% - 20px)",
            require: true,
            expandLevel: Infinity,
            showError: false,
            datas: this.$store.state.deptTreeList
        },
        {
            name: "审批人",
            type: "select",
            key: "approveUserId",
            format: 'approveUserName',
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.userList,
        },
        {
            name: "相关附件",
            key: "resourceId",
            ref: "file",
            type: "upload",
            width: "calc(50% - 20px)",
            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.isReadonly ? "" : "请上传.pdf,.png,.jpg,.doc.docx,.xls,.xlsx格式文件",
            fileList: this.fileList,
            btn: [{
                name: "上传附件",
                value: "upload",
                hide: this.isReadonly,
                size: "small",
                type: "primary"
            }]
        }
        ];
        this.updateActions = [{
            name: "取消",
            value: "cancel"
        }, {
            name: "保存并继续添加",
            value: "saveAndContinue",
            type: "primary",
            hide: this.updateParams.id
        }, {
            name: "保存",
            value: "save",
            type: "primary"
        }];
    }

    public subUpdateOptions: FormOption<BtnOption>[] = []
    public buildSubForm() {
        this.subUpdateOptions = [{
            name: "姓名",
            type: "select",
            key: "userId",
            format: "userName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.userList,
        }, {
            name: "手机号码",
            type: "text",
            key: "phone",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            rules: [
                { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', }
            ]

        }, {
            name: "单位",
            key: "deptId",
            format: "deptName",
            type: "treeSelect",
            width: "calc(50% - 20px)",
            require: true,
            expandLevel: Infinity,
            showError: false,
            datas: this.$store.state.deptTreeList
        }, {
            name: "职务",
            type: "text",
            key: "duty",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        }, {
            name: "职责描述",
            type: "textarea",
            key: "description",
            require: true,
            width: "100%",
            showError: false,
        },]
        this.subUpdateActions = [{
            name: "取消",
            value: "cancel"
        }, {
            name: "保存并继续添加",
            value: "saveAndContinue",
            type: "primary",
            hide: this.subUpdateParams.index
        }, {
            name: "保存",
            value: "save",
            type: "primary"
        }];
    }

    created() {
        //
    }


    public buildTable() {
        this.tableColumn.push({ name: '机构名称', key: "name", width: "200px" });
        this.tableColumn.push({ name: '机构负责人', key: "chargeUserName", width: "120px" });
        this.tableColumn.push({
            name: '成员信息', key: "memberNumber", width: "100px", render: (data) => {
                return "<span class='link memberNumber'>" + (data.memberNumber ? data.memberNumber : 0) + "</span>"
            }
        });
        this.tableColumn.push({ name: '机构主要职责', key: "duty", width: "250px", showTip: true, });
        this.tableColumn.push({ name: '单位名称', key: "orgName", width: "150px", });
        this.tableColumn.push({
            name: '附件', width: "300px", key: "resourceName", showTip: true, render: (data) => {
                if (data.resourceName) {
                    return `<span class="link resourceName">${data.resourceName}</span>`
                }
            }
        });
        this.tableColumn.push({ name: '成立时间', key: "establishTime" });
        this.tableColumn.push({ name: '审批人', key: "approveUserName" });


        this.subTableColumn.push({ name: '序号', key: "index", });
        this.subTableColumn.push({ name: '姓名', key: "userName", });
        this.subTableColumn.push({ name: '单位', key: "deptName", });
        this.subTableColumn.push({ name: '职务', key: "duty", });
        this.subTableColumn.push({ name: '联系方式', key: "phone",width:"130px" });
        this.subTableColumn.push({ name: '职责描述', key: "description", width: "250px", showTip: true, });
    }

    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.buildUpdateForm()
            this.isReadonly = false
            this.subIsReadonly = false
            this.updateParams = {
                members: []
            } as any;
            this.fileList = [] as any;
            this.getFormNumber()
            //清除附件缓存数据
            this.clearFileListMethod()
        }
    }
    //获取机构编号
    public getFormNumber() {
        this.tableService.getNumber({}).then(res => {
            this.updateParams.number = res.data
            this.buildUpdateForm()
            if (this.showUpdate === false) {
                this.showUpdate = 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;
        this.getTableData()
    }

    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.updateParams.resourceId = resourceId.join(",")
            this.updateParams.resourceName = resourceName.join(",")
        } else {
            this.updateParams.resourceId = ''
            this.updateParams.resourceName = ''
        }
        // 新增
        this.updateParams.chargeUserName = this.$store.getters.user_map[this.updateParams.chargeUserId];
        this.updateParams.approveUserName = this.$store.getters.user_map[this.updateParams.approveUserId];
        this.updateParams.orgName = this.$store.getters.dept_map[this.updateParams.orgId]
        this.updateParams.memberNumber = this.updateParams.members.length
        this.tableService.addOrUpdate(this.updateParams, this.updateParams.id ? false : true).then((res) => {
            this.$message.success(!this.updateParams.id ? "新增成功！" : "编辑成功！");
            this.updateParams = {
                members: [],
            } as any
            this.showUpdate = !!goOn;
            this.getTableData();
            //清除附件缓存数据
            this.clearFileListMethod()
            if (goOn === true) {
                this.getFormNumber()
            }
        })
    }

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

    public handleClose() {
        this.showUpdate = 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) {
        this.subSelectData = data;
    }

    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 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 showModal(row, isReadonly) {
        if (isReadonly) {
            this.isReadonly = true
            this.subIsReadonly = true
        } else {
            this.isReadonly = false
            this.subIsReadonly = false
        }

        this.tableService.getListDetail({ id: row.id }).then((res: any) => {
            if (res.code === 200) {
                this.updateParams = res.data
                this.updateParams.members.forEach((item, index) => {
                    item.index = index + 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.updateParams.resourceId = ''
                        this.buildUpdateForm()
                    })
                }
                this.buildUpdateForm()
                this.showUpdate = true
            } else {
                this.$message.error(res.msg);
            }

        })
    }

    public showDetails(el, row) {
        const isTarget = el.target.classList.contains("memberNumber");
        const isTargetResourceName = el.target.classList.contains("resourceName");
        if (isTarget) {
            this.tableService.getListDetail({ id: row.id }).then((res: any) => {
                if (res.code === 200) {
                    this.currentDetailsTableData.datas = res.data.members
                    this.currentDetailsTableData.datas.forEach((item, index) => {
                        item.index = index + 1;
                    });
                    this.showDetailsTable = true
                } else {
                    this.$message.error(res.msg);
                }

            })
        }

        if (isTargetResourceName) {
            if (row.resourceId) {
                this.tableService.getFileUrls({ ids: row.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 handleTableClose() {
        this.showDetailsTable = false
    }

    public subCallback(data) {
        if (data.value === "add") {
            this.subUpdateParams = {} as any;
            this.buildSubForm()
            this.subShowUpdate = true
        } else if (data.value === "cancel") {
            this.showUpdate = false;
            //清除附件缓存数据
            this.clearFileListMethod()
        } else if (data && data.value.indexOf("save") >= 0) {
            this.doSave(data.value !== "save")
        } else if (data && data.value === 'delete') {
            // 批量删除步骤
            this.deleteSubData(this.subSelectData.map((itm: any) => itm.index - 1))
        }
    }

    public triCallback(data) {
        if (data.value === "cancel") {
            this.subShowUpdate = false
        } else if (data && data.value.indexOf("save") >= 0) {
            this.doSubSave(data.value !== "save")
        }
    }

    public doSubSave(goOn) {
        // 如果是新增步骤
        if (this.subShowUpdate) {
            // 新增
            this.subUpdateParams.userName = this.$store.getters.user_map[this.subUpdateParams.userId]
            this.subUpdateParams.deptName = this.$store.getters.dept_map[this.subUpdateParams.deptId]
            if (!this.subUpdateParams.index) {
                this.subUpdateParams.index = this.updateParams.members.length + 1;
                this.updateParams.members.push(this.subUpdateParams);
            } else {
                this.updateParams.members.splice(this.updateParams.members.findIndex(item => item.index === this.subUpdateParams.index), 1, this.subUpdateParams)
            }
            this.subUpdateParams = {} as any;
            this.subShowUpdate = !!goOn;
            return
        }
    }

    //查看或者修改
    public showSubModal(row, isReadonly) {
        if (isReadonly) {
            this.subIsReadonly = true
            this.subUpdateParams = JSON.parse(JSON.stringify(row))
        } else {
            this.subIsReadonly = false
            this.subUpdateParams = JSON.parse(JSON.stringify(row))
        }
        this.subShowUpdate = true
        this.buildSubForm()
    }

    //删除成员
    public deleteSubData(indexs) {
        if (indexs.length === 0) {
            this.$message.warning("请选择要删除的数据！")
        } else {
            this.$confirm('确认删除所选数据', '确认数据', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                for (let i = this.updateParams.members.length - 1; i >= 0; i--) {
                    if (indexs.includes(i)) {
                        this.updateParams.members.splice(i, 1)
                    }
                }
                this.updateParams.members.forEach((item, index) => {
                    item.index = index + 1;
                });
                this.$message.success("删除成功")
            }).catch(() => {
                //
            });
        }
    }

    public changes(data, item) {
        //
    }


    //预览附件
    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")
        }
    }

    /**
     * 下载附件
     * @param url 下载url
     * @param file 文件信息
     */
    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.updateOptions.find(item => item.key === "resourceId") as any;
        option.fileList = [];
    }
}
</script>
<style lang="scss" scoped src="../common.component.scss"></style>
<style lang="scss" >
.el-tooltip__popper {
    max-width: 400px;
    letter-spacing: 2px;
    border-radius: 4px;


}

.el-tooltip__popper.is-dark {
    background: #000000;
    opacity: 0.8;
    font-size: 12px;
    font-weight: 400;
    padding: 10px;
}
</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>