
<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 safeCardService from "@/service/safeCard.service";
import FormOption from "hbt-common/models/formOptions";
import BtnOption from "hbt-common/models/btnOptions";
import AreaService from '@/service/area.service';
import CommonService from '@/service/common.service'
import { Base64 } from 'js-base64';

@Component({
    template,
    components: {
        FormComponent,
        TableComponent,
    },
})
export default class SafeCard extends BaseRecordComponent<any> {
    public tableService = new safeCardService();
    public areaService = new AreaService();
    public commonService = new CommonService();

    public params = {
        areaId: null,
        promiserId: null,
    } as any;
    public showProtable = false;

    public tableColumn = [] as any;

    public subUpdateParams = {} as any;

    public updateParams = {} as any;

    public areaList = [] as any;

    public unitList = [] as any;


    public selectData = [];

    public subIsReadonly = false;

    public isReadonly = false;

    public fileList = [] as any;

    public showFile = false;
    public currentUrl = null;

    public subShowUpdate = false;

    public showUpdate = false;

    public setpsOptions = [] as any;

    public showFileModal = false;

    public showFileList = [] as any;

    public labelWidth = "130px";

    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: "areaName",
        type: "text",
    }, {
        name: "承诺人",
        key: "promiserId",
        type: "select",
        datas: this.$store.state.userList,
    }];

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

    public updateActions = [] as any;


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

    public updateStepsOptions: 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: "select",
            key: "areaId",
            format: "areaName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.areaList
        },
        {
            name: "岗位名称",
            type: "select",
            key: "postCode",
            format: "postName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.postList
        },
        {
            name: "承诺人",
            type: "select",
            key: "promiserId",
            format: "promiserName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.userList,
        },
        {
            name: "上级领导",
            type: "select",
            key: "leaderId",
            format: "leaderName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.userList,
        },
        {
            name: "承诺人联系方式",
            type: "text",
            key: "promiserPhone",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            labelWidth: "130px",
            rules: [
                { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', }
            ]
        },
        {
            name: "承诺事项",
            type: "textarea",
            key: "content",
            require: true,
            width: "100%",
            showError: false,
        },
        {
            name: "承诺时间",
            type: "date",
            key: "promiseTime",
            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"
            }]
        },
        ];
        this.updateActions = [{
            name: "取消",
            value: "cancel"
        }, {
            name: "保存并继续添加",
            value: "saveAndContinue",
            type: "primary",
            hide: this.subUpdateParams.id
        }, {
            name: "保存",
            value: "save",
            type: "primary"
        }];
    }


    @Watch("$store.state.deptList", { immediate: true, deep: true })
    onChanges() {
        this.loadAreaData()
    }

    created() {
    }
    // 加载区域列表
    public loadAreaData() {
        this.areaService.selectByPage({ pageSize: 1000 }).then((res: any) => {
            this.areaList = res.data.datas.map(item => {
                return {
                    name: item.name,
                    value: item.id,
                    analRiskLevel: item.analRiskLevel ? item.analRiskLevel : null,
                }
            });
            this.buildUpdateForm()
        })
    }

    public buildTable() {
        this.tableColumn.push({ name: '区域名称', key: "areaName", });
        this.tableColumn.push({ name: '承诺人', key: "promiserName", });
        this.tableColumn.push({ name: '岗位', key: "postName", });
        this.tableColumn.push({ name: '承诺事项', key: "content", showTip: true, });
        this.tableColumn.push({ name: '上级领导', key: "leaderName", width: "130px" });
        this.tableColumn.push({ name: '承诺日期', key: "promiseTime", width: "130px" });
        this.tableColumn.push({
            name: '附件', key: "resourceName", showTip: true, width: "300px", render: (data) => {
                if (data.resourceName) {
                    return `<span class="link">${data.resourceName}</span>`
                }
            }
        });
    }

    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.subIsReadonly = false;
            this.fileList = [] as any;
            //清除文件缓存
            this.clearFileListMethod()
            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;
        this.getTableData()
    }

    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.userId === item.userId);
                if (!find) {
                    (this.$refs.multipleTable as any).toggleRowSelection(item);
                }
            })
        }
    }

    public handleSelectionChange(data) {
        this.selectData = 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 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(",")
        }
        this.subUpdateParams.postName = this.$store.getters.post_map[this.subUpdateParams.postCode]
        this.subUpdateParams.promiserName = this.$store.getters.user_map[this.subUpdateParams.promiserId]
        this.subUpdateParams.leaderName = this.$store.getters.user_map[this.subUpdateParams.leaderId]

        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
                this.subUpdateParams.postCode = parseInt(res.data.postCode)
                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 stringChangeArray(data) {
        if (data) {
            return data.split(",").map((item) => parseInt(item))
        }
    }

    public changes(data, item) {
        //
    }

    //处理任务
    public rowCallback(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")
        }
    }

    /**
     * 下载附件
     * @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.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>