let util = require('../../../utils/util')
let apiArr = require('../../../api/water_filter')

const __staticUrl = require('../../../config/env.js').static_url
Page({
    data: {
        type: "",
        id: "",
        newOrderDesc: {},
        newOrderDateShow:false,
        newOrderDateAppointment:"",
        msg: "", //安装说明
        msg2: "", //更换说明
        imgList: [],
        imgList2: [],
        repairOrderDesc: {},
        partOrderDesc: {},

        uninstallDesc: {},
        uninstalldis: false,
        uninstallMsg: "",
        UninstallDate: false,
        uninstall_time: "",


        dis1: false,
        dis2: false,
        dis3: false,
        deviceInfo: {
            device_code:""
        },
        deviceCode: "",


        minDate: new Date().getTime(),
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            }
            if (type === 'month') {
                return `${value}月`;
            }
            if (type === 'day') {
                return `${value}日`;
            }
            return value;
        },
    },
    // 新装///////////////////////////////
    //输入框
    updateInstructions(e) {
        let that = this
        that.setData({
            msg: e.detail.value
        })
    },
    // 上传图片
    uploadImage() {
        let that = this
        wx.showLoading({
            title: '上传中...',
        })
        wx.chooseMedia({
            count: 9,
            mediaType: ['image'],
            success: (res) => {
                let tempFiles = res.tempFiles.map(file => file.tempFilePath);
                let imgList = []
                let imgList2 = []
                let uploadCount = 0;

                tempFiles.forEach((item, index) => {
                    util.uploadFileUrl(item, res => {
                        res = JSON.parse(res)
                        imgList[index] = util.img_url + res.data.path;
                        imgList2[index] = res.data.path
                        uploadCount++;

                        // 所有文件上传完成后更新数据
                        if (uploadCount === tempFiles.length) {
                            that.setData({
                                imgList: imgList,
                                imgList2
                            }, () => {
                                wx.hideLoading();
                            });
                        }
                    });
                });
            },
            fail: err => {
                wx.hideLoading()
                console.log(err, 999);
            }
        });
    },
    // 删除图片
    deleteImage(e) {
        let that = this
        const index = e.currentTarget.dataset.index;
        let imgList = that.data.imgList
        let imgList2 = that.data.imgList2
        imgList.splice(index, 1)
        imgList2.splice(index, 1)
        this.setData({
            imgList,
            imgList2
        });
    },
    getNewOrderDesc() {
        let that = this
        wx.showLoading({
            title: '加载中...',
            mask:true
        })
        util.postUrl(apiArr.newOrderDesc, { install_id: Number(that.data.id) }, res => {
            wx.hideLoading()
            console.log(res);
            res.product_icon2 = util.img_url + res.product_icon
            let imgList = ''
            let newArr = []
            if (res.install_imgs) {
                imgList = res.install_imgs.split(",")
                newArr = []
                imgList.forEach(item => {
                    newArr.push(util.img_url + item)
                })
            } else {
                imgList = ''
                newArr = []
            }
            that.setData({
                newOrderDesc: res,
                imgList: newArr,
                msg:res.install_desc,
                newOrderDateAppointment:res.remaining_days?res.remaining_days:''
            })

            if (res.status == 5 ) {
                that.getDeriveInfo()
                let imgList2 = ''
                let imgList = []

                if (res.install_imgs) {
                    console.log(123);
                    imgList2 = res.install_imgs.split(',')
                    imgList = []
                    imgList2.forEach((item, index) => {
                        imgList.push(util.img_url + item)
                    })
                } else {
                    console.log(456);
                    imgList2 = []
                    imgList = []
                }
                that.setData({
                    msg: res.install_desc,
                    imgList2,
                    imgList,
                    dis1: true
                })
            }



        })
    },

    closeNewOrder(){
        let that= this
        that.setData({
            newOrderDateShow:!that.data.newOrderDateShow
        })
    },
    changeNewAppointment(e){
        let that = this
        that.setData({
            newOrderDateAppointment:e.detail.value
        })
    },
    jihuoItem() {
        let that = this
      
        util.postUrl(apiArr.BeActive, {
            install_id: that.data.newOrderDesc.install_id,
            remaining_days:Number(that.data.newOrderDateAppointment)
        }, res => {
            console.log(res);
            if (res.msg == '操作成功') {
                wx.showToast({
                    title: '激活成功！',
                    icon: "none"
                })
                setTimeout(() => {
                    wx.navigateBack({
                        delta: 1
                    })
                }, 1500)
            }
        })
    },
    completeNewOrder() {
        let that = this
        let content = '确认完成该工单吗？'

        if (!that.data.msg) {
            return wx.showToast({
                title: '请填写安装说明',
                icon: "none"
            })
        }

        if (!that.data.deviceInfo.device_code) {
            return wx.showToast({
                title: '请扫码设备二维码',
                icon: "none"
            })
        }

        if (!that.data.imgList.length) {
            return wx.showToast({
                title: '请上传安装图片',
                icon: "none"
            })
        }

        util.postUrl(apiArr.getDeviceByCode, {
            device_code: that.data.deviceInfo.device_code,
            install_id:that.data.id
        }, res => {
            console.log(res,'res');
            if(res.msg == '设备与订单产品不匹配'){

                return wx.showToast({
                  title: res.msg,
                  icon:"none"
                })
            }
            that.setData({
                deviceInfo: res
            })
            wx.showModal({
                title: '提示',
                content: content,
                success: (res) => {
                    if (res.confirm) {
                        util.postUrl(apiArr.completeNewOrder, {
                            install_id: Number(that.data.id),
                            status: 3,
                            install_desc: that.data.msg,
                            install_imgs: that.data.imgList2.join(','),
                            install_time: util.getCurrentTime(),
                            device_id: that.data.deviceInfo.device_id,
                            product_id: that.data.deviceInfo.product_id
                        }, res => {
                            if (res.msg == '操作成功') {
                                // that.jihuoItem()
                                wx.showToast({
                                    title: '创建成功！',
                                    icon: "none"
                                })
                                setTimeout(() => {
                                    // wx.navigateBack({
                                    //     delta: 1
                                    // })
                                    that.getNewOrderDesc()
                                }, 1500)
                            } else {
                                wx.showToast({
                                    title: res.msg,
                                    icon: "none"
                                })
                            }
                        })
                    }
                }
            });
        })

    },
    cancelNewOrder() {
        let that = this
        util.postUrl(apiArr.cancelNewOrder, {
            install_id: Number(that.data.id),
        }, res => {
            wx.showToast({
                title: res.msg,
            })
            if (res.msg == '操作成功') {
                setTimeout(() => {
                    wx.navigateBack({
                        delta: 1
                    })
                }, 1500);
            }
        })
    },
    scanQrcode() {
        let that = this
        wx.scanCode({
            success: (res) => {
                // 处理扫码结果
                this.setData({
                    deviceCode: res.result,
                    "deviceInfo.device_code":res.result
                });

                util.postUrl(apiArr.getDeviceByCode, {
                    device_code: res.result,
                    install_id:that.data.id
                }, res => {
                    that.setData({
                        deviceInfo: res
                    })
                })

            },
            fail: (err) => {
                wx.showToast({
                    title: '扫码失败',
                    icon: 'none'
                });
            }
        });
    },
    iptDeviceCode(e){
        let that = this
        console.log(e);
        that.setData({
            "deviceInfo.device_code":e.detail.value
        })
    },
    iptSearch(){
        let that = this
        util.postUrl(apiArr.getDeviceByCode, {
            device_code: that.data.deviceInfo.device_code,
            install_id:that.data.id
        }, res => {
            that.setData({
                deviceInfo: res
            })
        })
    },
    // 新装///////////////////////////////

    // 维修 ///////////////////////////////
    getRepairOrderDesc() {
        let that = this
        wx.showLoading({
            title: '加载中...',
            mask:true
        })
        util.postUrl(apiArr.RepairOrderDesc, {
            repair_id: that.data.id
        }, res => {
            wx.hideLoading()
            res.fault_imgs = util.img_url + res.fault_imgs
            that.setData({
                repairOrderDesc: res
            })

            if (res.status == 3 || res.status == 4) {
                let imgList2 = res.repair_imgs.split(',')
                let imgList = []
                imgList2.forEach((item, index) => {
                    imgList.push(util.img_url + item)
                })
                console.log(imgList);
                that.setData({
                    msg: res.repair_desc,
                    imgList,
                    imgList2,
                    dis2: true
                })
            }
        })
    },
    completeRepairOrder(e) {
        let status = Number(e.currentTarget.dataset.type)
        let that = this
        let content = '确认完成该工单吗？'
        if (status == 3) {
            content = '确认完成该工单吗？'
        } else {
            content = '确认撤销该工单吗？'
        }
        wx.showModal({
            title: '提示',
            content: content,
            success: (res) => {
                if (res.confirm) {
                    util.postUrl(apiArr.completeRepairOrder, {
                        repair_id: Number(that.data.id),
                        status,
                        repair_desc: that.data.msg,
                        repair_imgs: that.data.imgList2.join(','),
                        repair_time: util.getCurrentTime()
                    }, res => {
                        wx.showToast({
                            title: res.msg,
                        })
                        if (res.msg == '操作成功') {
                            setTimeout(() => {
                                
                                wx.navigateBack({
                                    delta: 1
                                })
                            }, 1500);
                        }
                    })
                }
            }
        });
    },
    // 维修 ///////////////////////////////

    // 滤芯更换  ///////////////////////////////
    getPartOrderDesc() {
        let that = this
        wx.showLoading({
            title: '加载中...',
            mask:true
        })
        util.postUrl(apiArr.PartOrderDesc, {
            replace_id: that.data.id
        }, res => {
            wx.hideLoading()
            that.setData({
                partOrderDesc: res
            })

            if (res.status == 3 || res.status == 4 ) {
                that.setData({
                    msg2: res.install_desc,
                    dis3: true
                })
            }

        })
    },
 
    completePartOrder(e) {
        let status = Number(e.currentTarget.dataset.type)
        let that = this
        let content = '确认完成该工单吗？'
        if (status == 3) {
            content = '确认完成该工单吗？'
        } else {
            content = '确认撤销该工单吗？'
        }
        wx.showModal({
            title: '提示',
            content: content,
            success: (res) => {
                if (res.confirm) {
                    util.postUrl(apiArr.completePartOrder, {
                        replace_id: Number(that.data.id),
                        status,
                        install_desc: that.data.msg2,
                        install_time: util.getCurrentTime()
                    }, res => {
                        wx.showToast({
                            title: res.msg,
                        })
                        if (res.msg == '操作成功') {
                            setTimeout(() => {
                                // wx.navigateBack({
                                //     delta: 1
                                // })
                                // device_id
                                if(status == 3){
                                    wx.navigateTo({
                                        url: '/packages/master/deviceInfo/index?id=' + that.data.partOrderDesc.device_id,
                                    })
                                }else{
                                    wx.navigateTo({
                                      url: '/packages/master/order/index?type=2',
                                    })
                                }
                            }, 1500);
                        }
                    })
                }
            }
        });
    },
    updateInstructions2(e) {
        let that = this
        that.setData({
            msg2: e.detail.value
        })
    },
    // 滤芯更换  ///////////////////////////////



    // 拆卸工单详情/////////////////////////////////////////////
    getUninstallDesc() {
        let that = this
        wx.showLoading({
            title: '加载中...',
            mask:true
        })
        util.postUrl(apiArr.getUninstallDesc, {
            uninstall_id: that.data.id
        }, res => {
            wx.hideLoading()
            let uninstalldis = false
            if(res.status != 2){
                uninstalldis = true
            }

            let imgList = ''
            let newArr = []
            if (res.uninstall_imgs) {
                imgList = res.uninstall_imgs.split(",")
                imgList.forEach(item => {
                    newArr.push(util.img_url + item)
                })
            } else {
                imgList = ''
                newArr = []
            }


            that.setData({
                uninstallDesc: res,
                uninstall_time:res.uninstall_time,
                uninstallMsg:res.uninstall_desc,
                imgList:newArr,
                uninstalldis
            })
        })
    },
    updateInstructions3(e) {
        let that = this
        that.setData({
            uninstallMsg: e.detail.value
        })
    },
    changeUninstallDate() {
        let that = this
        that.setData({
            UninstallDate: !that.data.UninstallDate
        })
    },

    onInput(event) {
        let that = this
        const date = new Date(event.detail); // 获取选中的 Date 对象
        const year = date.getFullYear(); // 获取年份
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0'); // 小时补零
        const minutes = String(date.getMinutes()).padStart(2, '0'); // 分钟补零
        const time = `${year}-${month}-${day} ${hours}:${minutes}`;
        that.setData({
            uninstall_time: time,
            UninstallDate: false
        })
    },
    onInput2(event) {
        let that = this
        const date = new Date(event.detail); // 获取选中的 Date 对象
        const year = date.getFullYear(); // 获取年份
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0'); // 小时补零
        const minutes = String(date.getMinutes()).padStart(2, '0'); // 分钟补零
        const time = `${year}-${month}-${day} ${hours}:${minutes}`;
        that.setData({
            newOrderDateAppointment: time,
            newOrderDateShow: false
        })
    },

    // 拆机
    uninstallDesc() {
        let that = this

        if (!that.data.uninstallMsg) {
            return wx.showToast({
                title: '请填写拆除说明',
                icon: "none"
            })
        }
        if (!that.data.uninstall_time) {
            return wx.showToast({
                title: '请选择拆除时间',
                icon: "none"
            })
        }
        if (!that.data.imgList.length) {
            return wx.showToast({
                title: '请上传拆除图片',
                icon: "none"
            })
        }

        util.postUrl(apiArr.unintsall, {
            uninstall_id: that.data.uninstallDesc.uninstall_id,
            uninstall_time: that.data.uninstall_time + ':00',
            uninstall_desc: that.data.uninstallMsg,
            uninstall_imgs: that.data.imgList2.join(','),
        }, res => {
            console.log(res);
            if (res.msg == '操作成功') {
                wx.showToast({
                    title: '拆机成功！',
                    icon: "none"
                })
                setTimeout(() => {
                    // wx.navigateBack({
                    //     delta: 1
                    // })
                    that.setData({
                        uninstallMsg:"",
                        imgList2:[],
                        imgList:[],
                        uninstall_time:"",
                    })
                    that.getUninstallDesc()
                }, 1500)
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: "none"
                })
            }
        })
    },

    //报废 入库
    operate(e) {
        let that = this
        let status = e.currentTarget.dataset.type
        let content = ''
        if (status == 9) {
            content = '确定要入库吗'
        } else {
            content = '确定要报废吗'
        }
        wx.showModal({
            title: '提示',
            content: content,
            complete: (res) => {
                if (res.cancel) {

                }

                if (res.confirm) {
                    util.postUrl(apiArr.operate, {
                        uninstall_id:that.data.uninstallDesc.uninstall_id,
                        status:status
                    },res=>{
                        wx.showToast({
                          title: '操作成功',
                          icon:"none"
                        })
                        setTimeout(()=>{
                            wx.navigateBack({
                                delta:1
                            })
                        },1500)
                    })
                }
            }
        })

    },



    //查询设备实时信息
    getDeriveInfo() {
        let that = this
        util.postUrl(apiArr.boardInfo, {
            device_id: that.data.newOrderDesc.device_id
        }, res => {
            console.log(res);
        })
    },



    onLoad(options) {
        let that = this
        // 这里可以根据options.id来设置不同的假数据
        const id = options.id;
        this.setData({
            id,
            type: options.type
        });

        if (options.type == 0) {
            that.getNewOrderDesc()
        } else if (options.type == 1) {
            that.getRepairOrderDesc()
        } else if (options.type == 3) {
            that.getUninstallDesc()
        } else if (options.type == 2) {
            that.getPartOrderDesc()
        }

        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })

    },

    onShareAppMessage() {
        return {
            title: '人人爱净水',  // 分享卡片标题（必填）
            path: '/pages/water_filter/water_filter',  // 用户点击后跳转的路径（可选，默认当前页）
            imageUrl: (__staticUrl + '/share.png')  // 自定义图片（可选，比例建议 5:4）
        }
    },
    onShareTimeline() {
        return {
            title: '人人爱净水', // 自定义标题
            query: '', // 自定义页面路径中的参数
            imageUrl: (__staticUrl + '/share.png') // 自定义分享图片路径
        }
    },


});