<script lang="ts">
import { Component } from 'vue-property-decorator';
import template from './selfAssessment.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 SelfAssessmentService from "@/service/selfAssessment.service";
import FormOption from "hbt-common/models/formOptions";
import BtnOption from "hbt-common/models/btnOptions";
import Standard from '@/mock/selfAssessment';
import StandardContent from '@/mock/standard';
import moment from "moment";
import { Base64 } from 'js-base64';

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

    public params = {
        reviewerId: null,
        reviewerTime: null,
    } as any;

    public showProtable = false;

    public tableColumn = [] as any;

    public subTableColumn = [] as any;

    public showUpdate = false;

    public estimateStandard = [] as any;

    public account = JSON.parse(localStorage.getItem("account") as any);


    public updateParams = {
        reviewerId: this.account.userId,
        reviewTime: moment().format('YYYY-MM-DD'),
    } as any;

    public selectData = [];

    public isReadonly = false;


    public fileList = [] as any;

    public showFile = false;
    public currentUrl = null;

    public subShowUpdate = false;
    //否决项
    public checkReject = [] as any;

    public clickPointFlag = false;

    public StandardDetails = {} as any;

    //总分
    public total = 10;

    public showFileModal = false;

    public showFileList = [] as any;


    public paramTable = [{
        factorLevel: 1,
        flag: false
    }, {
        factorLevel: 2,
        flag: false
    }, {
        factorLevel: 3,
        flag: false
    }]

    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: "reviewTime",
        type: "date",
        format: "yyyy-MM-dd",
    }, {
        name: "评审人",
        key: "reviewerId",
        type: "select",
        datas: this.$store.state.userList
    }];

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

    public updateOptions: FormOption<BtnOption>[] = [] as any;
    public buildUpdateForm() {
        this.updateOptions = [{
            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"
            }]
        }, {
            name: "成效水平",
            type: "text",
            key: "level",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            disable: true,
        }, {
            name: "评审人",
            type: "select",
            key: "reviewerId",
            format: "reviewerName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.userList,
        }, {
            name: "评审时间",
            type: "date",
            key: "reviewTime",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            format: "yyyy-MM-dd"
        },]
    }


    public updateActions = [{
        name: "取消",
        value: "cancel"
    }, {
        name: "保存",
        value: "save",
        type: "primary"
    }];


    created() {
        //
    }


    public buildTable() {
        this.tableColumn.push({ name: '评审时间', key: "reviewTime", });
        this.tableColumn.push({ name: '评审人', key: "reviewerName", });
        this.tableColumn.push({ name: '扣分', key: "deductPoints", width: "90px" });
        this.tableColumn.push({ name: '得分', key: "scorePoints", width: "90px" });
        this.tableColumn.push({
            name: '成效水平', key: "level", render: (data) => {
                if (data.scorePoints < 70) {
                    return '不合格'
                } else if (data.scorePoints < 80) {
                    return '合格'
                } else if (data.scorePoints < 90) {
                    return '良好'
                } else if (data.scorePoints >= 90) {
                    return '优秀'
                }
            }
        });
        this.tableColumn.push({
            name: '线下评审记录', key: "resourceName", showTip: true, render: (data) => {
                if (data.resourceName) {
                    return `<span class="text_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.addUpdateMethod();
        }
    }
    /**
     * 添加按钮操作
     */
    public addUpdateMethod() {
        this.estimateStandard = [] as any;
        this.checkReject = [] as any;
        this.total = 10;
        this.updateParams = {
            reviewerId: this.account.userId,
            reviewTime: moment().format('YYYY-MM-DD'),
        } as any;
        const tmpStandard = JSON.parse(JSON.stringify(Standard));
        this.estimateStandard = tmpStandard;
        const tmpStandardContent = JSON.parse(JSON.stringify(StandardContent));
        this.StandardDetails = tmpStandardContent;
        this.isReadonly = false;
        this.buildUpdateForm();
        //清除附件缓存数据
        this.clearFileListMethod();
        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 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 showDetails(el, row) {
        const isTarget = el.target.classList.contains("text_link");
        if (isTarget) {
            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 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.response.data.id), 1)
    }

    public subCallback(data) {
        if (data.value === "cancel") {
            this.showUpdate = false
        } else if (data && data.value.indexOf("save") >= 0) {
            this.doSave(data.value !== "save")
        }
    }


    public doSave(goOn?) {
        //无否决项 判断自评项是否均已填写
        if (this.checkReject.length === 0) {
            let tips: any = false;
            this.estimateStandard.forEach((item: any) => {
                item.tableData.forEach((dataitem: any) => {
                    if (dataitem.deductPoints === '--') {
                        tips = true
                    }
                })
            })
            if (tips === true) {
                this.$message.warning('您有自评项未填写！！')
                return
            }
        }
        //整理传参数据
        this.reorganizeParamsDataMethod();
        this.tableService.addOrUpdate(this.updateParams, this.updateParams.id ? false : true).then((res) => {
            this.$message.success(!this.updateParams.id ? "新增成功！" : "编辑成功！");
            //保存清空
            this.estimateStandard = [] as any;
            this.checkReject = [] as any;
            this.total = 10;
            this.updateParams = {
                reviewerId: this.account.userId,
                reviewTime: moment().format('YYYY-MM-DD'),
            } as any;
            const tmpStandard = JSON.parse(JSON.stringify(Standard))
            this.estimateStandard = tmpStandard
            const tmpStandardContent = JSON.parse(JSON.stringify(StandardContent))
            this.StandardDetails = tmpStandardContent
            this.buildUpdateForm()
            this.showUpdate = !!goOn;
            this.getTableData();
        })
    }
    /**
     * 整理传参数据
     */
    public reorganizeParamsDataMethod() {
        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 = ''
        }
        let tmpContent = {} as any;
        tmpContent.content = this.estimateStandard;
        tmpContent.checkReject = this.checkReject;
        tmpContent.total = this.total;
        tmpContent.level = this.updateParams.level;
        this.updateParams.content = JSON.stringify(tmpContent);
        this.updateParams.scorePoints = this.total;
        this.updateParams.deductPoints = 110 - this.total;
        this.updateParams.reviewerName = this.$store.getters.user_map[this.updateParams.reviewerId];
    }

    public showModal(row, isReadonly) {
        if (isReadonly) {
            this.isReadonly = true
        } else {
            this.isReadonly = false
        }

        this.tableService.getListDetail({ id: row.id }).then((res: any) => {
            if (res.code === 200) {
                this.updateParams = res.data
                const tmpContent = JSON.parse(this.updateParams.content)
                this.estimateStandard = tmpContent.content
                this.total = tmpContent.total
                this.checkReject = tmpContent.checkReject
                this.updateParams.level = tmpContent.level
                const tmpStandardContent = JSON.parse(JSON.stringify(StandardContent))
                this.StandardDetails = tmpStandardContent
                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 selectRadio(e) {
        let level = null as any;
        if (e.length > 0) {
            level = this.compareLevel(0)
        } else {
            level = this.compareLevel(this.total)
        }

        this.updateParams.level = level
        this.buildUpdateForm()
    }

    public cellClick(row, column) {
        if (this.isReadonly === false) {
            if (column.label === '扣分') {
                row.pointFlag = true;
                this.clickPointFlag = true;
                this.$nextTick(() => {
                    (this.$refs.score as any)[0].focus();
                })
            } else if (column.label === '评估记录') {
                row.recordFlag = true;
                this.$nextTick(() => {
                    (this.$refs.record as any)[0].focus();
                })
            }
        }
    }
    //input框失去焦点事件
    public inputClick(row) {
        if (row.pointFlag === true) {
            row.pointFlag = false
            this.clickPointFlag = false
        } else if (row.recordFlag === true) {
            row.recordFlag = false
        }

    }

    public proving(e) {
        //键盘输入 --
        if (e.key == '-') {
            e.target.value = null
        }
        var val = e.target.value;
        //限制只能输入一个小数点
        if (val.indexOf(".") != -1) {
            var str = val.substr(val.indexOf(".") + 1);
            if (str.indexOf(".") != -1) {
                val = val.substr(0, val.indexOf(".") + str.indexOf(".") + 1);
            }
        }
    }
    /**
     * 获取输入焦点
     * @param data 
     * @param row 
     * @param items 
     */
    public pointInput(data, row, items) {
        // 过滤0后面接数值
        if (data.replace(/^0+(\d)/, "$1")) {
            data = data.replace(/^0+(\d)/, "$1")
            row.deductPoints = data.replace(/^0+(\d)/, "$1")
        }
        //过滤一串 0
        if (data == '00') {
            data = 0
            row.deductPoints = 0
        }
        //过滤超出该项分值
        if (data > row.score) {
            data = null
            row.deductPoints = null
        }
        if (!data) {
            data = null
            row.deductPoints = null
        }

        if (data || data === 0) {
            let points = row.score - data
            row.getPoints = points > 0 ? points : 0
            let itemScore = 0
            items.tableData.forEach(item => {
                if (item.getPoints !== '--') {
                    itemScore = itemScore + item.getPoints
                }
            })
            items.score = itemScore
            let totalScore = 0
            if (this.checkReject.length === 0) {
                this.estimateStandard.forEach(item => {
                    totalScore = totalScore + item.score
                })
            }
            this.total = totalScore
        } else {
            if (row.getPoints !== '--') {
                items.score = items.score - row.getPoints
                let totalScore = 0
                if (this.checkReject.length === 0) {
                    this.estimateStandard.forEach(item => {
                        totalScore = totalScore + item.score
                    })
                }
                this.total = totalScore
                row.deductPoints = '--'
                row.getPoints = '--'
            }

        }
        const level = this.compareLevel(this.total)
        this.updateParams.level = level
        this.buildUpdateForm()
    }

    //成效shuip
    public compareLevel(score) {
        if (this.checkReject.length > 0) {
            return '不合格'
        } else {
            if (score < 70) {
                return '不合格'
            } else if (score < 80) {
                return '合格'
            } else if (score < 90) {
                return '良好'
            } else if (score >= 90) {
                return '优秀'
            }
        }
    }
    //预览附件
    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.updateOptions.find(item => item.key === "resourceId") as any;
        option.fileList = [];
    }

}
</script>
<style lang="scss" scoped src="../../common.component.scss"></style>
<style lang="scss" scoped>
::v-deep {
    .check-reject {

        .el-checkbox__input.is-checked .el-checkbox__inner,
        .el-checkbox__input.is-indeterminate .el-checkbox__inner {
            background-color: #F56C6C;
            border-color: #F56C6C;

        }

        .el-checkbox__inner {
            border-radius: 25px;
        }

        .el-checkbox__inner:hover {
            border-color: #F56C6C;
        }

        .el-checkbox__input.is-checked+.el-checkbox__label {
            color: #F56C6C;
        }

        .el-checkbox__input.is-focus .el-checkbox__inner {
            border-color: #F56C6C;
        }

        .el-radio__inner:after {
            width: 4px;
            height: 4px;
            border-radius: 100%;
            background-color: #fff;
            content: "";
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%) scale(0);
            transition: transform .15s ease-in;
        }

        .el-radio__input.is-checked .el-radio__inner:after {
            transform: translate(-50%, -50%) scale(1);
        }
    }


}

.total-title {
    width: 56px;
    height: 56px;
    background: #F7F7F7;
    border-radius: 4px 0px 0px 4px;
    border: 1px solid #E6E6E6;
    line-height: 56px;
    text-align: center;
    font-size: 16px;
    font-weight: 700;
    color: rgba(0, 0, 0, 0.7);
    letter-spacing: 1px;
}

.total-content {
    width: 159px;
    height: 56px;
    background: #FFFFFF;
    border-radius: 0px 4px 4px 0px;
    border: 1px solid #E6E6E6;
    text-align: center;
    font-size: 24px;
    font-weight: 500;
    color: #409EFF;
    line-height: 56px;
}
</style>
<style lang="scss">
.el-popover.standard-content {
    width: 400px !important;
    background: #000000 !important;
    border-radius: 4px !important;
    opacity: 0.8 !important;
    color: #fff;
    padding: 20px;
    letter-spacing: 2px;
    border: 0px;

    .standard-content-title {
        height: 22px;
        font-size: 16px;
        font-weight: 500;
        color: #FFFFFF;
        line-height: 22px;
        margin-bottom: 24px;
    }

    .standard-content-item-title {
        height: 20px;
        font-size: 14px;
        font-weight: 500;

        color: rgba(255, 255, 255, 0.5);
        line-height: 20px;
        border-left: 3px solid rgba(255, 255, 255, 0.5);
        padding-left: 14px;
        margin-bottom: 12px;
    }

    .standard-content-item-content {
        background: #000000;
        border-radius: 4px;
        opacity: 0.8;
        padding-bottom: 24px;

        .standard-item-title {
            font-size: 14px;
            font-weight: 500;
            color: #FFFFFF;
            line-height: 22px;
            padding-bottom: 5px;
        }

        .standard-item-content {
            font-size: 14px;
            font-weight: 500;
            color: #FFFFFF;
            line-height: 22px;
            padding-bottom: 5px;
            color: rgba(255, 255, 255, 0.9);
        }

        .standard-item-reject-content {
            font-size: 14px;
            font-weight: 500;
            color: #F56C6C;
            line-height: 22px;
        }
    }

    .standard-content-item-reject-title {
        height: 20px;
        font-size: 16px;
        font-weight: 500;
        color: #F56C6C;
        line-height: 20px;
        border-left: 3px solid #F56C6C;
        padding-left: 14px;
        margin-bottom: 12px;
    }
}
</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>