
<script lang="ts">
import { Component, Watch } from 'vue-property-decorator';
import template from "./workAnal.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 FormOption from "hbt-common/models/formOptions"
import BtnOption from "hbt-common/models/btnOptions"
import DrawComponent from '@/components/draw.component.vue';
import UnitTreeComponent from '@/components/tree.component.vue';
import AnalEvaluationComponent from '@/components/analEvaluation.component.vue';
import WorkService from '@/service/work.service';
import UnitService from '@/service/unit.service';
import AreaService from '@/service/area.service';
import SystemService from "hbt-common/service/system.service"
import JobHazardService from '@/service/jobHazard.service';
import ButtonListComponent from "hbt-common/components/common/buttonList.component.vue";
import moment from "moment";

@Component({
    template,
    components: {
        FormComponent,
        TableComponent,
        DrawComponent,
        AnalEvaluationComponent,
        UnitTreeComponent,
        ButtonListComponent
    },
})
export default class WorkAnalManagerComponent extends BaseRecordComponent<any> {
    public tableService = new JobHazardService();
    public unitService = new UnitService();
    public areaService = new AreaService();
    public systemService = new SystemService();
    // public diviceService = new DiviceService();
    public workService = new WorkService();

    public params = {
        areaName: "",
        unitName: "",
    } as any;

    public treeData = [] as any;

    public areaList = [] as any;
    public unitList = [];
    public jobList = [];
    public isReadonly = false;
    public isModifyonly = false;
    public subTableColumn = [] as any;
    public currentId = -1;

    public craftMap = {} as any;
    public chemicaltMap = {} as any
    public majorsignMap = {} as any;

    //检查项目
    public showProtable = false;

    public proTableColumn = [] as any;

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

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

    //评估矩阵
    public showMatrixModal = false;
    //评价
    public showSubUpdate = false;

    public analyIsReadonly = false;
    //危害分析评价
    public analysisUpdateParams = {
        riskChoose: [],
        remainChoose: [],
        remainLevel: null,
        riskLevel: null,
        datas: []

    } as any;

    //评估方法
    public checkRiskType = {
        risk: [],
        remain: [],
        type: null,
    } 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: "areaName",
        type: "text",
    }, {
        name: "单元名称",
        key: "unitName",
        type: "text",
    },];

    public showUpdate = false;

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

    public updateParams = {
        majorSign: [],
        steps: [],
        evaluateTime: moment().format('YYYY-MM-DD'),
        evaluateUserId: this.account.userId,
        evaluateUserName: this.account.nickName,
    } as any;

    public selectData = [];

    public subSelectData = []

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

    public subBasicRiskOptions: FormOption<BtnOption>[] = [];

    public subTableActions: BtnOption[] = [];

    public labelWidth = "140px";

    public seriousResultMap = {} as any;

    public riskLevelMap = {} as any;

    public buildUpdateForm() {
        console.log(this.updateParams.id && this.updateParams.status !== 1,);

        this.updateOptions = [{
            name: "区域名称",
            key: "areaId",
            format: "areaName",
            type: "select",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.areaList,
            disable: !this.updateParams.status || this.updateParams.status === 1 ? false : true
        }, {
            name: "单元名称",
            key: "unitId",
            format: "unitName",
            type: "select",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.unitList,
            disable: !this.updateParams.status || this.updateParams.status === 1 ? false : true
        }, {
            name: "责任部门",
            key: "chargeDeptName",
            type: "text",
            require: true,
            width: "calc(50% - 20px)",
            disable: true,
        }, {
            name: "责任人",
            key: "chargeUserName",
            type: "text",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            disable: true,
        }, {
            name: "作业名称",
            key: "jobInventoryId",
            format: 'jobInventoryName',
            type: "select",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.jobList,
            disable: !this.updateParams.status || this.updateParams.status === 1 ? false : true
        }, {
            name: "作业地点",
            key: "location",
            type: "text",
            require: true,
            width: "calc(50% - 20px)",
            disable: true,
        }, {
            name: "涉及岗位",
            key: "postName",
            type: "text",
            width: "calc(100% - 20px)",
            require: true,
            disable: true,
        }, {
            name: "评价人",
            key: "evaluateUserId",
            format: "evaluateUserName",
            require: true,
            width: "calc(50% - 20px)",
            type: "select",
            showError: false,
            datas: this.$store.state.userList
        }, {
            name: "评价时间",
            key: "evaluateTime",
            type: "date",
            subType: "date",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            format: "yyyy-MM-dd"
        }, {
            name: "区域固有风险等级",
            key: "analRiskLevel",
            format: "analRiskLevelName",
            require: true,
            width: "calc(50% - 20px)",
            labelWidth: "140px",
            type: "select",
            showError: false,
            disable: true,
            datas: this.$store.state.prevention_risk_level
        }, {
            name: "是否为两大一重",
            key: "majorSign",
            format: "majorSignName",
            type: "checkbox",
            labelWidth: "140px",
            width: "calc(100% - 20px)",
            require: true,
            showError: false,
            disable: this.updateParams.id && this.updateParams.status !== 1,
            datas: [{
                name: "不涉及",
                value: 0,

            }, {
                name: "重大危险源",
                disable: this.updateParams.majorSign && this.updateParams.majorSign.includes(0),
                value: 1
            }, {
                name: "重大监管化工工艺",
                disable: this.updateParams.majorSign && this.updateParams.majorSign.includes(0),
                value: 2
            }, {
                name: "重点监管危化品",
                disable: this.updateParams.majorSign && this.updateParams.majorSign.includes(0),
                value: 3
            }],
        }, {
            name: "重大危险源",
            key: "majorHazard",
            hide: (!this.updateParams.majorSign) || (this.updateParams.majorSign && (this.updateParams.majorSign.length === 0 || !this.updateParams.majorSign.includes(1) || this.updateParams.majorSign.includes(0))),
            type: "select",
            format: "majorHazardName",
            width: "calc(50% - 20px)",
            require: true,
            // multiple: true,
            datas: this.$store.state.prevention_risk_source,
            showError: false,

        }, {
            name: "重点监管工艺",
            key: "regulatoryProcess",
            format: "regulatoryProcessName",
            hide: (!this.updateParams.majorSign) || (this.updateParams.majorSign && (this.updateParams.majorSign.length === 0 || !this.updateParams.majorSign.includes(2) || this.updateParams.majorSign.includes(0))),
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            // multiple: true,
            datas: this.$store.state.prevention_risk_craft,
            showError: false,
        }, {
            name: "重点监管化学品",
            key: "regulatoryChemical",
            format: "regulatoryChemicalName",
            hide: (!this.updateParams.majorSign) || (this.updateParams.majorSign && (this.updateParams.majorSign.length === 0 || !this.updateParams.majorSign.includes(3) || this.updateParams.majorSign.includes(0))),
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            // multiple: true,
            datas: this.$store.state.prevention_risk_chemical,
            showError: false,
        }];

        this.subTableActions = [{
            name: "批量删除",
            value: "subDelete",
            plain: true,
            icon: "el-icon-delete",
            type: "danger"
        }, {
            name: "评估矩阵",
            value: "estimateMatrix",
            type: "primary"
        }];
        this.subBasicRiskOptions = [{
            name: "风险等级",
            key: "riskLevel",
            format: 'riskLevelName',
            type: "select",
            require: true,
            width: "calc(50% - 20px)",
            disable: true,
            showError: false,
            datas: this.$store.state.prevention_risk_level
        }, {
            name: "残余风险等级",
            key: "remainRiskLevel",
            format: "remainRiskLevelName",
            type: "select",
            require: true,
            width: "calc(50% - 20px)",
            disable: true,
            showError: false,
            datas: this.$store.state.prevention_risk_level
        }]
    }


    public updateActions = [] as any;
    public buildActionsForm() {
        this.updateActions = [{
            name: "取消",
            value: "cancel"
        }, {
            name: '存草稿',
            value: 'addDraft',
            type: "primay",
            hide: !this.updateParams.status || this.updateParams.status === 1 ? false : true
        }, {
            name: "保存并继续添加",
            value: "storeAndContinue",
            type: "primary",
            hide: this.updateParams.id ? true : false
        }, {
            name: "保存",
            value: "store",
            type: "primary"
        }];
    }

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

    @Watch("updateParams", { immediate: true, deep: true })
    onCountValueChange() {
        this.buildUpdateForm()
    }


    created() {
        //
    }

    // 加载区域列表
    public loadAreaData() {

        this.unitList = [];
        this.jobList = [];
        this.tableService.getDistinctList({}).then((res: any) => {
            this.areaList = res.data.map(item => {
                return {
                    name: item.areaName,
                    value: item.areaId,
                    analRiskLevel: item.analRiskLevel ? item.analRiskLevel : null,
                }
            });
            this.buildUpdateForm()
        })
    }
    // 加载单元列表
    public loadUnitData(id?) {
        this.tableService.getDistinctList({ areaId: id }).then((res: any) => {
            this.unitList = res.data.map(item => {
                return {
                    name: item.unitName,
                    value: item.unitId,
                    deptId: item.chargeDeptId,
                    deptName: item.chargeDeptName,
                    userId: item.chargeUserId,
                    userName: item.chargeUserName,
                }
            });
            this.buildUpdateForm()
        })
    }
    // 树点击
    public handleNodeClick(data) {
        this.params.unitName = "";
        this.params.areaName = "";
        if (data.areaId) {
            this.params.unitName = data.name
        } else {
            this.params.areaName = data.name === "全部" ? "" : data.name
        }
        this.getTableData()

    }

    public buildTable() {
        this.tableColumn.push({ name: '区域名称', key: "areaName", width: "150px" });
        this.tableColumn.push({ name: '风险分析单元', key: "unitName", width: "150px" });
        this.tableColumn.push({ name: '作业活动', key: "jobInventoryName", });
        this.tableColumn.push({
            name: '作业步骤', key: "stepNum", render: (data) => {
                return "<span class='link'>" + (data.stepNum ? data.stepNum : 0) + "</span>"
            }
        });
        this.tableColumn.push({ name: '责任部门', key: "chargeDeptName" });
        this.tableColumn.push({ name: '责任人', key: "chargeUserName" });
        this.tableColumn.push({
            name: '风险等级', key: "riskLevel", width: "150px", 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;
            }
        });
        this.tableColumn.push({
            name: '残余风险等级', key: "remainRiskLevel", width: "150px", render: (data) => {
                return "<span class='color_level_" + data.remainRiskLevel + "'>" + (data.remainRiskLevel ? (this.$store.getters.prevention_risk_level_map[data.remainRiskLevel]) : '') + "</span>"
            }
        });
        this.tableColumn.push({
            name: '状态', key: "status", render: (data) => {
                if (data.status) {
                    let tmpstatus: any = data.status
                    if (data.status === 1) {
                        tmpstatus = 2
                    } else if (data.status === 2) {
                        tmpstatus = 1
                    }
                    return "<span class='color_" + tmpstatus + "'>" + (data.status ? (this.$store.getters.prevention_evaluate_status_map[data.status]) : '') + "</span>"
                }
            },
            filters: this.$store.state.prevention_evaluate_status.map(item => {
                return {
                    text: item.name,
                    value: item.value,
                }
            }), filterMethod: (data, row) => {
                return row.status === data;
            }
        });


        //分析评价
        this.subTableColumn.push({ name: '序号', key: "index", width: "50px" });
        this.subTableColumn.push({
            name: '状态', key: "status", width: "80px", render: (data) => {
                if (data.status && data.status !== 1) {
                    let tmpstatus: any = data.status
                    if (data.status === 2) {
                        tmpstatus = 1
                    }
                    if (data.status) {
                        return "<span class='color_" + tmpstatus + "'>" + (data.status ? (this.$store.getters.prevention_evaluate_status_map[data.status]) : '') + "</span>"
                    }
                }
            }
        });
        this.subTableColumn.push({ name: '步骤名称', key: "name" });
        this.subTableColumn.push({ name: '作业步骤描述', key: "description", showTip: true, width: "200px" });
        this.subTableColumn.push({ name: '作业地点', key: "location" }); this.subTableColumn.push({ name: '风险源', key: "riskSource" });
        this.subTableColumn.push({ name: '危害分析', key: "hazardAnalysis", width: "200px" });
        this.subTableColumn.push({
            name: '最严重后果', key: "seriousResult", width: "100px", render: (data) => {
                if (data.seriousResult) {
                    return data.seriousResult.split(",").map(item => this.$store.getters.prevention_serious_result_map[item]).join(",")
                }
            }
        });
        this.subTableColumn.push({
            name: '风险等级', key: "riskLevel", width: "100px", render: (data) => {
                if (data.riskLevel) {
                    return this.$store.getters.prevention_risk_level_map[data.riskLevel]
                }
            }
        });
        this.subTableColumn.push({ name: '评估方法', key: "riskChoose", width: "100px", });
        this.subTableColumn.push({
            name: '残余风险等级', key: "remainLevel", width: "130px", render: (data) => {
                if (data.remainLevel) {
                    return this.$store.getters.prevention_risk_level_map[data.remainLevel]
                }
            }
        });
        this.subTableColumn.push({ name: '评估方法', key: "remainChoose", });
        this.subTableColumn.push({
            name: '管控措施', key: "measuresNum", render: (data) => {
                if (data.measuresNum) {
                    return data.measuresNum
                } else {
                    if (data.measures && data.measures.length) {
                        return data.measures.length
                    }

                }
            }
        });

        //作业步骤
        this.proTableColumn.push({ name: '序号', key: "index", width: "80px" });
        this.proTableColumn.push({ name: '步骤名称', key: "name" });
        this.proTableColumn.push({ name: '作业步骤描述', key: "description", showTip: true, width: "200px" });
        this.proTableColumn.push({ name: '作业地点', key: "location" });
        this.proTableColumn.push({ name: '风险源', key: "riskSource", width: "100px", });
        this.proTableColumn.push({
            name: '可能发生事故', key: "seriousResult", width: "130px", render: (data) => {
                if (data.seriousResult) {
                    return data.seriousResult.split(",").map(item => this.$store.getters.prevention_serious_result_map[item]).join(",")
                }
            }
        });
        this.proTableColumn.push({
            name: '风险等级', key: "riskLevel", width: "100px", 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.proTableColumn.push({
            name: '残余风险等级', key: "remainLevel", width: "120px", render: (data) => {
                if (data.remainLevel) {
                    return "<span class='color_level_" + data.remainLevel + "'>" + (data.remainLevel ? (this.$store.getters.prevention_risk_level_map[data.remainLevel]) : '') + "</span>"
                }
            }
        });
    }


    public callback(data, type) {
        if (type) {
            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.isReadonly = false;
            this.isModifyonly = false;
            this.showUpdate = true
            this.jobList = []
            this.unitList = []
            this.updateParams = {
                majorSign: [],
                items: [],
                evaluateTime: moment().format('YYYY-MM-DD'),
                evaluateUserId: this.account.userId,
                evaluateUserName: this.account.nickName,
            } as any
            this.buildActionsForm()
        } else if (data.value === "cancel") {
            this.handleClose()
            //评估矩阵
        } else if (data.value === "estimateMatrix") {
            this.showMatrixModal = true
            //保存
        } else if (data && data.value.indexOf("store") >= 0) {
            this.doSave(data.value !== "store")
            this.isReadonly = false;
            //存草稿
        } else if (data && data.value === 'addDraft') {
            this.doSaveDraft()
            this.isReadonly = false;
            //工作危害分析的删除
        } else if (data && data.value === "subDelete") {
            if (this.subSelectData.length > 0) {
                this.$confirm('确认删除所选数据', '确认数据', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if (!this.updateParams.deleteIds) {
                        this.updateParams.deleteIds = []
                    }
                    this.subSelectData.map((itemData: any) => {
                        this.updateParams.deleteIds.push(itemData.id)
                        this.updateParams.steps.splice(this.updateParams.steps.findIndex(item => item.index === itemData.index), 1)
                    })
                    //分析步骤添加序号
                    this.addStepsIndex()
                    this.updateParams.stepNum = this.updateParams.steps.length
                }).catch(() => {
                    //
                });
            }
        }
    }

    // 重置数据
    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 changes(data, item) {
        // 区域
        if (item && item.key === "areaId") {
            this.jobList = [];
            if (this.updateParams.unitId) {
                this.updateParams.unitId = null;
            }
            const areaData = this.areaList.find((itm: any) => itm.value === data) as any;
            //区域数据
            this.initAreaParamMethod(areaData);
            //区域关联数据初始化
            this.initParamMethod();
            //关联单元
            this.loadUnitData(data)
        }
        //单元
        if (item && item.key === 'unitId') {
            const unitData = this.unitList.find((itm: any) => itm.value === data) as any;
            //单元数据
            this.initUnitParamMethod(unitData);
            //单元关联数据初始化
            this.initParamMethod();
            //关联作业活动
            this.loadJobData(data)

        }
        //作业清单
        if (item && item.key === 'jobInventoryId') {
            const jobData = this.jobList.find((itm: any) => itm.value === data) as any;
            //作业活动
            this.initJobParamMethod(jobData)
        }
        //是否为两大一重
        //多选 选中不涉及时，其他三项不可选中
        if (item && item.key === 'majorSign') {
            if (!data) {
                data = []
            }
            if (this.updateParams.majorSign.includes(0)) {
                this.updateParams.majorSign = this.updateParams.majorSign.filter(item => item === 0)
                data = this.updateParams.majorSign.filter(item => item === 0)
            }

        }
        this.buildUpdateForm()
    }
    //加载作业清单列表
    public loadJobData(id?) {
        this.tableService.selectWorkByUnit({ unitId: id, id: this.updateParams.id ? this.updateParams.id : null }).then((res: any) => {
            this.jobList = res.data.map(item => {
                return {
                    name: item.name,
                    value: item.id,
                    location: item.location,
                    postCode: item.postCode,
                    postName: item.postName,
                    steps: item.steps,
                    stepNum: item.stepNum
                }
            });
            this.buildUpdateForm()
        })
    }
    //区域数据
    public initAreaParamMethod(areaData: any) {
        this.updateParams.analRiskLevel = areaData.analRiskLevel;
        this.updateParams.chargeDeptName = null;
        this.updateParams.chargeUserId = null;
        this.updateParams.chargeUserName = null;
        this.updateParams.chargeDeptId = null;
    }

    //单元数据
    public initUnitParamMethod(unitData: any) {
        this.updateParams.chargeDeptName = unitData.deptName;
        this.updateParams.chargeUserId = unitData.userId;
        this.updateParams.chargeUserName = unitData.userName;
        this.updateParams.chargeDeptId = unitData.deptId;
    }

    //作业活动数据
    public initJobParamMethod(jobData: any) {
        this.updateParams.location = jobData.location;
        this.updateParams.postCode = jobData.postCode;
        this.updateParams.postName = jobData.postName;
        this.updateParams.steps = jobData.steps;
        this.updateParams.jobInventoryName = jobData.name;
        this.updateParams.stepNum = jobData.steps.length;
        this.updateParams.steps.forEach((item, i) => {
            item.index = i + 1
        })
    }
    //区域单元切换，数据初始化
    public initParamMethod() {
        this.updateParams.type = null;
        this.updateParams.postName = null;
        this.updateParams.postCode = null;
        this.updateParams.jobInventoryName = null;
        this.updateParams.jobInventoryId = null;
        this.updateParams.name = null;
        this.updateParams.location = null;
        this.updateParams.steps = [];
        this.updateParams.stepNum = 0;
    }
    //作业步骤
    public showPros(el, data) {
        const isTarget = el.target.classList.contains("link");
        if (isTarget) {
            this.seriousResultMap = this.$store.getters.prevention_serious_result_map;
            this.riskLevelMap = this.$store.getters.prevention_risk_level_map;
            this.currentId = data.id;
            this.tableService.selectStepById({ jobAnalId: this.currentId }).then((res: any) => {
                if (res.code === 200) {
                    this.showProtable = true;
                    this.currentProTableData.datas = res.data.map((item, index) => {
                        item.index = index + 1;
                        return item
                    })
                }
            })
        }
    }

    //作业步骤--关闭
    public proCallback() {
        this.showProtable = false;
    }
    //评价信息
    public showUpdateModel(row, isReadonly, isModifyonly) {
        this.updateParams = { majorSign: [], steps: [], } as any;
        if (!row) {
            this.currentId = -1;
            this.showUpdate = true;
        } else {
            this.currentId = row.id;
            this.tableService.selectById(this.currentId).then((res: any) => {
                if (isReadonly) {
                    //select项翻译
                    this.readonlyParamTransform(res);
                    //分析步骤添加序号
                    this.addStepsIndex()
                    this.isReadonly = true;
                    this.isModifyonly = false
                } else {
                    this.isReadonly = false
                    this.isModifyonly = true
                    this.updateParams = res.data;
                    //对select进行转换
                    this.updateParamTransform(res);
                    //获取区域固有风险等级
                    this.getAreaRiskLevel(res);
                    //加载区域
                    this.loadUnitData(res.data.areaId)
                    //加载单元
                    this.loadJobData(res.data.unitId)
                    //分析步骤添加序号
                    this.addStepsIndex()
                }

                this.buildUpdateForm();
                this.buildActionsForm();
                this.showUpdate = true;
            })
        }
    }



    //查看，select项翻译
    public readonlyParamTransform(res: any) {
        const areaAnalRiskLevel = this.areaList.filter((item) => item.value === res.data.areaId)[0]['analRiskLevel'];
        const majorHazard = res.data.majorHazard ? parseInt(res.data.majorHazard) : null;
        const regulatoryProcess = res.data.regulatoryProcess ? parseInt(res.data.regulatoryProcess) : null;
        const regulatoryChemical = res.data.regulatoryChemical ? parseInt(res.data.regulatoryChemical) : null;
        this.updateParams = Object.assign({
            majorHazardName: majorHazard || majorHazard === 0 ? this.$store.getters.prevention_risk_source_map[majorHazard] : null,
            regulatoryProcessName: regulatoryProcess || regulatoryProcess === 0 ? this.$store.getters.prevention_risk_craft_map[regulatoryProcess] : null,
            regulatoryChemicalName: regulatoryChemical || regulatoryChemical === 0 ? this.$store.getters.prevention_risk_chemical_map[regulatoryChemical] : null,
            majorSignName: !res.data.majorSign ? null : res.data.majorSign.split(",").map(item => this.$store.getters.prevention_majorsign_map[item]).join(","),
            riskLevelName: this.$store.getters.prevention_risk_level_map[res.data.riskLevel],
            remainRiskLevelName: this.$store.getters.prevention_risk_level_map[res.data.remainRiskLevel],
            typeName: this.$store.getters.prevention_device_type_map[res.data.type],
            analRiskLevelName: this.$store.getters.prevention_risk_level_map[areaAnalRiskLevel]
        }, res.data);
    }

    //编辑对select进行转换
    public updateParamTransform(res: any) {
        this.updateParams.majorSign = res.data.majorSign ? this.stringChangeArray(res.data.majorSign) : [];
        this.updateParams.majorHazard = res.data.majorHazard ? parseInt(res.data.majorHazard) : null;
        this.updateParams.regulatoryProcess = res.data.regulatoryProcess ? parseInt(res.data.regulatoryProcess) : null;
        this.updateParams.regulatoryChemical = res.data.regulatoryChemical ? parseInt(res.data.regulatoryChemical) : null;
    }

    //获取区域固有风险等级
    public getAreaRiskLevel(res: any) {
        if (this.areaList.length > 0) {
            let tmpAnalRiskLevel = this.areaList.filter((item) => item.value === res.data.areaId);
            if (tmpAnalRiskLevel.length > 0) {
                const areaAnalRiskLevel = this.areaList.filter((item) => item.value === res.data.areaId)[0]['analRiskLevel'];
                this.updateParams.analRiskLevel = areaAnalRiskLevel;
            }
        }
    }

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

    public workHandleClose() {
        this.showProtable = false;
    }

    public handleAnalyClose() {
        this.showSubUpdate = false;
    }

    //保存 更新
    public doSave(goOn?) {
        let judgmentStatus = false as any;
        this.updateParams.steps.forEach((item) => {
            if (!item.status) {
                judgmentStatus = true
            }
        })
        if (judgmentStatus === true) {
            this.$message.error("您有评价项未评价，请您先完成评价！");
            return
        }
        // 如果是新增工作危害分析清单
        //对数据进行处理
        if ((this.$refs.basicForm as any).vaildParams()) {
            if ((this.$refs.riskForm as any).vaildParams()) {
                this.saveTransformData();

                this.tableService.addOrUpdate(this.updateParams, !this.updateParams.id || this.updateParams.status === 1 ? true : false).then((res) => {
                    this.$message.success(!this.updateParams.id ? "新增成功！" : "编辑成功！");
                    this.showUpdate = !!goOn;
                    this.updateParams = {
                        majorSign: [],
                        steps: [],
                        evaluateTime: moment().format('YYYY-MM-DD'),
                        evaluateUserId: this.account.userId,
                        evaluateUserName: this.account.nickName,
                    } as any;
                    this.buildUpdateForm();
                    this.getTableData();
                })
            }
        }
    }


    //存草稿
    public doSaveDraft() {
        // 如果是新增工作危害分析清单
        //对数据进行处理
        this.saveTransformData();
        this.tableService.addOrDraft(this.updateParams, !this.updateParams.id).then((res) => {
            this.$message.success(!this.updateParams.id ? "新增成功！" : "编辑成功！");
            this.showUpdate = false;
            this.updateParams = {
                majorSign: [],
                steps: [],
                evaluateTime: moment().format('YYYY-MM-DD'),
                evaluateUserId: this.account.userId,
                evaluateUserName: this.account.nickName,
            } as any;
            this.buildUpdateForm();
            this.getTableData();
        })
    }
    //保存处理数据
    public saveTransformData() {
        this.updateParams.majorSign = this.arrayChangeString(this.updateParams.majorSign);
        this.updateParams.regulatoryProcess = this.numberChangeString(this.updateParams.regulatoryProcess);
        this.updateParams.regulatoryChemical = this.numberChangeString(this.updateParams.regulatoryChemical);
        this.updateParams.majorHazard = this.numberChangeString(this.updateParams.majorHazard);
        this.updateParams.safetyFactor = this.arrayChangeString(this.updateParams.safetyFactor);
    }

    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 handleSubSelectionChange(data) {
        this.subSelectData = data
    }

    //分析评价
    public showSubModel(row, isReadonly) {
        this.analysisUpdateParams = {
            riskChoose: [],
            remainChoose: [],
        } as any;
        if (row) {
            if (isReadonly) {
                this.analyIsReadonly = true;
                //select 翻译
                this.analysisTransformParam(row);
                this.analysisUpdateParams = { ...this.analysisUpdateParams, ...JSON.parse(JSON.stringify(row)) };
                //管控措施
                this.initAnalysisMeasure();
            } else {
                this.analyIsReadonly = false
                // 暂存数据 用于取消修改
                this.analysisUpdateParams = { ...this.analysisUpdateParams, ...JSON.parse(JSON.stringify(row)) };
                //编辑 参数处理
                this.updateAnalysisParam(row);
                //管控措施
                this.initAnalysisMeasure();

            }
        }
        this.showSubUpdate = true
    }

    //工作危害分析法 查看翻译
    public analysisTransformParam(row: any) {
        this.analysisUpdateParams = Object.assign({
            seriousResultName: row.seriousResult.split(",").map(item => this.$store.getters.prevention_serious_result_map[item]).join(","),
            safetySignName: row.safetySign.split(",").map(item => this.$store.getters.prevention_security_identifier_map[item]).join(","),
            riskLevelName: this.$store.getters.prevention_risk_level_map[row.riskLevel],
            remainLevelName: this.$store.getters.prevention_risk_level_map[row.remainLevel],
            riskControlLevelName: this.$store.getters.prevention_control_level_map[row.riskControlLevel],
        }, row);
    }
    //分析法编辑 数据处理
    public updateAnalysisParam(row: any) {
        this.analysisUpdateParams.seriousResult = this.stringChangeArray(row.seriousResult);
        this.analysisUpdateParams.safetySign = this.stringChangeArray(row.safetySign);
        this.analysisUpdateParams.riskChoose = row.riskChoose ? row.riskChoose.split(",") : [];
        this.analysisUpdateParams.remainChoose = row.remainChoose ? row.remainChoose.split(",") : [];
        this.analysisUpdateParams.chargeUserName = this.updateParams.chargeUserName;
        this.checkRiskType.risk = this.analysisUpdateParams.riskChoose;
        this.checkRiskType.remain = this.analysisUpdateParams.remainChoose;
    }
    //管控措施初始化
    public initAnalysisMeasure() {
        if (!this.analysisUpdateParams.measures) {
            this.analysisUpdateParams.measures = [];
        }
        this.analysisUpdateParams.measures.forEach((item, index) => {
            item.index = index + 1;
            return item;
        });
    }

    //数组转字符串
    public arrayChangeString(data) {
        if (data && data.length > 0) {
            if (data instanceof Array) {
                return data.join(",")
            } else {
                return data
            }
        } else {
            return null
        }
    }

    //字符串转数组
    public stringChangeArray(data) {
        if (data) {
            return data.split(",").map((item) => parseInt(item))
        }
    }

    //数字转字符串
    public numberChangeString(data) {
        if (data || data === 0) {
            return data.toString()
        } else {
            return null
        }
    }

    //工作危害分析步骤 add 序号
    public addStepsIndex() {
        this.updateParams.steps.forEach((item, i) => {
            item.index = i + 1
            return item
        })
    }

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

    .el-step__line {
        background-color: #409EFF;
        text-align: center;
    }

    .el-step.is-vertical .el-step__head {
        width: 64px;
        text-align: center;
    }

    .el-step__icon.is-text {
        width: 64px;
        background: #409EFF;
        border-radius: 4px;
        color: #fff;
        border: 0px;
        font-size: 12px;
    }

    .el-step__description {
        padding-right: 20px;
    }

    .el-step.is-vertical .el-step__main {
        padding-left: 16px;
    }

    .el-step.is-vertical .el-step__title {
        font-size: 16px;
        font-weight: 500;
        color: #409EFF;
        padding-bottom: 16px;
        display: flex;
        justify-content: space-between;
    }

    .el-step.is-vertical .el-step__line {
        left: 32px;
        opacity: 0.3;
    }

    .description {
        .el-textarea.is-disabled .el-textarea__inner {
            background: rgba(64, 158, 255, 0.05) !important;
        }

        .el-textarea__inner {
            font-size: 14px !important;
            font-weight: 400 !important;
            color: rgba(0, 0, 0, 0.6) !important;
            background: rgba(64, 158, 255, 0.05) !important;
            border-radius: 4px;
            border-color: #fff !important;
            padding: 16px;
        }
    }

    .basic-content {
        padding: 18px 0px;
        font-size: 14px;
        font-weight: 500;
        color: rgba(0, 0, 0, 0.3);
        display: flex;
        justify-content: flex-start;

        .content-item {
            width: 24%;

            span {
                color: rgba(0, 0, 0, 0.6);
            }
        }
    }

    .end-step {
        .el-step__head.is-wait {
            height: 9px !important;
        }

        .el-step__icon.is-text {
            width: 9px;
            height: 9px;
            background: #C5E1FF;
            border-radius: 50%;
            margin-left: 2px;
            margin-bottom: 6px;
        }
    }

    .end-title {
        height: 17px;
        font-size: 12px;
        font-weight: 500;
        color: #C5E1FF;
        line-height: 17px;
        padding-left: 22px;
        margin-bottom: 20px;
    }

    .add-steps-btn {
        width: 100%;
        text-align: center;
        height: 40px;
        background: #ECF5FF;
        border-radius: 4px;
        border: 1px solid #409EFF;
        line-height: 40px;
        color: #409EFF;
        cursor: pointer;
        margin: 0px 20px 20px 20px;
    }

    .modify-img {
        background: #409EFF;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        cursor: pointer;
    }

    .delete-img {
        width: 24px;
        height: 24px;
        margin-left: 20px;
        margin-right: 20px;
        cursor: pointer;
    }
}
</style>
