
<script lang="ts">
import { Component } from 'vue-property-decorator';
import template from "./safe.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 AreaService from "@/service/area.service"
import FormOption from "hbt-common/models/formOptions"
import BtnOption from "hbt-common/models/btnOptions"
import DrawComponent from '@/components/draw.component.vue';
import WorkFlowService from "@/service/workFlow.service"
import TaskService from '@/service/task.service';
import MapComponent from "@/components/map.component.vue"
import mapboxgl from "mapbox-gl";
import moment from 'moment';
@Component({
    template,
    components: {
        FormComponent,
        TableComponent,
        DrawComponent,
        MapComponent
    },
})
export default class RulesManagerComponent extends BaseRecordComponent<any> {
    public tableService = new TaskService();
    public workFlowService = new WorkFlowService();

    public isAction = true;
    // 显示计划列表按钮
    public isPlan = false;
    public tableActionWidth = "80px";
    public statusList = ["", "检查中", "已检查", "待检查", "超期未检查"];
    public account = JSON.parse(localStorage.getItem("account") as string);
    // 是否隐藏隐患登记情况
    public hideActions = false;

    public nowDate = moment().format("YYYY-MM-DD HH:mm:ss")
    public params = {} as any;

    public idReadonly = false;

    public formActions = [{
        name: "查询",
        value: "search",
        icon: "el-icon-search",
        type: "primary"
    }, {
        name: "清空",
        icon: "el-icon-tickets",
        value: "reset"
    }];
    public updateActions = [{
        name: "取消",
        value: "cancel"
    }, {
        name: "保存",
        value: "save",
        type: "primary"
    }];
    public tableActions = [];
    public footerActions = [];
    public formOptions: FormOption<BtnOption>[] = [];

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

    public showRecord = false;
    public recordParams = {
        taskId: null,
        tableId: null,
    } as any;

    public tableTabs = [] as any;

    public currentTable = {} as any;

    public currentTableId: any = null;

    public troubleTableData = [] as any;
    public selectData = [];

    public showUpdate = false;

    public showMap = false;
    public center = [118.751353, 31.969568];
    public marker: any;
    public isReadonly = false;
    public fileList = [] as any;
    public photoList = [] as any;
    public map: any;

    public showFile = false;
    public currentUrl = "";

    public levelMap = ["", "一般隐患", "重大隐患"]
    public reformModeMap = ["", "即查即改", "限期整改"]

    public riskSource = [] as any;

    public planTypeMap = {
        1: "单次计划",
        2: "长期计划"
    }

    created() {
        //重大危险源
        this.initRiskSource()
    }

    public buildTable() {
        this.tableColumn.push({ name: '检查名称', key: "planName" });
        this.tableColumn.push({
            name: '检查类型', render: (data) => {
                return this.$store.getters.prevention_danger_check_type_map[data.inspectType]
            }
        });
        this.tableColumn.push({ name: '检查对象', key: "analControlNames" });
        this.tableColumn.push({ name: '检查执行时间', key: "checkTime" });
        this.tableColumn.push({ name: '检查负责人', key: "chargeUserName" });
        this.tableColumn.push({
            name: '检查表', key: "tableNum", render: (data) => {
                return "<span class='text_link'>" + (data.tableNum || 0) + "</span>"
            }
        });
        this.tableColumn.push({ name: '开始时间', key: "taskStartTime", width: "180px" });
        this.tableColumn.push({
            name: '截止时间', key: "taskEndTime", width: "180px", render: (data) => {
                if (data.inspectCycleUnit && data.inspectCycleValue) {
                    return this.taskEndTime(data.taskStartTime, data.inspectCycleValue, data.inspectCycleUnit)
                } else {
                    return data.taskEndTime
                }

            }
        });
        this.tableColumn.push({
            name: '计划类型', render: (data) => {
                return this.planTypeMap[data.planType]
            }
        });
        this.tableColumn.push({
            name: '检查周期', key: "inspectCycleValue", render: (data) => {
                return !data.inspectCycleValue ? '--' : data.inspectCycleValue
            }
        });
        this.tableColumn.push({
            name: '单位', render: (data) => {
                return !data.inspectCycleUnit ? '--' : this.$store.getters.prevention_cycle_unit_map[data.inspectCycleUnit]
            }
        });
        this.tableColumn.push({
            name: '状态', filters: [{
                text: "检查中",
                value: 1
            }, {
                text: "已检查",
                value: 2
            }, {
                text: "待检查",
                value: 3
            }, {
                text: "超期未检查",
                value: 4
            }], filterMethod: (data, row) => {
                return row.status === data
            }, key: "status", render: (data) => {
                if (data.status === 3) {
                    const now = moment().format("YYYY-MM-DD HH:mm:ss");
                    if (now > data.taskStartTime) {
                        return "<span class='color_2'>" + (this.statusList[data.status] || '') + "</span>"
                    } else {
                        return "即将开始"
                    }
                } else {
                    let color = "color_1"
                    if (data.status === 1) {
                        color = "color_3"
                    } else if (data.status === 4) {
                        color = "color_4"
                    }
                    return "<span class='" + (color) + "'>" + (this.statusList[data.status] || '') + "</span>"
                }
            }
        });
    }

    public getTableCallback() {
        this.formOptions = [{
            name: "检查名称",
            key: "planName",
            type: "text",
        }, {
            name: "检查类型",
            key: "inspectType",
            type: "select",
            datas: this.$store.state.prevention_danger_check_type
        },{
            name:"检查负责人",
            key: "chargeUserId",
            type: "select",
            datas: this.$store.state.userList
        }];
        this.updateOptions = [{
            name: "隐患编号",
            key: "number",
            disable: true,
            width: "100%",
            require: true,
            showError: false,
            type: "text"
        }, {
            name: "隐患标题",
            key: "title",
            width: "100%",
            require: true,
            showError: false,
            type: "text"
        }, {
            name: "隐患描述",
            width: "100%",
            key: "description",
            require: true,
            showError: false,
            type: "textarea"
        }, {
            name: "隐患级别",
            key: "level",
            format: "levelName",
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            datas: [{
                name: "一般隐患",
                value: 1
            }, {
                name: "重大隐患",
                value: 2
            }]
        }, {
            name: "整改方式",
            key: "reformMode",
            format: "reformModeName",
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            datas: [{
                name: "即查即改",
                value: 1
            }, {
                name: "限期整改",
                value: 2
            }]
        }, {
            name: "隐患位置",
            key: "locationName",
            type: "text",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            unit: {
                type: "btn",
                name: this.isReadonly ? "查看定位" : "点击定位",
                value: "fixed",
                btnType: "primary"
            }
        }, {
            name: "隐患分类",
            key: "classify",
            format: "classifyName",
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            datas: this.$store.state.prevention_dangrous_type
        }, {
            name: "整改部门",
            key: "reformDeptId",
            format: "reformDeptName",
            type: "treeSelect",
            width: "calc(50% - 20px)",
            require: true,
            expandLevel: Infinity,
            showError: false,
            datas: this.$store.state.deptTreeList
        }, {
            name: "整改责任人",
            key: "reformUserId",
            format: "reformUserName",
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            datas: this.$store.state.userList,
        }, {
            name: "验证人",
            key: "verifyUserId",
            format: "verifyUserName",
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            datas: this.$store.state.userList,
        }, {
            name: "整改时限",
            key: "reformDeadline",
            type: "date",
            subType: "datetime",
            format: "yyyy-MM-dd HH",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            pickerOptions: {
                disabledDate(time: any) {
                    return time.getTime() < moment().subtract(1, 'day').valueOf();
                }
            }
        }, {
            name: "隐患类别",
            key: "dangerType",
            format: "dangerTypeName",
            type: "select",
            width: "100%",
            require: true,
            showError: false,
            datas: this.$store.state.prevention_danger_type,
        }, {
            name: "隐患照片",
            key: "photo",
            ref: "photo",
            type: "upload",
            width: "calc(50% - 20px)",
            require: true,
            onSucess: this.onSuccess,
            onMove: this.onRemove,
            showError: false,
            autoUpload: true,
            onPreview: this.onPreview,
            accept: "image/png, image/jpeg",
            listType: "picture-card",
            fileList: this.photoList,
            icon: "el-icon-plus",
        }, {
            name: "相关附件",
            key: "file",
            ref: "file",
            type: "upload",
            width: "calc(50% - 20px)",
            showError: false,
            onSucess: this.onSuccess2,
            onMove: this.onRemove2,
            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: "violateNumber",
            type: "number",
            width: "calc(50% - 20px)",
            showError: false,
            rules: [
                { pattern: /^([1-9][0-9]{0,1}|100)$/, message: '在1~100范围内', }
            ],
            min: 1,
            max: 100,
        }, {
            name: "专业分类",
            key: "professionClassify",
            format: "professionClassifyName",
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            datas: this.$store.state.prevention_major_type,
        }, {
            name: "属性分类",
            key: "attributeClassify",
            format: "attributeClassifyName",
            type: "select",
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.prevention_safe_reason,
        }, {
            name: "发生环节",
            key: "occurNode",
            format: "occurNodeName",
            type: "select",
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.prevention_occur_step,
        }, {
            name: "违反规定条款",
            key: "violateTerm",
            type: "textarea",
            width: "100%",
            showError: false,
        }, {
            name: "隐患整改要求",
            key: "reformDemand",
            type: "textarea",
            width: "100%",
            showError: false,
        }, {
            name: "重大危险源名称",
            key: "majorHazard",
            format: "majorHazardName",
            type: "select",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
            datas: this.riskSource
        },]
    }

    //重大危险源
    public initRiskSource() {
        this.riskSource = [] as any;
        this.riskSource = JSON.parse(JSON.stringify(this.$store.state.prevention_risk_source));
        this.riskSource.unshift({
            name: '不涉及',
            value: 0,
        })
        this.getTableCallback()
    }

    //截止时间计算
    // 开始时间 + 周期（周期单位） - 一天
    public taskEndTime(begindate, inspectCycleValue, inspectCycleUnit) {
        let unitData = this.transformDate(inspectCycleUnit)
        if (unitData) {
            if (unitData === 'halfyear') {
                return moment(begindate).add(inspectCycleValue * 6, 'months').format('YYYY-MM-DD HH:mm:ss')
            } else {
                return moment(begindate).add(inspectCycleValue, unitData).format('YYYY-MM-DD HH:mm:ss')
            }
        }
    }

    //周期单位转换
    public transformDate(unit) {
        switch (unit) {
            case '1':
                return 'year';
            case '2':
                return 'halfyear';
            case '3':
                return 'quarters';
            case '4':
                return 'months';
            case '5':
                return 'weeks';
            case '6':
                return 'days';
            case '7':
                return 'hours';
        }
    }

    public change(data, item) {
        if (item && item.key === "inspectUserId") {
            this.updateParams.inspectUserName = this.$store.getters.user_map[data]
        }
        if (item && item.key === "reformDeptId") {
            this.updateParams.reformDeptName = this.$store.getters.dept_map[data]
        }
        if (item && item.key === "reformUserId") {
            this.updateParams.reformUserName = this.$store.getters.user_map[data]
        }
        if (item && item.key === "verifyUserId") {
            this.updateParams.verifyUserName = this.$store.getters.user_map[data]
        }
        if (item && item.key === "reformDeadline") {
            const now = moment().format("YYYY-MM-DD HH");
            if (now > data) {
                this.$message.error("整改时限不能早于当前时间")
                this.updateParams.reformDeadline = null;
                return
            }
        }
    }


    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));
            setTimeout(() => {
                this.getTroubleList()
            })
        } else if (data.value === "fixed") {
            this.showMap = true

        } else if (data.value.indexOf("save") >= 0) {
            this.doSave();
        } else {
            this.handleClose()
        }
    }

    public deleteData(ids) {
        if (!ids.length) {
            return
        } else {
            this.$confirm("确认删除所选数据？", "确认数据", {
                type: 'warning'
            }).then(() => {
                this.tableService.deleteByIds(ids, true).then((res: any) => {
                    this.$message.success("删除成功！");
                    this.getTroubleList();
                })
            }).catch(() => {
                //
            })
        }
    }

    public doSave() {
        this.updateParams.resourceId = this.photoList.map(item => item.id).join(",")
        this.updateParams.resourceName = this.photoList.map(item => item.name).join(",")
        this.updateParams.resourceOtherId = this.fileList.map(item => item.id).join(",")
        this.updateParams.resourceOtherName = this.fileList.map(item => item.name).join(",")
        this.updateParams.majorHazard = this.updateParams.majorHazard.toString()
        this.tableService.addOrUpdate(this.updateParams, !this.updateParams.id).then((res: any) => {
            this.$message.success(!this.updateParams.id ? "新增成功！" : "编辑成功");
            this.handleClose();
            this.getTroubleList();
        })
    }
    // 重置数据
    public reset() {
        this.params = {
            pageNum: 1,
            pageSize: 20,
        } as any;
        this.getTableData()
    }

    public getMap(map) {
        this.map = map;
        this.addMarker();
    }
    public addMarker() {
        this.marker = new mapboxgl.Marker({ draggable: !this.isReadonly })
            .setLngLat(this.center)
            .addTo(this.map);
        this.map.flyTo({ center: this.center })
    }

    public handleClose() {
        if (this.showMap) {
            this.showMap = false;
            this.marker.remove();
            this.marker = null;
            return
        }
        if (this.showUpdate) {
            this.showUpdate = false;
            this.updateParams = {} as any;
            return
        }
        if (this.showRecord) {
            if (this.hideActions) {
                this.hideActions = false;
            }
            this.showRecord = false;
            this.recordParams = {
                taskId: null,
                tableId: null,

            }
            this.tableTabs = [];
            this.currentTable = {} as any;
            this.currentTableId = null
            return
        }
    }

    public onDragEnd() {
        const lngLat = this.marker.getLngLat();
        this.updateParams.locationLng = lngLat.lng;
        this.updateParams.locationLat = lngLat.lat;
        this.center = [lngLat.lng, lngLat.lat]
        // this.updateParams.locationName = lngLat.lng+","+lngLat.lat;
        this.handleClose()
    }


    public onSuccess(res, file, fileList) {
        if (res.code === 200) {
            this.photoList.push({
                name: res.data.originalName,
                url: res.data.url,
                type: res.data.type,
                id: res.data.id
            });
            this.updateParams.photo = this.photoList.length;
            const option = this.updateOptions.find(item => item.key === "photo") as any;
            option.showError = false
        }
    }
    public onSuccess2(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
            })
        }
    }

    public onRemove(file, fileList) {
        this.photoList.splice(this.photoList.findIndex(item => item.id === file.response.data.id), 1)
        this.updateParams.photo = this.photoList.length || null
    }
    public onRemove2(file, fileList) {
        this.fileList.splice(this.fileList.findIndex(item => item.id === file.response.data.id), 1)
    }

    public onPreview(file) {
        if (file.type.indexOf("png") >= 0 || file.type.indexOf("jp") >= 0) {
            this.currentUrl = file.url;
            this.showFile = true;
        } else {
            window.open(file.url, "_blank")
        }
    }

    public showUpdateModel(row?, isRead?) {
        this.initRiskSource()
        this.isReadonly = !!isRead;
        this.fileList = [];
        this.photoList = [];
        this.updateParams = {
            taskId: this.recordParams.taskId,
            locationName: "",
            inspectUserId: this.account.userId,
            inspectUserName: this.account.nickName,
            number: null,
            photo: null,
            dangerType: 4,
            planId: this.recordParams.planId,
            inspectTime: moment().format("YYYY-MM-DD HH:mm")
        }
        if (!row) {
            this.tableService.getNumber().then(res => {
                this.updateParams.number = res.data;
                this.center = [118.751353, 31.969568];
                this.getTableCallback();
                this.showUpdate = true;
            })
        } else {

            this.updateParams = Object.assign({
                classifyName: this.$store.getters.prevention_dangrous_type_map[row.classify],
                dangerTypeName: this.$store.getters.prevention_danger_type_map[row.dangerType],
                inspectTypeName: this.$store.getters.prevention_danger_check_type_map[row.inspectType],
                levelName: this.levelMap[row.level],
                attributeClassifyName: this.$store.getters.prevention_safe_reason_map[row.attributeClassify],
                professionClassifyName: this.$store.getters.prevention_major_type_map[row.professionClassify],
                reformModeName: this.reformModeMap[row.reformMode],
            }, row)
            this.updateParams.majorHazard = this.updateParams.majorHazard ? +this.updateParams.majorHazard : 0
            this.updateParams.majorHazardName = !this.updateParams.majorHazard ? '不涉及' : this.$store.getters.prevention_risk_source_map[this.updateParams.majorHazard]

            // 获取url
            if (row.resourceId) {
                this.updateParams.photo = row.resourceId
                this.tableService.getFileUrls({ ids: row.resourceId.split(",") }).then((photos: any) => {
                    this.photoList = photos.data.map(item => {
                        return {
                            name: item.originalName,
                            url: item.url,
                            type: item.type,
                            id: item.id
                        }
                    })
                    this.getTableCallback()
                })
            }
            if (row.resourceOtherId) {
                this.tableService.getFileUrls({ ids: row.resourceOtherId.split(",") }).then((files: any) => {
                    this.fileList = files.data.map(item => {
                        return {
                            name: item.originalName,
                            url: item.url,
                            type: item.type,
                            id: item.id
                        }
                    })
                    this.getTableCallback()
                })
            }

            this.center = [row.locationLng, row.locationLat];

            this.showUpdate = true
        }
    }


    public openRecordModel(row, isRecord?) {
        this.showRecord = true;
        this.recordParams.taskId = row.id;
        this.recordParams.planId = row.planId
        this.getTabsData(isRecord)
        this.getTroubleList();
    }

    public getTabsData(isRecord?) {
        this.tableService.getRecordTabList(this.recordParams).then((res: any) => {
            this.tableTabs = res.data.map(item => {
                return {
                    name: item.tableName,
                    id: item.tableId,
                    tableItems: []
                }
            })
            this.tableTabs.forEach(async item => {
                this.recordParams.tableId = item.id;
                const datas = (await this.tableService.getRecordList(this.recordParams)).data as any;
                item.tableItems = datas.map(subItem => {
                    subItem.userIds = subItem.itemExecuteIds ? subItem.itemExecuteIds.split(",").map(id => +id) : [];
                    // 属于自己的必填 未避免多集检索 默认正常
                    if (subItem.userIds.includes(this.account.userId)) {
                        if (!isRecord) {
                            if (!subItem.itemResult && subItem.itemResult !== 0) {
                                subItem.itemResult = 1
                            }
                        }
                    }
                    return subItem
                })
            })
            this.currentTableId = this.tableTabs[0].id;
            this.currentTable = this.tableTabs[0]
        })
    }

    public getTroubleList() {
        this.tableService.getTroubleList(this.recordParams).then((res: any) => {
            this.troubleTableData = res.data.map(data => {
                data.urls = data.resources.map(source => source.resourceUrl) || [];
                return data
            });
        })
    }

    public sendTabChange(data) {
        this.currentTable = this.tableTabs.find(item => item.id === data)
    }

    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 startWorkFlow(ids, userIds, data) {
        this.workFlowService.startWorkFlow({
            "bpmSchemeCode": "prevention-yhzl",
            "userList": userIds,
            "bizData": {
                "bizId": ids,
                "data": JSON.stringify(data)
            }
        }).then((res: any) => {
            this.getTableData()
            // 发起工作流成功
        })
    }

    public doCheck() {
        const params = [] as any;
        let total = 0;

        this.tableTabs.forEach(item => {
            total += item.tableItems.length;
            item.tableItems.forEach(subItem => {
                if (subItem.userIds.includes(this.account.userId)) {
                    params.push({
                        content: subItem.itemRecord,
                        resultFlag: subItem.itemResult,
                        taskTableId: subItem.taskTableId,
                        taskId: this.recordParams.taskId,
                        inspectUserId: this.account.userId,
                        inspectUserName: this.account.nickName,
                    })
                }
            })
        })

        this.tableService.addRecord({
            dangerInspectTaskRecords: params,
            total,
        }).then((res: any) => {
            if (res.code === 200 && res.data) {
                this.$message.success("检查成功");
                if (res.data.length) {
                    res.data.forEach((item) => {
                        this.startWorkFlow(item.id, [item.reformUserId], item)
                    })
                } else {
                    this.getTableData()
                }
                this.handleClose();
            }
        })
    }

    public rowCallback(el, data) {
        const isTarget = el.target.classList.contains("text_link");
        if (isTarget) {
            this.hideActions = true;
            this.openRecordModel(data, true)
        }

    }


}
</script>
<style lang="scss" scoped src="../../common.component.scss"></style>
