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

// pages/deposit/deposit.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        deposit: {},
        agreed: false,
        show: false,//押金缴纳
        show2: false, //预约时间
        show3: false,//省市区
        show4: false,//选择押金类型
        customerName: '', // 客户姓名
        customerPhone: '', // 客户手机号
        time: '', // 预约时间
        cityList: [],
        areaList: [],
        businessList: [],
        newAreaList: [],  // 默认展示 市区
        newBusiness: [], // 默认展示 县/区
        confirmCity: '',
        confirmArea: '',
        confirmBusiness: '',
        name: "",
        phone: "",
        address: '', // 详细地址
        GoodsMsg: "",
        depositName: "",
        depositList: [],
        selectedDeposit: "",
        minDate: new Date().getTime(),
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            }
            if (type === 'month') {
                return `${value}月`;
            }
            if (type === 'day') {
                return `${value}日`;
            }
            return value;
        },

        swiperList:[],
        swiperActive:"0",
        options: [],
        selectedId: 1,// 已选中值，需回显时传
        showSelect: false, // [暂未发现]处理滚动选项区域时背景页面滚动问题
    },

    swiperChange(e){
        let that = this
        that.setData({
            swiperActive: e.detail.current
        })
    },
    handleChange(e) {
        console.log(e.detail); // {value: 3, label: "测试数据三"}
        let that = this
        let depositList = that.data.depositList
        depositList.forEach(item => {
            if (item.id == e.detail.id) {
                that.setData({
                    deposit: item,
                    selectedDeposit: item,
                    swiperList: item.imgList
                })
            }
        })
    },
    handleShow(e) {

    },


    changeDeposit() {
        let that = this
        that.setData({
            show4: true
        })
    },
    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({
            address: e.detail.value
        })
    },

    onDepositConfirm(event) {
        const { value } = event.detail;
        console.log(event);
        this.setData({
            selectedDeposit: value,
            show4: false,
            depositName: value.text
        });
    },

    onDepositCancel() {
        this.setData({ show4: false });
    },

    extractImagesFromRichText(richText) {
        const imageArray = [];
        const regex = /<img[^>]+src=["']([^"']+)["'][^>]*>/g;
        let match;

        while ((match = regex.exec(richText)) !== null) {
            imageArray.push({
                src: match[1],
                fullTag: match[0]
            });
        }

        return imageArray;
    },
    addImageStyles(richText) {
        return richText.replace(/<img([^>]*)>/g, (match, attributes) => {
            // 检查是否已有style属性
            if (/style\s*=\s*["'][^"']*["']/.test(attributes)) {
                return `<img${attributes.replace(
                    /style\s*=\s*["']([^"']*)["']/,
                    'style="$1;width:100% !important;height:100% !important;"'
                )}>`;
            } else {
                return `<img${attributes} style="width:100% !important;height:100% !important;">`;
            }
        });
    },

    getDepositList() {
        let that = this
        util.postUrl(apiArr.getDepositList, { dealer_id: wx.getStorageSync('dealer_id') }, res => {
            const depositList = res.rows.map(item => ({
                id:item.id,
                text: item.title,
                value: item.id,
                price: item.price,
                desc: that.addImageStyles(item.desc),
                imgList: that.extractImagesFromRichText(item.desc)
            }));
            console.log(depositList,'223');
            that.setData({ depositList });
        })
    },
    getDeposit() {
        let that = this
        util.postUrl(apiArr.getDeposit, { dealer_id: wx.getStorageSync('dealer_id') }, res => {
            console.log(res);
            that.setData({
                deposit: res
            })
        })
    },
    handleAgreeChange() {
        this.setData({ agreed: !this.data.agreed });
    },
    yajin() {
        let that = this
        that.setData({
            show: !that.data.show
        })
    },
    inputCustomerName(e) {
        this.setData({
            customerName: e.detail.value
        });
    },

    // 输入客户手机号
    inputCustomerPhone(e) {
        this.setData({
            customerPhone: e.detail.value
        });
    },

    // 选择预约时间
    changeShow() {
        let that = this
        that.setData({
            show2: true
        })
    },
    headerAreaClick() {
        this.setData({
            show3: true
        })
    },


    // 省市区选择器
    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({
            show3: false,
            area: `${confirmCity.name}${confirmArea.area_name}${confirmBusiness.business_name}`,
        })
    },
    onClose3() {
        this.setData({
            show3: false,
        })
    },
    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],
                    })
                })
            })
        })
    },

    onClose() {
        let that = this
        that.setData({
            show2: false
        })
    },
    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({
            time,
            show2: false
        })
    },
    checkboxChange() {
        let that = this
        that.setData({
            agreed: !that.data.agreed
        })
    },




    handlePay() {
        let that = this
        if (!that.data.name) {
            wx.showToast({
                title: '请输入客户姓名',
                icon: "none"
            })
            return
        }

        if (!that.data.phone) {
            wx.showToast({
                title: '请输入客户电话',
                icon: "none"
            })
            return
        }

        if (!util.isPhone(that.data.phone)) {
            wx.showToast({
                title: '请输入正确的客户电话',
                icon: "none"
            })
            return
        }

        if (!that.data.time) {
            wx.showToast({
                title: '请选择预约时间',
                icon: "none"
            })
            return
        }
        if (!that.data.area) {
            wx.showToast({
                title: '请选择所在区域',
                icon: "none"
            })
            return
        }
        if (!that.data.address) {
            wx.showToast({
                title: '请填写详细地址',
                icon: "none"
            })
            return
        }
        if(!that.data.deposit.text){
            wx.showToast({
                title: '请选择产品套餐',
                icon: "none"
            })
            return
        }

        util.postUrl(apiArr.createPosit, {
            deal_deposit_id: that.data.selectedDeposit.value,
            price: String(that.data.selectedDeposit.price),
            customer_name: that.data.name,
            customer_phone: that.data.phone,
            address: that.data.address,
            appointment_time: that.data.time + ':00',
            city_id: that.data.confirmCity.city_id,
            area_id: that.data.confirmArea.area_id,
            business_id: that.data.confirmBusiness.business_id
        }, res => {
            that.setData({
                GoodsMsg: res
            })
            that.pay()
        })
    },

    pay() {
        let that = this

        util.postUrl2(PayJs.HsqueryPay, {
            total_amount: String(that.data.selectedDeposit.price * 100),
            // total_amount: String(1),
            subject: that.data.depositName,
            out_trade_no: that.data.GoodsMsg.order_no,
            remark: '',
            user_id: wx.getStorageSync('openId'),
            goods_id: that.data.GoodsMsg.id,
            quantity: "1",
            address: that.data.area + that.data.address,
            user: String(wx.getStorageSync('userId'))
        }, res => {
            const { resp_data, msg } = res.data.data
            console.log(msg);
            console.log(resp_data);
            if (msg == '成功') {
                wx.requestPayment({
                    timeStamp: String(resp_data.acc_resp_fields.time_stamp),
                    nonceStr: String(resp_data.acc_resp_fields.nonce_str),
                    package: String(resp_data.acc_resp_fields.package),
                    signType: String(resp_data.acc_resp_fields.sign_type),
                    paySign: String(resp_data.acc_resp_fields.pay_sign),
                    success(res) {
                        that.queryPay()
                    },
                    fail(fal) {
                        if (fal.errMsg == 'requestPayment:fail cancel') {
                            that.payFail(2)
                        } else {
                            that.payFail(1)
                        }
                    }
                })
            }

        })
    },


    payFail(e) {
        let that = this
        util.postUrl(PayJs.payFail, {
            order_id: that.data.GoodsMsg.id,
            type: "1",
            state: e,
        }, res => {
            console.log(res);
        })
    },

    queryPay() {
        let that = this
        util.postUrl2(PayJs.HsqueryPayByWechat, {
            out_trade_no: that.data.GoodsMsg.order_no
        }, res => {
            if (res.statusCode == '200') {
                wx.showToast({
                    title: '支付成功！',
                })
                wx.getSetting({
                    withSubscriptions: true,
                    success: (res) => {
                        if (res.subscriptionsSetting && res.subscriptionsSetting.mainSwitch) {
                            const itemSettings = res.subscriptionsSetting.itemSettings || {};
                            const tmplMap = {
                                '_s7GcsGNqapbnlLAJ5lUFexCEAx-dl4RD-DwwL9QqC4': '工单状态通知',
                                'VXRbeTG6gPPOrxTSwF_da8jzqH0UVHxQykYAH0XH51s': '设备故障通知',
                                'T87KsBIrVrjgO4VETEOpIn4c4-bsxOTpzM6lR0ghduo': '设备告警通知'
                            };

                            const unsubscribedTmplIds = [];
                            Object.keys(tmplMap).forEach(tmplId => {
                                if (itemSettings[tmplId] !== 'accept') {
                                    unsubscribedTmplIds.push(tmplId);
                                }
                            });

                            if (unsubscribedTmplIds.length > 0) {
                                wx.requestSubscribeMessage({
                                    tmplIds: unsubscribedTmplIds,
                                    success: (res) => {
                                        console.log('订阅成功', res);
                                        that.getUserInfo();
                                        // wx.reLaunch({
                                        //     url: '/pages/water_filter/water_filter',
                                        // })
                                    },
                                    fail: (err) => {
                                        console.error('订阅失败', err);
                                        that.getUserInfo();
                                        // wx.reLaunch({
                                        //     url: '/pages/water_filter/water_filter',
                                        // })
                                    }
                                });
                            } else {
                                that.getUserInfo();
                                // wx.reLaunch({
                                //     url: '/pages/water_filter/water_filter',
                                // })
                            }
                        }
                    },
                    fail: () => {
                        that.getUserInfo();
                        // wx.reLaunch({
                        //     url: '/pages/water_filter/water_filter',
                        // })
                    }
                });

            } else {
                wx.showToast({
                    title: res.msg,
                })
            }
        })
    },

    getUserInfo() {
        let that = this
        util.postUrl(apiArr.loginInfo, {}, ress => {
            if (ress.error) return;
            wx.setStorageSync('userId', ress.user_id);
            wx.setStorageSync('openId', ress.open_id);
            wx.setStorageSync('shopId', ress.wshop_id);
            wx.setStorageSync('mshopId', ress.mshop_id);
            wx.setStorageSync('dealer_id', ress.dealer_id);
            wx.setStorageSync('is_dev', ress.is_dev);

            wx.reLaunch({
                url: '/pages/water_filter/water_filter',
            })

            // if (ress.is_dev == 2) {

            // } else if (ress.is_dev == 3) {
            //     wx.navigateTo({
            //         url: '/pages/water_filter/water_filter',
            //     })
            // }
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        that.setData({
            phone: wx.getStorageSync('phone')
        })
        // that.getDeposit()
        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()
        }
        that.getDepositList()

        setTimeout(() => {
            that.setData({
                deposit: that.data.depositList[0],
                selectedDeposit: that.data.depositList[0],
                depositName: that.data.depositList[0].text,
                swiperList: that.data.depositList[0].imgList,
            })
        }, 1500)
    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})