<script lang="ts">
import { Component } from 'vue-property-decorator';
import template from "./riskJudgment.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 RiskJudgmentService from "@/service/riskJudgment.service"
import FormOption from "hbt-common/models/formOptions"
import BtnOption from "hbt-common/models/btnOptions"
import DrawComponent from '@/components/draw.component.vue';
import ButtonListComponent from "hbt-common/components/common/buttonList.component.vue";
import UnitTreeComponent from '@/components/tree.component.vue';
import judgment from "@/mock/judgment";
import moment from 'moment';
import { Row } from 'element-ui';

@Component({
    template,
    components: {
        FormComponent,
        TableComponent,
        DrawComponent,
        ButtonListComponent,
        UnitTreeComponent,
    },
})
export default class RiskJudgment extends BaseRecordComponent<any> {
    public tableService = new RiskJudgmentService();

    public params = {
        type: 1
    } as any;

    public isReadonly = false;
    //班组信息
    public subIsReadonly = false;

    public fileList = [] as any;

    public teamsTableColumn = [] as any;

    public workshopTableColumn = [] as any;

    public companyTableColumn = [] as any;

    public subTableColumn = [] as any;

    public subUpdateParams = {
        risks: []
    } as any;

    public riskUpdateParams = {} as any;

    public subShowUpdate = false;

    public judgmentData = JSON.parse(JSON.stringify(judgment));

    public subTableTitle = ['', '风险研判', '班组研判信息', '车间研判信息'];

    public triTableTitle = '';

    public hideNextBtn = false;

    public tableState = { 1: '待研判', 2: '已研判', 3: '未研判' };

    public tableStateColor = ['', '#E6A23C', "#68C23A", "#F56C6C"];

    public subTableState = { 0: '未研判', 1: "已研判" };

    public currentUrl = '';

    public detailTableData = {} as any;

    public showDetailModal = false;

    public detailTableColumn = [] as any;

    public showFile = false;

    public tabs = [{
        name: "班组风险研判",
        value: 1
    }, {
        name: "车间风险研判",
        value: 2
    }, {
        name: "企业风险研判",
        value: 3
    },]


    public showUpdate = false;


    public formActions = [{
        name: "查询",
        value: "search",
        icon: "el-icon-search",
        type: "primary"
    }, {
        name: "清空",
        icon: "el-icon-tickets",
        value: "reset"
    }];
    public subTableActions = [{
        name: "批量研判",
        value: "batchAdd",
        icon: "el-icon-plus",
        type: "primary"
    },];
    public footerActions = [{
        name: "选择全部",
        value: "selectAll",
        type: "primary"
    }, {
        name: "反向选择",
        value: "reverse"
    }];
    public formOptions: FormOption<BtnOption>[] = [{
        name: "车间",
        key: "controlName",
        type: "text",
    }, {
        name: "班组",
        key: "analName",
        type: "text",
    }];

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

    public updateParams = {} as any;
    public selectData = [];

    public updateActions = [] as any;

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

    public buildUpdateForm() {
        this.updateOptions = [{
            name: "班组名称",
            key: "name",
            type: "text",
            require: true,
            width: "calc(50% - 20px)",
            disable: true,
            hide: this.params.type !== 1,
            showError: false,
        },
        {
            name: "班组负责人",
            key: "chargeUserName",
            type: "text",
            require: true,
            width: "calc(50% - 20px)",
            hide: this.params.type !== 1,
            showError: false,
            disable: true
        },
        {
            name: "车间名称",
            key: "name",
            type: "text",
            require: true,
            width: "calc(50% - 20px)",
            disable: true,
            hide: this.params.type !== 2,
            showError: false,
        },
        {
            name: "车间负责人",
            key: "chargeUserName",
            type: "text",
            require: true,
            width: "calc(50% - 20px)",
            hide: this.params.type !== 2,
            showError: false,
        },
        {
            name: "企业名称",
            key: "name",
            type: "select",
            require: true,
            width: "calc(50% - 20px)",
            disable: true,
            hide: this.params.type !== 3,
            showError: false,
        },
        {
            name: "企业负责人",
            key: "chargeUserName",
            type: "text",
            require: true,
            width: "calc(50% - 20px)",
            hide: this.params.type !== 3,
            showError: false,
        },
        {
            name: "研判时间",
            key: "researchTime",
            type: "date",
            subType: "datetime",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            format: "yyyy-MM-dd HH:mm:ss"
        },
        {
            name: "负责人签名",
            key: "file",
            ref: "file",
            type: "upload",
            width: "calc(50% - 20px)",
            showError: false,
            require: true,
            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: "是否已落实管控措施",
            key: "workableFlag",
            format: "workableFlagName",
            type: "radio",
            require: true,
            labelWidth: "140px",
            width: "calc(50% - 20px)",
            showError: false,
            datas: [{
                name: "是",
                value: 1,
            }, {
                name: "否",
                value: 0,
            }],
        },];

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

    public resultOptions: FormOption<BtnOption>[] = [] as any;
    public judgmentFooterActions = [] as any;
    public buildJudgmentForm() {
        this.resultOptions = [
            {
                name: "研判状态",
                key: "status",
                format: 'statusName',
                type: "radio",
                require: true,
                width: "calc(50% - 20px)",
                showError: false,
                disable: this.params.type !== 1,
                datas: [{
                    name: "已研判",
                    value: 1
                },]
            },
        ];
        this.judgmentFooterActions = [{
            name: "取消",
            value: "cancel"
        }, {
            name: "下一条",
            value: "next",
            type: "primary",
            hide: this.hideNextBtn,
        }, {
            name: "保存",
            value: "save",
            type: "primary"
        }] as any;
    }


    created() {
        //
        this.buildSubTable()


    }

    public buildTable() {
        //班组
        this.teamsTableColumn.push({
            name: '状态', key: "status", render: (data) => {
                return `<span style="color:${this.tableStateColor[data.status]}">${this.tableState[data.status]}</span>`
            }
        });
        this.teamsTableColumn.push({ name: '班组名称', key: "name", });
        this.teamsTableColumn.push({ name: '班组负责人', key: "chargeUserName", });
        this.teamsTableColumn.push({ name: '已研判风险点', key: "completeNum", });
        this.teamsTableColumn.push({ name: '未研判风险点', key: "noCompleteNum", });
        this.teamsTableColumn.push({
            name: '是否已落实管控措施', key: "workableFlag", render: (data) => {
                return data.workableFlag === 1 ? '是' : '否'
            }
        });
        this.teamsTableColumn.push({ name: '研判时间', key: "researchTime", });
        //车间
        this.workshopTableColumn.push({
            name: '状态', key: "status", render: (data) => {
                return `<span style="color:${this.tableStateColor[data.status]}">${this.tableState[data.status]}</span>`
            }
        });
        this.workshopTableColumn.push({ name: '车间名称', key: "name", });
        this.workshopTableColumn.push({ name: '车间负责人', key: "chargeUserName", });
        this.workshopTableColumn.push({
            name: '已研判班组', key: "completeNum", render: (data) => {
                return "<span class='link completeNum'>" + (data.completeNum ? data.completeNum : 0) + "</span>"
            }
        });
        this.workshopTableColumn.push({
            name: '未研判班组', key: "noCompleteNum", render: (data) => {
                return "<span class='link nocompleteNum'>" + (data.noCompleteNum ? data.noCompleteNum : 0) + "</span>"
            }
        });
        this.workshopTableColumn.push({
            name: '风险点', key: "riskNumber", render: (data) => {
                return "<span class='link riskNumber'>" + (data.riskNumber ? data.riskNumber : 0) + "</span>"
            }
        });
        this.workshopTableColumn.push({
            name: '是否已落实管控措施', key: "workableFlag", render: (data) => {
                return data.workableFlag === 1 ? '是' : '否'
            }
        });
        this.workshopTableColumn.push({ name: '研判时间', key: "researchTime", });
        //企业
        this.companyTableColumn.push({
            name: '状态', key: "status", render: (data) => {
                return `<span style="color:${this.tableStateColor[data.status]}">${this.tableState[data.status]}</span>`
            }
        });
        this.companyTableColumn.push({ name: '企业名称', key: "name", });
        this.companyTableColumn.push({ name: '企业负责人', key: "chargeUserName", });
        this.companyTableColumn.push({
            name: '已研判车间', key: "completeNum", render: (data) => {
                return "<span class='link completeNum'>" + (data.completeNum ? data.completeNum : 0) + "</span>"
            }
        });
        this.companyTableColumn.push({
            name: '未研判车间', key: "noCompleteNum", render: (data) => {
                return "<span class='link nocompleteNum'>" + (data.noCompleteNum ? data.noCompleteNum : 0) + "</span>"
            }
        });
        this.companyTableColumn.push({
            name: '风险点', key: "riskNumber", render: (data) => {
                return "<span class='link riskNumber'>" + (data.riskNumber ? data.riskNumber : 0) + "</span>"
            }
        });
        this.companyTableColumn.push({
            name: '是否已落实管控措施', key: "workableFlag", render: (data) => {
                return data.workableFlag === 1 ? '是' : '否'
            }
        });
        this.companyTableColumn.push({ name: '研判时间', key: "researchTime", });

    }

    //子表 -- table
    public buildSubTable() {
        this.subTableColumn = [] as any;
        if (this.params.type === 1) {
            this.subTableColumn.push({ name: "序号", key: "index" });
            this.subTableColumn.push({ name: "风险点名称", key: "riskName" });
            this.subTableColumn.push({
                name: "风险等级", key: "riskLevel", render: (data) => {
                    if (data.riskLevel) {
                        return "<span class='color_level_" + data.riskLevel + "'>" + (data.riskLevel ? (this.$store.getters.prevention_risk_level_map[data.riskLevel]) : '') + "</span>"
                    }
                }
            });
            this.subTableColumn.push({
                name: "研判状态", key: "status", render: (data) => {
                    return `<span class="color_${data.status}">${this.subTableState[data.status]}</span>`
                }
            });
        } else if (this.params.type === 2) {
            this.subTableColumn.push({ name: "序号", key: "index" });
            this.subTableColumn.push({ name: "班组名称", key: "subordinateName" });
            this.subTableColumn.push({ name: "班组负责人", key: "chargeUserName" });
            this.subTableColumn.push({
                name: "风险点", key: "total", render: (data) => {
                    return "<span class='link total'>" + (data.total ? data.total : 0) + "</span>"
                }
            });
            this.subTableColumn.push({ name: "重大风险", key: "greater" });
            this.subTableColumn.push({ name: "较大风险", key: "significant" });
            this.subTableColumn.push({ name: "一般风险", key: "general" });
            this.subTableColumn.push({ name: "低风险", key: "low" });
            this.subTableColumn.push({
                name: "研判状态", key: "status", render: (data) => {
                    return `<span style="color:${this.tableStateColor[data.status]}">${this.tableState[data.status]}</span>`
                }
            });
        } else if (this.params.type === 3) {
            this.subTableColumn.push({ name: "序号", key: "index" });
            this.subTableColumn.push({ name: "车间名称", key: "subordinateName" });
            this.subTableColumn.push({ name: "车间负责人", key: "chargeUserName" });
            this.subTableColumn.push({
                name: "风险点", key: "total", render: (data) => {
                    return "<span class='link total'>" + (data.total ? data.total : 0) + "</span>"
                }
            });
            this.subTableColumn.push({ name: "重大风险", key: "significant" });
            this.subTableColumn.push({ name: "较大风险", key: "greater" });
            this.subTableColumn.push({ name: "一般风险", key: "general" });
            this.subTableColumn.push({ name: "低风险", key: "low" });
            this.subTableColumn.push({
                name: "研判状态", key: "status", render: (data) => {
                    return `<span style="color:${this.tableStateColor[data.status]}">${this.tableState[data.status]}</span>`
                }
            });
        }

    }

    public changes(data, item) {
        //
    }

    public callback(data, type) {
        if (type) {
            this.params[type] = data;
            this.getTableData();
            return
        }
        // 查询
        if (data.value === "search") {
            this.getTableData()
            // 重置
        } else if (data.value === "cancel") {
            this.showUpdate = false
        } else if (data.value === 'batchAdd') {
            //批量研判
            this.batchAddMethod();
        } else if (data.value === 'save') {
            this.doSave()
        }
    }
    //批量研判
    public batchAddMethod() {
        this.$confirm('批量研判会统一修改研判状态为“已研判”，并写入默认数据。请在此确认是否操作？', '确认数据', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            //批量处理
            const judgmentdata = JSON.parse(JSON.stringify(judgment));
            this.subUpdateParams.risks.forEach((item: any) => {
                item.content = JSON.stringify(judgmentdata);
                item.status = 1;
            });
        });
    }

    // 重置数据
    public reset() {
        this.params = {
            pageNum: 1,
            pageSize: 20,
        } as any;
    }

    // 分页数据
    public getTableData() {
        this.tableService.selectByPage(this.params).then(res => {
            this.tableData = res.data as any;
        })
    }

    public handleClose() {
        this.showUpdate = false;
        this.buildUpdateForm()
    }

    public onPreview(file: any) {
        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: any) {
        if (res.code === 200) {
            this.fileList = [];
            this.fileList.push({
                name: res.data.originalName,
                url: res.data.url,
                type: res.data.type,
                id: res.data.id
            })
            this.subUpdateParams.file = this.fileList.length || null;
            this.buildUpdateForm()
        } else {
            this.$message.error(res.msg);
        }

    }

    public onRemove(file: any) {
        this.fileList.splice(this.fileList.findIndex((item: any) => item.id === file.uid), 1)
        this.subUpdateParams.file = this.fileList.length || null;
    }

    //标签页切换
    public tabTableChange(type) {
        this.params.pageNum = 1;
        this.buildSubTable()
        this.getTableData()
    }

    //保存
    public doSave() {
        if ((this.$refs.basicForm as any).vaildParams()) {
            //车间或者企业判断
            if (this.params.type !== 1) {
                if (this.subUpdateParams.subordinates.filter((item: any) => item.status !== 2).length > 0) {
                    this.$message.error("请先确定风险点已研判完成！");
                    return
                }
            }
            this.subUpdateParams.resourceId = this.fileList.map((item: any) => item.id).join(",");
            this.subUpdateParams.resourceName = this.fileList.map((item: any) => item.name).join(",");
            this.subUpdateParams.status = 2;
            this.tableService.addOrUpdate(this.subUpdateParams, false).then((res: any) => {
                this.$message.success("研判成功！");
                this.subUpdateParams = { risks: [] } as any
                this.showUpdate = false;
                this.getTableData();
            })
        }
    }

    //风险点研判信息
    public triCallback(data) {
        if (data && data.value === "cancel") {
            this.subShowUpdate = false
        } else if (data.value === 'save') {
            //保存研判表数据
            this.doSaveJudgmentContent()
            this.subShowUpdate = false;
        } else if (data.value === 'next') {
            if (this.riskUpdateParams.status !== 1) {
                this.$message.error("当前风险未研判！");
                return
            }
            //下一条研判
            //先保存当前数据
            this.doSaveJudgmentContent();
            //处理下一条数据
            this.handleNextMethod();
            this.buildJudgmentForm()
        }
    }

    public handleNextMethod() {
        let currentRiskIdx = this.subUpdateParams.risks.findIndex((item) => item.id === this.riskUpdateParams.id);
        this.riskUpdateParams = this.subUpdateParams.risks[currentRiskIdx + 1];
        //判断是否是最后一条
        if ((currentRiskIdx + 2) === this.subUpdateParams.risks.length) {
            this.hideNextBtn = true;
        } else {
            this.hideNextBtn = false;
        }
        this.riskUpdateParams.status = null
        this.triTableTitle = this.riskUpdateParams.riskName;
        this.judgmentData = this.riskUpdateParams.content ? JSON.parse(this.riskUpdateParams.content) : JSON.parse(JSON.stringify(judgment));
    }

    //研判 -- 查看
    public showUpdateModel(row: any, isreadonly: any) {
        this.subUpdateParams = { risks: [] } as any;
        this.fileList = [];
        this.subUpdateParams.file = null;
        if (isreadonly) {
            this.isReadonly = true;
        } else {
            this.isReadonly = false;
        }
        this.tableService.selectByDetail({ id: row.id, type: this.params.type }).then((res: any) => {
            this.subUpdateParams = res.data;
            this.subUpdateParams.name = row.name;
            this.subUpdateParams.chargeUserName = row.chargeUserName;
            this.subUpdateParams.researchTime = moment().format('YYYY-MM-DD HH:mm:ss');
            this.subUpdateParams.workableFlagName = this.subUpdateParams.workableFlag === 1 ? '是' : '否';
            if (this.params.type === 1) {
                this.subUpdateParams.risks.forEach((item, index) => {
                    item.index = index + 1
                })
            } else {
                if (this.subUpdateParams.subordinates.filter((item) => item.status !== 2).length > 0) {
                    this.subUpdateParams.status = 0
                    this.subUpdateParams.statusName = '未研判'
                } else {
                    this.subUpdateParams.status = 1
                    this.subUpdateParams.statusName = '已研判'
                }
                this.subUpdateParams.subordinates.forEach((item, index) => {
                    item.index = index + 1;
                })
                this.buildJudgmentForm()
            }
            // 获取url
            if (res.data.resourceId) {
                this.tableService.getFileUrls({ ids: res.data.resourceId }).then((file: any) => {
                    this.fileList = file.data.map(item => {
                        return {
                            name: item.originalName,
                            url: item.url,
                            type: item.type,
                            id: item.id
                        }
                    })
                    if (!isreadonly) {
                        this.subUpdateParams.file = this.fileList.length || null;
                    }
                    this.buildUpdateForm();
                })
            }
            this.buildUpdateForm();
            this.showUpdate = true;
        })

    }

    //研判操作
    public showJudgmentModal(row: any, isreadonly: any) {
        this.triTableTitle = row.riskName;
        this.riskUpdateParams = JSON.parse(JSON.stringify(row));
        if (isreadonly) {
            this.subIsReadonly = true;
            this.riskUpdateParams.statusName = this.riskUpdateParams.status === 1 ? '已研判' : '未研判'
        } else {
            this.subIsReadonly = false;
            if (this.riskUpdateParams.status !== 1) {
                this.riskUpdateParams.status = null
            }
        }
        this.judgmentData = row.content ? JSON.parse(row.content) : JSON.parse(JSON.stringify(judgment));
        if (row.index === this.subUpdateParams.risks.length) {
            this.hideNextBtn = true;
        } else {
            this.hideNextBtn = false;
        }
        this.buildJudgmentForm()
        this.subShowUpdate = true;
    }

    //合并研判表的单元格
    public objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        //把几行合成一行  判断起始行，设置合并行数，其余行设置为0 
        if (columnIndex === 0) {
            if (rowIndex === 0) {
                return {
                    rowspan: 4,
                    colspan: 1
                };
            } else if (rowIndex === 4) {
                return {
                    rowspan: 6,
                    colspan: 1
                };
            } else if (rowIndex === 10) {
                return {
                    rowspan: 3,
                    colspan: 1
                };
            } else {
                return {
                    rowspan: 0,
                    colspan: 0
                }
            }
        }
    }

    //保存研判内容
    public doSaveJudgmentContent() {
        this.riskUpdateParams.content = JSON.stringify(this.judgmentData);
        this.subUpdateParams.risks.splice(this.subUpdateParams.risks.findIndex(item => item.id === this.riskUpdateParams.id), 1, this.riskUpdateParams);
    }
    //查看信息
    public showDetails(el, data, rowparams) {
        //初始化参数
        let params = {} as any;
        params.taskId = data.taskId;
        params.type = this.params.type
        if (this.params.type === 2) {
            params.workshopId = data.workshopId
        } else if (this.params.type === 3) {
            params.companyId = data.companyId
        }
        //已判班组车间
        if (el.target.classList.contains("completeNum")) {
            params.status = 2
            this.judgmentMethod(params);
        }
        //未判班组车间
        if (el.target.classList.contains("nocompleteNum")) {
            this.judgmentMethod(params);
        }
        //风险点
        if (el.target.classList.contains("riskNumber")) {
            this.tableService.selectRiskGroup({ id: data.workshopId ? data.workshopId : data.companyId, type: this.params.type }).then((res) => {
                this.addTeamsColumnMethod('risk');
                this.detailTableData.datas = res.data
                this.showDetailModal = true
            })
        }
        //班组 车间风险点详情
        if (el.target.classList.contains("total")) {
            this.riskDetailMethod(rowparams, data);
        }
    }
    //班组 车间风险点详情
    public riskDetailMethod(rowparams: any, data: any) {
        if (this.params.type === 3) {
            this.tableService.getWorkshopRiskList({ workshopId: data.subordinateId }).then((res: any) => {
                this.detailTableData.datas = res.data;
                this.addTeamsColumnMethod('totalrisk');
                this.showDetailModal = true;
            })
            return
        }
        let params = {} as any;
        params.taskId = rowparams.taskId;
        params.teamId = data.subordinateId;
        this.tableService.selectRiskList(params).then((res: any) => {
            this.detailTableData.datas = res.data.datas;
            this.addTeamsColumnMethod('totalrisk');
            this.showDetailModal = true;
        });
    }

    //已研判、未研判信息
    public judgmentMethod(params: any) {
        this.tableService.selectResearchDetail(params).then((res: any) => {
            this.detailTableData.datas = res.data;
            //班组、车间 定义column
            this.addTeamsColumnMethod(null);
            this.showDetailModal = true;
        });
    }

    //已研判 未研判
    public addTeamsColumnMethod(type) {
        this.detailTableColumn = [];
        if (type && type.indexOf('risk') !== -1) {
            if (type === 'risk') {
                if (this.params.type === 2) {
                    this.detailTableColumn.push({ name: "班组名称", key: "name" });
                }
                if (this.params.type === 3) {
                    this.detailTableColumn.push({ name: "车间名称", key: "name" });
                }
            }
            this.detailTableColumn.push({ name: "风险点", key: "riskName" });
            this.detailTableColumn.push({
                name: "风险等级", key: "riskLevel", render: (data) => {
                    return "<span class='color_level_" + data.riskLevel + "'>" + (data.riskLevel ? (this.$store.getters.prevention_risk_level_map[data.riskLevel]) : '') + "</span>"
                },
                filters: this.$store.state.prevention_risk_level.map(item => {
                    return {
                        text: item.name,
                        value: item.value,
                    }
                }), filterMethod: (data, row) => {
                    return row.riskLevel === data;
                }
            });
            return
        }
        if (this.params.type === 2) {
            this.detailTableColumn.push({ name: "班组名称", key: "subordinateName" });
        }
        if (this.params.type === 3) {
            this.detailTableColumn.push({ name: "车间名称", key: "subordinateName" });
        }
        this.detailTableColumn.push({ name: "班组负责人", key: "chargeUserName" });
    }

}
</script>
<style lang="scss" scoped src="../../common.component.scss"></style>
<style  lang="scss" scoped >
.common-table-box {
    margin-top: 15px
}
</style>
