// package/report/report.js

import { getPointList,getPatrolTemplate,getTemplates,reportQuest,getPatrolPlan,getStructuresList } from "../../utils/getApiUrl";
import {Request} from "../../common";
const moment = require("../../utils/moment");

Page({
    data: {
        isPlanState: false,
        structList: [],//结构物列表
        data:[],//巡检计划的数据(包括点位,设备等等)
        structListIndex: undefined,//结构物id
        pointList:[],//点位列表
        pointIndex:undefined,//点位索引
        devicesList:[],//设备列表
        dataList: '', // 当前巡检计划
        patrolTemplate:[],//巡检模板
        templateData:[],//巡检模板总数居
        // curPlanTemplateId:0,//当前巡检计划的模板id
        patrolTemplateIndex:undefined,//巡检模板索引
        itemData: '', // 点位
        address: '', // 当前位置
        imgUrl: getApp().globalData.imgUrl,
        checkItems: [], // 检查项
        inspectContentArr: [], // 巡检内容
        isCommitting: false,
        // planList: null, // 巡检计划列表
        structListVisible: true,
        scenePointId: null, // 当前点位id
    },
    // //巡检计划
    // getPatrolPlan: function (scenePointId) {
    //     let that = this;
    //     wx.showLoading({
    //         title: '加载中',
    //     })
    //     Request.get(getPatrolPlan()).then(res => {
    //         wx.hideLoading();
    //         let pointPlan = res.rows.filter(plan => {
    //             for (const point of plan.points) {
    //                 if (point.id == scenePointId) {
    //                     return true;
    //                 }
    //             }
    //             return false;
    //         }).map(p => ({
    //             label: p.name,
    //             value: p.name,
    //             ...p
    //         }))
    //         that.setData({
    //             planList: pointPlan
    //         })
    //     })
    // },
    //点位改变函数
    pointChange(e){
        const that = this
        // that.getPatrolPlan(that.data.data[e.detail.value].id)
            that.setData({
                inspectContentArr:[],
                pointIndex:e.detail.value,
                devicesList:that.data.data[e.detail.value].devices,
                scenePointId:that.data.data[e.detail.value].id,
                // patrolTemplate:[]
                patrolTemplateIndex:null
            })
        
       
    },
     // 预览图片
     previewImg: function (e) {
        const { deviceidx, itemidx, index } = e.currentTarget.dataset;
        // 所有图片
        const imgs = this.data.inspectContentArr[deviceidx].checkItems[itemidx].imgs;
        const newImgs = imgs.map(i => this.data.imgUrl + i);
        wx.previewImage({
            // 当前显示图片
            current: newImgs[index],
            // 所有图片
            urls: newImgs
        })
    },
    //结构物改变函数
   structChange(event) {
    //    console.log('pointIndex',this.data.pointIndex)
        const that = this
        that.setData({
            structListIndex: event.detail.value,
            // isPlanState: true,
            pointList:[],//选择结构物后先置空先前的点位列表
            patrolTemplate:[],
            inspectContentArr:[],
            patrolTemplateIndex:null,
            pointIndex:null
        })
      
        const projectId=that.data?.structList[event.detail.value]?.id
        const query={projectId}
        
        Request.get(getTemplates(query)).then(res=>{
            if(res){
                const rlst=res.map(item=>item.patrolTemplate)
                that.setData({patrolTemplate:rlst,templateData:res})
            }else{

            }
        })
        Request.get(getPointList(query)).then(res => {
            if(res){
                const pointList=res.map(item=>{
                    return {
                        id:item.id,
                        name:item.name
                    }
                })
                // console.log('patrolTemplateIndex',this.data.patrolTemplateIndex)
                that.setData({pointList:pointList,data:res})
            }else {
                wx.hideLoading();
            }
        })

    },
    //整理设备和检查项
    getPatrolTemplate(templateId,pointDevices=[]) {
        const that=this
        Request.get(getPatrolTemplate(templateId)).then(res => {
            const checkItems = res.rows[0].checkItems;
            let inspectContentArr = [];
            // 有绑定设备的点位,每个设备都要检查各个检查项
            if (pointDevices.length) {
                pointDevices.forEach(device => {
                    inspectContentArr.push({
                        deviceName: device.name,
                        deviceId: device.id,
                        checkItems: checkItems.map(c => ({
                            id: `${device.id}-${c.id}`,
                            name: c.name,
                            isNormal: true,
                            msgInp: null,
                            level: null,
                            imgs: [],
                        }))
                    })
                });
            } else {
                inspectContentArr.push({
                    checkItems: checkItems.map(c => ({
                        id: c.id,
                        name: c.name,
                        isNormal: true,
                        msgInp: null,
                        level: null,
                        imgs: [],
                    }))
                })
            }
            this.setData({
                checkItems,
                inspectContentArr: inspectContentArr,
            })
        })
    },
    //选择异常或者正常
    handleChangeTwo(e) {
        const { deviceidx, itemidx } = e.currentTarget.dataset;
        let nextInspectContentArr = this.data.inspectContentArr;

        nextInspectContentArr[deviceidx].checkItems[itemidx].isNormal = e.detail;
        if (e.detail) { // 清除异常数据
            nextInspectContentArr[deviceidx].checkItems[itemidx].msgInp = null;
            nextInspectContentArr[deviceidx].checkItems[itemidx].level = null;
            nextInspectContentArr[deviceidx].checkItems[itemidx].imgs = [];
        }
        this.setData({ inspectContentArr: nextInspectContentArr })
    },
    //返回前一页
    bindCancel() {
            wx.navigateBack();
    },
     // 开始巡检录入
     addPatrolRecord: function () {
        const that = this;
        if (that.data.isCommitting) { return }
        let {
            patrolTemplate,
            patrolTemplateIndex,
            structListIndex,
            pointIndex,
            pointList,
            inspectContentArr,
            dataList,
            address,
            data,
            templateData
        } = that.data;
        let alarm = false;
        // if (!address) {
        //     wx.showToast({
        //         title: '请获取当前位置',
        //         icon: 'none',
        //         duration: 1500
        //     })
        //     return;
        // }
        if (!structListIndex) {
            wx.showToast({
                title: '请选择结构物',
                icon: 'none',
                duration: 1500
            })
            return;
        }
        if (!patrolTemplateIndex) {
            wx.showToast({
                title: '请选择模板',
                icon: 'none',
                duration: 1500
            })
            return;
        }
        if (!pointIndex) {
            wx.showToast({
                title: '请选择点位',
                icon: 'none',
                duration: 1500
            })
            return;
        }
        let reportArr = inspectContentArr.map(d => ({ ...d, alarm: false }));
        for (const [index, device] of inspectContentArr.entries()) {
            for (const item of device.checkItems) {
                if (item.isNormal === null) {
                    wx.showToast({
                        title: '请填写完整',
                        icon: 'none',
                        duration: 1500
                    })
                    return;
                }
                if ((!item.isNormal) && (!item.level || !item.msgInp)) {
                    wx.showToast({
                        title: '异常项必须输入巡查详情和选择严重等级',
                        icon: 'none',
                        duration: 2000
                    })
                    return;
                }
                if (item.isNormal === false) {
                    alarm = true; // 巡检记录异常
                    reportArr[index].alarm = true; // 设备异常
                }
            }
        }
        const { id, name, departmentId, deptName } = wx.getStorageSync('userInfo');
        const newData = that.data.data.map((item) => {
            let pointDevices=[]
            item.devices.map(child=>{
                const {pointDevice,...newItem } = child;
                pointDevices.push({device:newItem,deviceId:pointDevice.deviceId}) 
            })
            // 使用对象的解构赋值去掉 project 和 devices 属性
                const { project, devices, ...newItem } = item;
                return {...newItem,pointDevices}
          });
        const nextItemData=newData.find(item=>item.id===pointList[pointIndex].id)
        // const curPlan = that.data.planList.find(item=>item.id==patrolTemplate[patrolTemplateIndex].id)
        // const nextItemData = curPlan.points.find(p => p.id == this.data.scenePointId)
        const aboutSend=templateData.find(item=>item.patrolTemplate.id===patrolTemplate[patrolTemplateIndex].id)
        let datas = {
            patrolPlanId: -1,
            pointId: pointList[pointIndex].id,
            inspectionTime: moment().format('YYYY-MM-DD HH:mm:ss'),
            points: {
                user: { id, name, department: { id: departmentId, name: deptName } },
                project: aboutSend.project,
                // frequency: aboutSend.frequency,
                itemData:nextItemData,
                inspectContent: reportArr,
                address: address
            },
            alarm,
            projectId: aboutSend.project.id
        }
        wx.showLoading({ title: '提交中...' });
        that.setData({ isCommitting: true });
        Request.post(reportQuest(), datas).then(res => {
            wx.hideLoading();
            that.setData({ isCommitting: false });
            wx.showToast({
                title: '提交成功',
                icon: 'success'
            })
            setTimeout(() => {
                that.bindCancel();
            }, 1500)
        })
    },
     //多张图片上传
     uploadImg: function (data, deviceidx, itemidx) {
        wx.showLoading({
            title: '上传中...',
            mask: true,
        })
        let that = this,
            i = data.i ? data.i : 0,
            success = data.success ? data.success : 0,
            fail = data.fail ? data.fail : 0;
        let imgs = that.data.inspectContentArr[deviceidx].checkItems[itemidx].imgs;
        wx.uploadFile({
            url: data.url,
            filePath: data.path[i],
            name: 'file',
            success: (resp) => {
                wx.hideLoading();
                success++;
                let str = JSON.parse(resp.data) // 返回的结果,可能不同项目结果不一样
                str = str.uploaded
                if (imgs.length >= 20) {
                    let nextInspectContentArr = that.data.inspectContentArr;
                    nextInspectContentArr[deviceidx].checkItems[itemidx].imgs = imgs;
                    that.setData({ inspectContentArr: nextInspectContentArr });
                    return false;
                } else {
                    imgs.push(str);
                    let nextInspectContentArr = that.data.inspectContentArr;
                    nextInspectContentArr[deviceidx].checkItems[itemidx].imgs = imgs;
                    that.setData({ inspectContentArr: nextInspectContentArr });
                }
            },
            fail: (res) => {
                fail++;
                console.log('fail:' + i + "fail:" + fail);
            },
            complete: () => {
                i++;
                if (i == data.path.length) { // 当图片传完时,停止调用     
                    console.log('执行完毕');
                    console.log('成功:' + success + " 失败:" + fail);
                } else { // 若图片还没有传完,则继续调用函数
                    data.i = i;
                    data.success = success;
                    data.fail = fail;
                    that.uploadImg(data, deviceidx, itemidx); // 递归,回调自己
                }
            }
        });
    },
      // 上传图片
      chooseImg: function (e) { // 这里是选取图片的方法
        const { deviceidx, itemidx } = e.currentTarget.dataset;
        const that = this;
        let pics = [];
        const detailPics = that.data.inspectContentArr[deviceidx].checkItems[itemidx].imgs;
        if (detailPics.length >= 20) {
            wx.showToast({
                title: '最多选择20张图片上传',
                icon: 'none'
            });
            return;
        }
        wx.chooseMedia({
            count: 20, // 基础库2.25.0前,最多可支持9个文件,2.25.0及以后最多可支持20个文件
            mediaType: ['image'], // 文件类型
            sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有
            sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
            success: function (res) {
                const imgs = res.tempFiles;
                for (let i = 0; i < imgs.length; i++) {
                    if (res.tempFiles[i].size > 15728640) {
                        wx.showToast({ title: '图片大于15M,不可上传', icon: 'none' });
                        return;
                    }
                    const fileNameArr = res.tempFiles[i].tempFilePath.split('.');
                    const extension = res.tempFiles[i].tempFilePath.split('.')[fileNameArr.length - 1];
                    if (extension !== 'jpg' && extension !== 'png' && extension !== 'jpeg') {
                        wx.showToast({ title: '只能上传jpg、jpeg、png格式的图片', icon: 'none' });
                        return;
                    }
                    pics.push(imgs[i].tempFilePath)
                }
                that.uploadImg({
                    url: getApp().globalData.webUrl + '_upload/attachments/project', // 图片上传的接口
                    path: pics, // 选取的图片的地址数组
                }, deviceidx, itemidx);
            },
        })
    },
      // 删除图片
      deleteImg: function (e) {
        const { deviceidx, itemidx, index } = e.currentTarget.dataset;
        let imgs = this.data.inspectContentArr[deviceidx].checkItems[itemidx].imgs;
        imgs.splice(index, 1);
        let nextInspectContentArr = this.data.inspectContentArr;
        nextInspectContentArr[deviceidx].checkItems[itemidx].imgs = imgs;
        this.setData({ inspectContentArr: nextInspectContentArr })
    },
     // 巡查详情
     bindInput: function (e) {
        const { deviceidx, itemidx } = e.currentTarget.dataset;
        let nextInspectContentArr = this.data.inspectContentArr;

        nextInspectContentArr[deviceidx].checkItems[itemidx].msgInp = e.detail.value;
        this.setData({ inspectContentArr: nextInspectContentArr })
    },

    handleChangeThree(e) {
        const { deviceidx, itemidx } = e.currentTarget.dataset;
        let nextInspectContentArr = this.data.inspectContentArr;
        nextInspectContentArr[deviceidx].checkItems[itemidx].level = e.detail;
        this.setData({ inspectContentArr: nextInspectContentArr })
    },


    //巡检模板改变
    patrolTemplateChange(e){
        const that=this
        
            that.getPatrolTemplate(that.data.patrolTemplate[e.detail.value].id,that.data.devicesList)
            that.setData({
                patrolTemplateIndex:e.detail.value
            })
        
      
    },
    bindShowMsg() {
        this.setData({
            select: !this.data.select
        })
    },

    mySelect(e) {
        var name = e.currentTarget.dataset.name
        this.setData({
            tihuoWay: name,
            select: false
        })
    },
    /**
     * 页面的初始数据
     */
    //   data: {

    //   },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const that=this
        wx.setNavigationBarTitle({
            title: options.key,
        });
        Request.get(getStructuresList()).then(res=>{
            if(res){
                const list=res.rows
                if(list&&list.length){
                  const res=  list.filter(item=>item.type=='管廊')
                 that.setData({structList:res.map(item=>{
                    return {
                        name:item.name,
                        id:item.id
                    }
                })})
                }
            }else{
                wx.hideLoading();

            }
        })
    },
    onStructListPicker() {
        this.setData({
            structListVisible: true
        });
    },
    // 获取当前位置
    selfLocation() {
        const that = this
        wx.showLoading({
            title: '定位中',
            mask: true,
        });
        wx.getLocation({
            type: 'wgs84',
            success: (res) => {
                wx.request({
                    url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&key=${getApp().globalData.key}`,
                    success: function (res) {
                        wx.hideLoading();
                        wx.chooseLocation({
                            success:function(res){
                                that.setData({
                                    address: res.name
                                })
                            }
                        })
                        // 根据自己项目需求获取res内容
                        
                    }
                })
            },
            fail: (res) => {
                wx.hideLoading();
                if (res.errMsg === 'getLocation:fail auth deny') {
                    that.toSettingModal('请允许位置权限')
                } else {
                    wx.showToast({
                        title: res.errMsg,
                        icon: 'none',
                        duration: 1000
                    });
                }
            }
        });
    },
    toSettingModal() {
        wx.showModal({
            title: '提示',
            confirmText: '去设置',
            content: '请允许位置权限',
            success: function (res) {
                const { confirm } = res || {}
                if (confirm) {
                    wx.openSetting()
                }
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})