
<script lang="ts">
import { Component } from 'vue-property-decorator';
import template from "./common.component.html"
import BaseRecordComponent from "hbt-common/components/common/baseRecord.component.vue"
import FormComponent from "hbt-common/components/common/form.component.vue"
import TableComponent from "hbt-common/components/common/table.component.vue"
import 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 NoteService from '@/service/note.service';
import WorkFlowService from "@/service/workFlow.service"
import UnitService from '@/service/unit.service';
import MapComponent from "@/components/map.component.vue"
import mapboxgl from "mapbox-gl";
import moment from 'moment';
@Component({
    template,
    components:{
        FormComponent,
        TableComponent,
        DrawComponent,
        MapComponent
    },
} as any)
export default class HiddenDangerClapComponent extends BaseRecordComponent<any> {
    public tableService = new NoteService();

    public areaService = new AreaService();

    public unitService = new UnitService();
    public workFlowService = new WorkFlowService()

    public areaList = [];

    public unitList = [];

    public params = {} as any;
    // 是否显示删改查按钮
    public isBase = true;
    public isClap = true;

    public isAction = false;

    public isPlan = false;

    public tableActionWidth = "150px";

    public isReadonly = false;
    public account = JSON.parse(localStorage.getItem("account") as string);
    public showMap = false;
    public center = [118.751353,31.969568];
    public marker:any;

    public map: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:"number",
        type:"text",
    }];

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

    public photoList = [] as any;
    public fileList = [] as any;

    public currentUrl:any;
    public showFile = false;



    public updateActions = [{
        name:"取消",
        value:"cancel"
    },{
        name:"保存并下发",
        value:"submit",
        type:"primary"
    },{
        name:"保存",
        value:"draft",
        type:"primary"
    }];

    public selectData = [];

    public levelMap = ["","一般隐患","重大隐患"]
    public statusMap = ["未下发","已下发"];
    public reformModeMap = ["","即查即改","限期整改"]
    

    created(){
        this.loadAreaData()
        this.loadUnitData();
    }



    // 加载区域列表
    public loadAreaData(){
        this.areaService.selectByPage({pageSize:1000}).then((res:any)=>{
            this.areaList = res.data.datas.map(item=>{
                return {
                    name:item.name,
                    value:item.id
                }
            });
            this.buildUpdateForm()
        })
    }
    // 加载单元列表
    public loadUnitData(id?){
        this.unitService.selectByPage({pageSize:1000,areaId:id},false).then((res:any)=>{
            this.unitList = res.data.datas.map(item=>{
                return {
                    name:item.name,
                    value:item.id
                }
            });
            this.buildUpdateForm()
        })
    }


    public buildUpdateForm(){
        this.updateOptions = [{
            name:"隐患编号",
            key:"number",
            type:"text",
            width:"100%",
            require:true,
            showError:false,
            disable:true
        },{
            name:"隐患来源",
            key:"type",
            type:"text",
            width:"100%",
            require:true,
            showError:false,
            disable:true,
        },{
            name:"检查区域",
            key:"areaId",
            format:"areaName",
            type:"select",
            width:"calc(50% - 20px)",
            require:true,
            showError:false,
            datas:this.areaList
        },{
            name:"检查单元",
            key:"unitId",
            format:"unitName",
            type:"select",
            width:"calc(50% - 20px)",
            require:true,
            showError:false,
            datas:this.unitList
        },{
            name:"整改标题",
            key:"title",
            type:"text",
            width:"100%",
            require:true,
            showError:false,
        },{
            name:"检查类型",
            key:"inspectType",
            format:"inspectTypeName",
            type:"select",
            width:"calc(50% - 20px)",
            require:true,
            showError:false,
            datas:this.$store.state.prevention_danger_check_type,
        },{
            name:"隐患类别",
            key:"dangerType",
            format:"dangerTypeName",
            type:"select",
            width:"calc(50% - 20px)",
            require:true,
            showError:false,
            datas:this.$store.state.prevention_danger_type,
        },{
            name:"检查人员",
            key:"inspectUserId",
            format:"inspectUserName",
            type:"select",
            width:"calc(50% - 20px)",
            require:true,
            showError:false,
            datas:this.$store.state.userList,
        },{
            name:"检查时间",
            key:"inspectTime",
            type:"date",
            subType:"datetime",
            format:"yyyy-MM-dd HH:mm",
            width:"calc(50% - 20px)",
            require:true,
            showError:false,
        },{
            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,
        },{
            name:"问题描述",
            key:"description",
            type:"textarea",
            width:"100%",
            require:true,
            showError:false,
        },{
            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,
        },{
            name:"专业分类",
            key:"professionClassify",
            format:"professionClassifyName",
            type:"select",
            width:"calc(50% - 20px)",
            require:true,
            showError:false,
            datas:this.$store.state.prevention_major_type,
        },{
            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,
        }]
    }

    public buildTable(){
        this.tableColumn.push({name:'整改单编号',key:"number"});
        this.tableColumn.push({name:'隐患描述',key:"description",width:"200px"});
        this.tableColumn.push({name:'整改部门',key:"reformDeptName"});
        this.tableColumn.push({name:'隐患级别',render:(data)=>{
            return this.levelMap[data.level]
        }});
        this.tableColumn.push({name:'隐患位置',key:"locationName"});
        this.tableColumn.push({name:'检查时间',key:"inspectTime"});
        this.tableColumn.push({name:'检查人员',key:"inspectUserName"});
        this.tableColumn.push({name:'下发状态',render:(data)=>{
            return `<span class="color_"${data.status}>${this.statusMap[data.status] || ""}</span>`
        }});
    }
    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 change(data,item){
        if(item && item.key === "areaId"){
            this.loadUnitData(data)
        }
        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]
        }
        //
    }

    public callback(data){
        // 查询
        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 === "add"){
            this.showUpdateModel()
        }else if(data.value === "delete"){
            this.deleteData(this.selectData.map((item:any)=>item.id))
        }else if(data.value ==="fixed"){
            this.showMap = true

        }else if(data.value ==="draft" || data.value ==="submit"){
            this.doSave(data.value === "submit");
        }else{
            this.handleClose()
        }
    }
    // 重置数据
    public reset(){
        this.params = {
            pageNum:1,
            pageSize:20,
        } as any;
    }



    public showUpdateModel(row?,isRead?){
        this.isReadonly = !!isRead;
        this.fileList = [];
        this.photoList = [];
        this.updateParams = {
            type:"随手拍",
            locationName:"",
            inspectUserId:this.account.userId,
            inspectUserName:this.account.nickName,
            number:null,
            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.buildUpdateForm()
                this.showUpdate = true;
            })
        }else{
            if(isRead){
                delete this.updateParams.photo;
            }
            this.tableService.selectById(row.id).then((res:any)=>{
                Object.assign(this.updateParams,{
                    classifyName:this.$store.getters.prevention_dangrous_type_map[res.data.classify],
                    attributeClassifyName:this.$store.getters.prevention_safe_reason_map[row.attributeClassify],
                    dangerTypeName:this.$store.getters.prevention_danger_type_map[res.data.dangerType],
                    inspectTypeName:this.$store.getters.prevention_danger_check_type_map[res.data.inspectType],
                    levelName:this.levelMap[res.data.level],
                    occurNodeName:this.$store.getters.prevention_occur_step_map[res.data.occurNode],
                    professionClassifyName:this.$store.getters.prevention_major_type_map[res.data.professionClassify],
                    reformModeName:this.reformModeMap[res.data.reformMode],
                    unitName:(this.unitList.find((item:any)=>item.value===res.data.unitId) as any).name,
                    areaName:(this.areaList.find((item:any)=>item.value===res.data.areaId) as any).name,
                },res.data)
                // 地图定位
                this.center = [res.data.locationLng,res.data.locationLat];
                     this.buildUpdateForm()

                // 获取url
                if(res.data.resourceId){
                    this.tableService.getFileUrls({ids:res.data.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.updateParams.photo = this.photoList.length || null;
                        this.buildUpdateForm()
                    })
                }
                if(res.data.resourceOtherId){
                    this.tableService.getFileUrls({ids:res.data.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.buildUpdateForm()
                    })
                }
                this.showUpdate = true
            })
        }
    }

    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 handleClose(){
        if(this.showMap){
            this.showMap = false;
            this.marker.remove();
            this.marker = null;
            return
        }
        this.showUpdate = false;
        this.updateParams = {} as any;
    }

    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 || null;
        }
    }
    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){
        console.log(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 doSave(isSubmit){
        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.tableService.addOrUpdate(this.updateParams,!this.updateParams.id).then(res=>{
            this.$message.success(!this.updateParams.id?"新增成功！":"编辑成功");
            if(isSubmit){
                this.startWorkFlow([res.data],[this.updateParams.reformUserId])
            }else{
                this.getTableData();
            }
            this.handleClose();
        })
    }

    public startWorkFlow(ids,userIds){
        const keyValue = ids.map(id=>{
            return {
                F_Id:id,
                F_FormId:1742822461669376,
                F_Type:2,
                F_UrlAddress:"ceshi1"
            }
        })
        this.workFlowService.startWorkFlow({
            "F_Id": "1743872031226688",
            "relationTaskList": "[]",
            "keyValue": JSON.stringify(keyValue),
            "userJson": "[]",
            "fileValue": [],
            "nextNodeName":"确认",
            "nodeName":"上报",
            "userList": userIds
        }).then((res:any)=>{
            this.getTableData()
            // 发起工作流成功
        })
    }


    public toggleAll() {
        (this.$refs.multipleTable as any).toggleAllSelection();
    }
    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;
    }
}
</script>
<style lang="scss" scoped src="../common.component.scss">
</style>
