// packages/partner/pages/newWorkOrder/newWorkOrder.js
import apiArr from '../../../../api/partner';
import apiArr2 from '../../../../api/water_filter'
import util from '../../../../utils/util';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        admin: "",
        show: false,

        region: "",//省市区
        remark: "",//备注
        address: "",//详细地址？

        package: {},//套餐
        customer_name: "",//顾客姓名
        customer_phone: "",//顾客电话
        customer_id: "",
        area: "",
        address: "",

        show3: false,
        show2: false,
        show4: false,
        cityList: [],
        areaList: [],
        businessList: [],
        newAreaList: [],  // 默认展示 市区
        newBusiness: [], // 默认展示 县/区
        confirmCity: '',
        confirmArea: '',
        confirmBusiness: '',
        minDate: new Date().getTime(),
        time: "",
        packageList: [],//套餐列表
        masterList: [], //师傅列表
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            }
            if (type === 'month') {
                return `${value}月`;
            }
            if (type === 'day') {
                return `${value}日`;
            }
            return value;
        },
        product: "",
        show5: false,
        productList: []
    },

    changeShow5() {
        let that = this
        that.setData({
            show5: true
        })
    },
    cancel5() {
        let that = this
        that.setData({
            show5: false
        })
    },
    changeCustomerName(e) {
        let that = this
        that.setData({
            customer_name: e.detail.value
        })
    },
    changeCustomerPhone(e) {
        let that = this
        that.setData({
            customer_phone: e.detail.value
        })
        if(e.detail.value.length == 11){
            that.searchCustomer(e.detail.value)
        }
    },

    searchCustomer(e) {
        let that = this
        util.postUrl4(apiArr.phoneSearch, {
            phone: e
        }, res => {
            console.log(res);
            if (res.row.length == 1) {
                that.setData({
                    customer_name: res.row[0].name,
                    address: res.row[0].address,
                    customer_id: res.row[0].info_id,
                    area:res.row[0].region,
                    address:res.row[0].address,
                    customer_phone:res.row[0].phone,
                })
            } else {
                that.setData({
                    customer_name: '',
                    address: '',
                    customer_id: 0
                })
            }
        })
    },

    changeAddress(e) {
        let that = this
        that.setData({
            address: e.detail.value
        })
    },
    onClose() {
        let that = this
        that.setData({
            show: false
        })
    },
    onClose2() {
        let that = this
        that.setData({
            show2: false
        })
    },
    onClose6() {
        console.log(123);
        let that = this
        that.setData({
            show3: false
        })
    },
    onClose4() {
        let that = this
        that.setData({
            show4: false
        })
    },
    changeShow3() {
        let that = this
        that.setData({
            show3: true
        })
    },
    changeShow4() {
        let that = this
        that.setData({
            show4: true
        })
    },

    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,
            show4: false
        })
    },

    headerAreaClick() {
        this.setData({
            show2: 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({
            show2: false,
            area: `${confirmCity.name}${confirmArea.area_name}${confirmBusiness.business_name}`,
        })
    },
    onClose3() {
        this.setData({
            show2: false,
        })
    },
    getSSQ() {
        let that = this
        util.postUrl2(apiArr2.city, {}, res => {
            util.postUrl2(apiArr2.area, {}, res1 => {
                util.postUrl2(apiArr2.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],
                    })
                })
            })
        })
    },

    changeRemark(e) {
        let that = this
        that.setData({
            remark: e.detail.value
        })
    },

    confirmPackage3(e) {
        console.log(e);
        let that = this
        that.setData({
            masterInfo: e.detail.value,
            show3: false
        })
    },


    //套餐显示
    changeShow1() {
        let that = this
        that.setData({
            show: true
        })
    },
    //套餐取消
    cancel1() {
        let that = this
        that.setData({
            show: false
        })
    },
    confirmproduct(e) {
        let that = this
        that.setData({
            product: e.detail.value,
            show5: false,
        })
    },
    confirmPackage(e) {
        let that = this
        that.setData({
            package: e.detail.value,
            show: false,
        })
        util.postUrl4(apiArr.getproductList, {
            package_id: e.detail.value.package_id
        }, res => {
            console.log(res);
            that.setData({
                productList: res.rows
            })
        })
    },
    //获取套餐详情
    getPackageList() {
        let that = this
        util.postUrl4(apiArr.getPackageList, {
            dealer_id: that.data.admin.shop_id
        }, res => {

            if (res.msg == '操作成功') {
                that.setData({
                    packageList: res.rows
                })
            }
        })
    },


    getMasterList() {
        let that = this
        util.postUrl4(apiArr.getMasterList, {
            page_num: 1,
            page_size: 50,
            dealer_id: that.data.admin.shop_id
        }, res => {
            if (res.msg == '操作成功') {
                that.setData({
                    masterList: res.rows
                })
            }
        })
    },

    submit() {
        let that = this

        if (!that.data.package) {
            return wx.showToast({
                title: '请选择套餐',
                icon: "none"
            })
        }
        if (!that.data.product) {
            return wx.showToast({
                title: '请选择产品',
                icon: "none"
            })
        }
        if (!that.data.customer_name) {
            return wx.showToast({
                title: '请输入客户姓名',
                icon: "none"
            })
        }
        if (!that.data.customer_phone) {
            return wx.showToast({
                title: '请输入客户电话',
                icon: "none"
            })
        }
        if (!util.isPhone(that.data.customer_phone)) {
            return wx.showToast({
                title: '请输入正确客户电话',
                icon: "none"
            })
        }
        if (!that.data.area) {
            return wx.showToast({
                title: '请选择所在区域',
                icon: "none"
            })
        }
        if (!that.data.address) {
            return wx.showToast({
                title: '请输入详细地址',
                icon: "none"
            })
        }
        if (!that.data.masterInfo) {
            return wx.showToast({
                title: '请选择维修师傅',
                icon: "none"
            })
        }
        if (!that.data.time) {
            return wx.showToast({
                title: '请选择预约时间',
                icon: "none"
            })
        }

        util.postUrl4(apiArr.createNewOrder, {
            packages_id: that.data.package.package_id,
            product_id: that.data.product.product_id,
            customer_id: that.data.customer_id,
            customer_name: that.data.customer_name,
            customer_phone: that.data.customer_phone,
            region: that.data.area,
            address: that.data.address,
            remark: that.data.remark,
            repairman_id: that.data.masterInfo.info_id,
            dealer_id: that.data.admin.shop_id,
            city_id: that.data.confirmCity.city_id,
            area_id: that.data.confirmArea.area_id,
            business_id: that.data.confirmBusiness.business_id,
            appointment_time: that.data.time + ':00',
            user_id: wx.getStorageSync('userId') ? wx.getStorageSync('userId') : 0,
        }, res => {
            console.log(res);
            if (res.msg == '操作成功') {
                wx.showToast({
                    title: '创建成功！',
                    icon: "none"
                })
                // wx.navigateBack({         //返回上一页  
                //     delta: 1
                // })
                setTimeout(()=>{
                    wx.navigateTo({
                      url: `/packages/partner/pages/OrderMsgInfo/OrderMsgInfo?type=0&id=${res.install_id}`,
                    })
                },1500)

            } else {
                wx.showToast({
                    title: '创建失败！',
                    icon: "none"
                })
            }
        })
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        that.setData({
            admin: wx.getStorageSync('admin')
        })
        console.log(apiArr.getPackageList,'asd');

        that.getPackageList()
        that.getMasterList()

        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()
        }
    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})