const apiArr = require("../../../../api/water_filter");
const { postUrl } = require("../../../../utils/util");
const util = require("../../../../utils/util");

// pages/water_filter/repair/repair.js
const app = getApp()

const __staticUrl = require('../../../../config/env.js').static_url
Page({

    /**
     * 页面的初始数据
     */
    data: {
        s: app.system.statusBarHeight, // 状态栏高度
        n: (app.menu.top - app.system.statusBarHeight) * 2 + app.menu.height, // 导航栏高度
        t: app.menu.top, // 胶囊局顶部距离
        h: app.menu.height, // 胶囊高度
        value: '',

        name: "",
        phone: "",
        message: "",
        address:"",

        fileList: [],
        fileList2: [],
        time: "",

        equipmentShow: false,
        equipmentList: [],
        selectEquipment: {}, // 所选设备信息
        DoorTimeShow: false,
        sucess: false,//是否报修成功
        minDate: new Date().getTime(),
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            }
            if (type === 'month') {
                return `${value}月`;
            }
            if (type === 'day') {
                return `${value}日`;
            }
            return value;
        },
        currentDevice:{},

        show2: false,
        cityList: [],
        areaList: [],
        businessList: [],
        newAreaList: [],  // 默认展示 市区
        newBusiness: [], // 默认展示 县/区
        confirmCity: '',
        confirmArea: '',
        confirmBusiness: '',
    },
    choseRegion(){
        this.setData({
            show2:true
        })
    },
    getInfo() {
        wx.showLoading({
            title: '加载中...',
            mask: true
        })
        let that = this
        util.postUrl(apiArr.deviceInfo, { device_id:wx.getStorageSync('device_id')}, res => {
            wx.hideLoading()
            that.setData({
                currentDevice: res,
                name:res.device_customer.name,
                phone:res.device_customer.phone,
                address:res.address,
                region:res.region
            })
        })
    },
    deleteImg(e) {
        console.log(e);
        let that = this
        let fileList = that.data.fileList
        let fileList2 = that.data.fileList2
        fileList.splice(e.detail.index, 1)
        fileList2.splice(e.detail.index, 1)
        that.setData({
            fileList,
            fileList2
        })
    },

    ipt1(e) {
        let that = this
        that.setData({
            name: e.detail.value
        })
    },
    ipt2(e) {
        let that = this
        that.setData({
            phone: e.detail.value
        })
    },
    ipt3(e) {
        let that = this
        that.setData({
            message: e.detail
        })
    },
    ipt4(e) {
        let that = this
        that.setData({
            address: e.detail
        })
    },

    switchShow() {
        let that = this
        that.setData({
            DoorTimeShow: !that.data.DoorTimeShow
        })
    },

    // 取消所选设备信息
    headerCancelClick() {
        this.setData({
            selectEquipment: {}, // 所选设备信息
            equipmentShow: false
        })
    },

    // 关闭弹窗
    onClose() {
        let that = this
        that.setData({
            DoorTimeShow: false
        })
    },
    headerEquipmentPopupClick() {
        this.setData({
            equipmentShow: true
        })
    },

    onClosePopup() {
        this.setData({
            equipmentShow: false
        })
    },

    onInput(event) {
        let that = this
        const date = new Date(event.detail);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份补零
        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}`;
        console.log(time);
        that.setData({
            time,
            DoorTimeShow: false
        })
    },

    afterRead(e) {
        const { file } = e.detail;
        // 验证文件类型
        if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image') {
            wx.showToast({ title: '只能上传 JPG/PNG 格式的图片', icon: 'none' });
            return false;
        }
        // 验证文件大小
        if (file.size > 5 * 1024 * 1024) {
            wx.showToast({ title: '图片大小不能超过 5MB', icon: 'none' });
            return false;
        }
        return true;
    },
    beforeRead(e) {
        console.log(e);
        let that = this
        wx.showLoading({
            title: '上传中',
            mask: true,
        })
        util.uploadFileUrl(e.detail.file.url, (res) => {
            wx.hideLoading()
            let datas = JSON.parse(res)
            console.log(datas.data);
            let url = util.img_url + datas.data.path
            let fileList = that.data.fileList
            let fileList2 = that.data.fileList2
            let obj = {
                url: url,
                name: 'avatar'
            }
            let obj2 = {
                url: datas.data.path,
                name: 'avatar'
            }
            fileList.push(obj)
            fileList2.push(obj2)
            that.setData({
                fileList,
                fileList2
            })
        })
    },

    submit() {
        const { selectEquipment, name, phone, time, message, fileList2 } = this.data;
        let that = this

        if (!selectEquipment.device_id) {
            wx.showToast({
                title: '请选择报修设备',
                icon: "none"
            })
            return
        }
        if (!name) {
            wx.showToast({
                title: '请填写联系人姓名',
                icon: "none"
            })
            return
        }
        if (!phone) {
            wx.showToast({
                title: '请填写联系人电话',
                icon: "none"
            })
            return
        }
        if (!util.isPhone(phone)) {
            wx.showToast({
                title: '请填写正确电话',
                icon: "none"
            })
            return
        }
        if (!time) {
            wx.showToast({
                title: '请选择上门时间',
                icon: "none"
            })
            return
        }
        if (!message) {
            wx.showToast({
                title: '请填写报修内容',
                icon: "none"
            })
            return
        }
        wx.showLoading({
            title: '提交中...',
            mask: true,
        })

        wx.getSetting({
            withSubscriptions: true,
            success: (res) => {
                if (res.subscriptionsSetting && res.subscriptionsSetting.mainSwitch) {
                    const itemSettings = res.subscriptionsSetting.itemSettings || {};
                    const tmplMap = {
                        'q3Aa07wgYPgB23mu4JOuSzgFoiYhouUcw-NhV5CNuSA': '订单重新指派提醒',
                        'eEetEKoNpqXk_EY0xqMt22_Xd7NFEyiODY6j0t3_A24': '欠费通知',
                        'pUkdPwh7jWLjCWWv2zyz7I086xNO_GoaJQ6A-cYuGVg': '新订单提醒'
                    };

                    // 收集未订阅的模板ID
                    const unsubscribedTmplIds = [];
                    Object.keys(tmplMap).forEach(tmplId => {
                        if (itemSettings[tmplId] !== 'accept') {
                            unsubscribedTmplIds.push(tmplId);
                        }
                    });

                    if (unsubscribedTmplIds.length > 0) {
                        // 逐个订阅未订阅的消息
                        wx.requestSubscribeMessage({
                            tmplIds: unsubscribedTmplIds,
                            success: (res) => {
                                util.postUrl(apiArr.repair, {
                                    appointment_time: time,
                                    customer_name: name,
                                    customer_phone: phone,
                                    device_id: selectEquipment.device_id,
                                    fault_desc: message,
                                    fault_imgs: fileList2.length !== 0 ? fileList2[0].url : '',
                                    user_id: Number(wx.getStorageSync('userId')),
                                    
                                }, res => {
                                    wx.hideLoading();
                                    if (res.error) {
                                        wx.showToast({
                                            title: '提交失败',
                                            icon: 'none'
                                        })
                                        return;
                                    }
                                    that.setData({
                                        sucess: true
                                    })
                    
                                })
                            },
                            fail: (err) => {
                                util.postUrl(apiArr.repair, {
                                    appointment_time: time,
                                    customer_name: name,
                                    customer_phone: phone,
                                    device_id: selectEquipment.device_id,
                                    fault_desc: message,
                                    fault_imgs: fileList2.length !== 0 ? fileList2[0].url : '',
                                    user_id: Number(wx.getStorageSync('userId'))
                                }, res => {
                                    wx.hideLoading();
                                    if (res.error) {
                                        wx.showToast({
                                            title: '提交失败',
                                            icon: 'none'
                                        })
                                        return;
                                    }
                                    that.setData({
                                        sucess: true
                                    })
                    
                                })
                            }
                        });
                    }else{
                        util.postUrl(apiArr.repair, {
                            appointment_time: time,
                            customer_name: name,
                            customer_phone: phone,
                            device_id: selectEquipment.device_id,
                            fault_desc: message,
                            fault_imgs: fileList2.length !== 0 ? fileList2[0].url : '',
                            user_id: Number(wx.getStorageSync('userId'))
                        }, res => {
                            wx.hideLoading();
                            if (res.error) {
                                wx.showToast({
                                    title: '提交失败',
                                    icon: 'none'
                                })
                                return;
                            }
                            that.setData({
                                sucess: true
                            })
            
                        })
                    }
                }
            },
           fail:()=>{
            util.postUrl(apiArr.repair, {
                appointment_time: time,
                customer_name: name,
                customer_phone: phone,
                device_id: selectEquipment.device_id,
                fault_desc: message,
                fault_imgs: fileList2.length !== 0 ? fileList2[0].url : '',
                user_id: Number(wx.getStorageSync('userId'))
            }, res => {
                wx.hideLoading();
                if (res.error) {
                    wx.showToast({
                        title: '提交失败',
                        icon: 'none'
                    })
                    return;
                }
                that.setData({
                    sucess: true
                })

            })
           }
        });
    },

    getSSQ() {
        let that = this
        util.postUrl2(apiArr.city, {}, res => {
            util.postUrl2(apiArr.area, {}, res1 => {
                util.postUrl2(apiArr.business, {}, res2 => {
                    wx.hideLoading();
                    // 省列表来自 res
                    let cityList = res.data.data.rows;
                    // 市列表来自 res1
                    let areaList = res1.data.data.rows;
                    // 区列表来自 res2
                    let businessList = res2.data.data.rows;
                    
                    // 处理市列表，将衡水市放到最后
                    let hengshuiIndex = areaList.findIndex(item => item.name === '衡水市');
                    console.log(hengshuiIndex, 'hengshuiIndex');
                    if (hengshuiIndex !== -1) {
                        const hengshui = areaList.splice(hengshuiIndex, 1)[0];
                        areaList.push(hengshui);
                    }

                    console.log(businessList);
                    // 处理区列表，将衡水市的桃城区放到最后一个
                    let taochengIndex = businessList.findIndex(item => item.business_name === '桃城区');
                    if (taochengIndex !== -1) {
                        const taocheng = businessList.splice(taochengIndex, 1)[0];
                        businessList.unshift(taocheng);
                    }


                    // 默认展示第一条数据的省、市和区
                    let newArea = res1.data.data.rows.filter((item) => {
                        return item.city_id === res.data.data.rows[0].city_id
                    });
                    let newbus = res2.data.data.rows.filter((item) => {
                        return item.area_id === res1.data.data.rows[0].area_id
                    });

                    // 正确存储数据
                    wx.setStorageSync('cityList', cityList)
                    wx.setStorageSync('areaList', areaList)
                    wx.setStorageSync('businessList', businessList)

                    this.setData({
                        cityList: cityList,
                        areaList: areaList,
                        businessList: businessList,
                        newAreaList: newArea,  // 默认展示市
                        newBusiness: newbus, // 默认展示区
                        confirmCity: cityList[0],
                        confirmArea: newArea[0],
                        confirmBusiness: newbus[0],
                    })
                })
            })
        })
    },
    onClose2() {
        this.setData({
            show2: false
        })
    },

    bindChange(e) {
        const { value } = e.detail;
        const { cityList, areaList, businessList } = this.data;
        // 每次切换时，根据当前点击的省过滤出所属市区，并且试试变化县/区
        let newArea = areaList.filter((item) => item.city_id === cityList[value[0]].city_id);
        let newbus = businessList.filter((item) => item.area_id === newArea[value[1]].area_id);
        this.setData({
            newAreaList: newArea,
            newBusiness: newbus,
            confirmCity: cityList[value[0]],
            confirmArea: newArea[value[1]],
            confirmBusiness: newbus[value[2]],
        })
    },
    onOk() {
        const { confirmCity, confirmArea, confirmBusiness } = this.data;
        console.log(confirmCity, confirmArea, confirmBusiness);
        this.setData({
            show2: false,
            region: `${confirmCity.name}${confirmArea.area_name}${confirmBusiness.business_name}`,
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.init();
        this.getInfo()
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
        if (wx.getStorageSync('cityList') && wx.getStorageSync('areaList') && wx.getStorageSync('businessList')) {
            let res = wx.getStorageSync('cityList')
            let res1 = wx.getStorageSync('areaList')
            let res2 = wx.getStorageSync('businessList')
            console.log(res1);
            // 默认展示第一条数据 的市区 和 城区
            let newArea = res1.filter((item) => {
                return item.city_id === res[0].city_id
            });
            let newbus = res2.filter((item) => {
                return item.area_id === res1[0].area_id
            });
            this.setData({
                cityList: res,
                areaList: res1,
                businessList: res2,
                newAreaList: newArea,  // 默认展示 市区
                newBusiness: newbus, // 默认展示 县/区
                confirmCity: res1[0],
                confirmArea: newArea[0],
                confirmBusiness: newbus[0],
            })
        } else {
            that.getSSQ()
        }
    },

    init() {
        wx.showLoading({
            title: '加载中...',
            mask: true
        })
        postUrl(apiArr.BXDeviceList, {
            page_num: 1,
            page_size: 50, //TODO: 临时写一次获取50个，后续优化
            user_id: Number(wx.getStorageSync('userId'))
        }, res => {
            wx.hideLoading()
            if (res.msg == '操作成功') {
                if (res.rows) {
                    res.rows.forEach(item => {
                        item.product_icon = util.img_url + item.product_icon
                    })
                    this.setData({
                        equipmentList: res.rows || [],
                        selectEquipment:res.rows[0] || ''
                    })
                }
            }
        })
    },


    headerSelectClick(e) {
        console.log('e', e);
        this.setData({
            selectEquipment: e.currentTarget.dataset.item,
            name: e.currentTarget.dataset.item.customer_name,
            phone: e.currentTarget.dataset.item.customer_phone,
            address:e.currentTarget.dataset.item.address,
            region:e.currentTarget.dataset.item.region,
            equipmentShow: false,
        })
    },

    headerLookClick() {
        const pageUrl = getCurrentPages();
        // 获取当前页面的上一页 如果不是首页
        if (pageUrl[pageUrl.length - 2].route !== 'pages/index/newIndex/newIndex') {
            // 关闭当前页 返回上一页
            wx.navigateBack({
                delta: 1
            })
        } else {
            wx.redirectTo({
                url: '/packages/WaterPurifier/pages/Maintenance/Maintenance',
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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