
<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 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 isAction = true;
    // 显示计划列表按钮
    public isPlan = false;
    // 是否显示删改查按钮
    public isBase = false;
    public isFile = false;
    public tableActionWidth="60px";
    public statusList = ["","检查中","已检查","未检查"];
    public account = JSON.parse(localStorage.getItem("account") as string);
    // 是否隐藏隐患登记情况
    public hideActions = false;

    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 = ["","即查即改","限期整改"]

    created(){

    }

    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='link'>"+(data.tableNum || 0)+"</span>"
        }});
        this.tableColumn.push({name:'数据生成时间',key:"createTime"});
        this.tableColumn.push({name:'检查周期',key:"inspectCycleValue"});
        this.tableColumn.push({name:'单位',render:(data)=>{
            return this.$store.getters.prevention_cycle_unit_map[data.inspectCycleUnit]
        }});
        this.tableColumn.push({name:'状态',filters:[{
            text:"检查中",
            value:1
        },{
            text:"已检查",
            value:2
        },{
            text:"未检查",
            value:3
        }],filterMethod:(data,row)=>{
            return row.status === data
        },key:"status",render:(data)=>{
            return "<span class='color_"+(data.status-1)+"'>"+(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
        }];
        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:"text"
        },{
            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:"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,
        },{
            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,
        }]
    }

    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]
        }
    }


    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"){
            console.log(this.selectData)
            this.deleteData(this.selectData.map((item:any)=>item.id))
            this.getTroubleList();
        }else if(data.value ==="fixed"){
            this.showMap = true

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

    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.tableService.addOrUpdate(this.updateParams,!this.updateParams.id).then(res=>{
            this.$message.success(!this.updateParams.id?"新增成功！":"编辑成功");
            this.handleClose();
            this.getTroubleList();
        })
    }
    // 重置数据
    public reset(){
        this.params = {
            pageNum:1,
            pageSize:20,
        } as any;
    }

    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 || 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
    }
    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.isReadonly = !!isRead;
        this.fileList = [];
        this.photoList = [];
        this.updateParams = {
            taskId:this.recordParams.taskId,
            locationName:"",
            inspectUserId:this.account.userId,
            inspectUserName:this.account.nickName,
            number:null,
            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{

            if(isRead){
                delete this.updateParams.photo;
            }

            Object.assign(this.updateParams,{
                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)
            // 获取url
            if(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){
        this.showRecord = true;
        this.recordParams.taskId = row.id;
        this.recordParams.planId = row.planId
        this.getTabsData()
        this.getTroubleList();
    }
    public getTabsData(){
        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)){
                        console.log(subItem.userIds)
                        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=>{
            this.troubleTableData = res.data
        })
    }

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

    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;
    }

    public doCheck(){
        const params = [] as any;
        let total = 0;
        this.tableTabs.forEach(item=>{
            total+=item.tableItems.length;
            item.tableItems.forEach(subItem=>{
                        console.log(subItem)
                if(subItem.userIds.includes(this.account.userId)){
                    params.push({
                        content:subItem.itemRecord,
                        resultFlag:subItem.itemResult,
                        taskTableId:subItem.itemId,
                        taskId:this.recordParams.taskId,
                        inspectUserId:this.account.userId,
                        inspectUserName:this.account.nickName,
                    })
                }
            })
        })
        this.tableService.addRecord({
            dangerInspectTaskRecords:params,
            total,
        }).then(res=>{
            this.$message.success("检查成功");
            this.handleClose();
            this.getTableData()
        })
    }

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

    }


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