let util = require('../../../../utils/util')
let apiArr = require('../../../../api/partner')
let apiArr2 = require('../../../../api/water_filter')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        fileList: [],
        fileList2: [],
        device_code: "",
        customer_name: "",
        customer_phone: "",
        region: "",
        address: "",
        deviceList: [],
        fault_desc: "",
        page_num: 1,
        page_size: 50,
        show: false,
        currentDeviceInfo: {
            region:"",
            address:"",
        },
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            }
            if (type === 'month') {
                return `${value}月`;
            }
            if (type === 'day') {
                return `${value}日`;
            }
            return value;
        },
        show2: false,
        cityList: [],
        areaList: [],
        businessList: [],
        newAreaList: [],  // 默认展示 市区
        newBusiness: [], // 默认展示 县/区
        confirmCity: '',
        confirmArea: '',
        confirmBusiness: '',
        deviceInfo:{
            customer_name:"",
            customer_phone:"",
            device_code:"",
            address:"",
            region:""
        }
    },
    onClose2() {
        this.setData({
            show2: 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,
            "currentDeviceInfo.region": `${confirmCity.name}${confirmArea.area_name}${confirmBusiness.business_name}`,
        })
    },
  
    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],
                    })
                })
            })
        })
    },
    changeShow1() {
        let that = this
        wx.navigateTo({
            url: '/packages/partner/pages/chooseRepairDevice/chooseRepairDevice',
        })
    },
    getDeviceList() {
        let that = this
        util.postUrl4(apiArr.deviceList, {
            page_num: that.data.page_num,
            page_size: that.data.page_size,
        }, res => {
            that.setData({
                deviceList: res.list
            })
        })
    },

    changeAddress(e){
        console.log(e);
        let that = this
        that.setData({
            "currentDeviceInfo.address":e.detail.value
        })
    },

    updateFault_desc(e) {
        let that = this
        that.setData({
            fault_desc: e.detail.value
        })
    },

    confirmPackage(e) {
        let that = this
        that.setData({
            show: false,
            currentDeviceInfo: e.detail.value,
            device_code: e.detail.value.device_code
        })
    },
    onClose() {
        let that = this
        that.setData({
            show: false
        })
    },

    beforeRead(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
            })
        })
    },
    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
        })
    },
    changeCustomerPhone(e){
        console.log(e);
    },
    submit() {
        let that = this

        if (!that.data.deviceInfo.device_code) {
            return wx.showToast({
                title: '请选择维修设备',
                icon: "none"
            })
        }
        if (!that.data.fault_desc) {
            return wx.showToast({
                title: '请填写故障描述',
                icon: "none"
            })
        }

        if (!that.data.fileList.length) {
            return wx.showToast({
                title: '请上传故障图片',
                icon: "none"
            })
        }
        util.postUrl4(apiArr.createRepairOrder, {
            device_code: that.data.deviceInfo.device_code,
            appointment_time: '',
            fault_desc: that.data.fault_desc,
            fault_imgs: that.data.fileList2[0].url,
        }, res => {
            wx.showToast({
                title: '创建成功！',
                icon: "none"
            })
            setTimeout(() => {
                wx.navigateBack({
                    delta: 1
                })
            }, 1500)
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        that.getDeviceList()
        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() {

    }
})