// pages/login/login.js
import {getCityTree} from '../../api/feeddback.js'
import {getCityNameCode, getTenantData, getUserData, enterMini} from '../../api/login.js'
import {getOpenidData, getUserMessage} from '../../utils/getUserInfo.js'
import {getLocatonPermission} from '../../utils/getUserLocation.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 区域选项列表
        provinceOptions: [],
        cityOptions: [],
        districtOptions: [],
        provinceCurrent: -1, // 当前选择省
        cityCurrent: -1,
        districtCurrent: -1,
        params: {}, // 筛选条件
        obj: {},
        path: '/pages/FirstPage/index',
        fromType: 'tabbar',
        tenantId: '',
        tenantCurrent: -1, // 当前选择的租户数据index
        tenantOptions: [], // 租户列表
        formRules: {
            tenantId: {
                validator: function (value) {
                    return value;
                },
                warning: false
            }
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if(options) {
            this.setData({path: options.path, fromType: options.fromType})
        }
    },
    
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 隐藏返回图标
        wx.hideHomeButton();
        let positionParams = wx.getStorageSync('positionParams')
        let options = this.data.provinceOptions
        if(options.length === 0) {
            let provinceOptions = wx.getStorageSync('provinceOptions')
            if(provinceOptions.length) {
                this.setData({provinceOptions})
                if(Object.keys(positionParams).length) {
                    let params = this.data.params
                    params.provinceCode = positionParams.provinceCode
                    params.cityCode = positionParams.cityCode
                    params.districtCode = positionParams.districtCode
                    this.setData({
                        params,
                        provinceCurrent: positionParams.provinceCurrent,
                        cityCurrent: positionParams.cityCurrent,
                        cityOptions: positionParams.cityOptions,
                        districtCurrent: positionParams.districtCurrent,
                        districtOptions: positionParams.districtOptions
                    })
                    // 获取租户信息
                    this.getTenantByParams(params)
                } else {
                    this.getUserLocation()
                }
            } else {
                this.getCityTreeList().then(res=> {
                    if(Object.keys(positionParams).length) {
                        let params = this.data.params
                        params.provinceCode = positionParams.provinceCode
                        params.cityCode = positionParams.cityCode
                        params.districtCode = positionParams.districtCode
                        this.setData({
                            params,
                            provinceCurrent: positionParams.provinceCurrent,
                            cityCurrent: positionParams.cityCurrent,
                            cityOptions: positionParams.cityOptions,
                            districtCurrent: positionParams.districtCurrent,
                            districtOptions: positionParams.districtOptions
                        })
                         wx.setStorage({
                            key: 'positionParams',
                            data: positionParams
                        })
                    } else {
                        this.getUserLocation()
                    }
                })
            }
        }
        const tenantObj = wx.getStorageSync('tenant')
        if(tenantObj) {
            const {tenantCurrent, tenantId} = tenantObj
            this.setData({tenantCurrent, tenantId})
        }
        const openid = wx.getStorageSync('openid')
        if(openid) {
            this.setData({openid})
        } else {
            getOpenidData().then(res=> {
                this.setData({openid: res.openid})
            })
        }
    },
    validate(name) {
        let formRules = this.data.formRules;
        let validator = formRules[name].validator
        let result = validator ? !validator(this.data[name]) : false;
        formRules[name].warning = result
        this.setData({formRules})
        return result
    },
    validateForm() {
        return new Promise((resolve, reject) => {
          try {
            let formRules = this.data.formRules;
            let result = false;
            for (let key in formRules) {
              let temp = this.validate(key)
              if (temp) {
                result = temp
              }
            }
            resolve(!result)
          } catch (e) {
            reject(e)
          }
        })
    },
    /**
     * 根据省市区查询已有租户
     */
    getTenantByParams(params) {
        getTenantData(params).then(res=> {
            if(res.code === 0) {
                this.setData({
                    tenantOptions: res.data
                })
            }
        })
    },

    /**
     * 选择租户
     */
    selectTenant(e) {
        const tenantCurrent = e.detail.value
        let tenantId = this.data.tenantOptions[tenantCurrent].id
        this.setData({
            tenantCurrent,
            tenantId
        })
        this.validate('tenantId')
    },
    /**
     * 根据name查找list
     */
    getListByName(obj) {
        let provinceOptions = this.data.provinceOptions
        let provinceCurrent, cityCurrent, districtCurrent, cityOptions, districtOptions
        let params = this.data.params
        params.provinceCode = obj.provinceCode
        params.cityCode = obj.cityCode
        params.districtCode = obj.districtCode
        if(provinceOptions.length) {
            provinceOptions.forEach((item,index)=> {
                if(item.citycode === obj.provinceCode) {
                    provinceCurrent = index
                    cityOptions = item?.itemList || []
                    if(cityOptions.length) {
                        cityOptions.forEach((i, j)=> {
                            if(i.citycode === obj.cityCode) {
                                cityCurrent = j
                                districtOptions = i?.itemList || []
                                if (districtOptions.length) {
                                    districtOptions.forEach((m, n) => {
                                        if(m.citycode === obj.districtCode) {
                                            districtCurrent = n
                                        }
                                    })
                                }
                            }
                        })
                    }
                }
            })
        }
        this.setData({provinceCurrent, cityCurrent, districtCurrent, cityOptions, districtOptions, params})
    },

    /* 获取省市区 */
    getCityTreeList() {
        return new Promise((resolve)=> {
            getCityTree().then(res=> {
                wx.setStorage({
                    key: 'provinceOptions',
                    data: res.data
                })
                this.setData({
                    provinceOptions: res.data
                })
                resolve(res)
            })
        })
    },
    /* 筛选 */
    updateAreaChange(e) {
        // 清空租户信息
        this.setData({
            tenantId: '', 
            tenantCurrent: -1,
            tenantOptions: [],
        })
        const type = e.target.dataset.type
        const current = e.detail.current
        let params = this.data.params
        let code = this.data[type+'Options'][current].citycode
        params[type+'Code'] = code
        let itemList = this.data[type+'Options'][current].itemList || []
        if(type === 'province') {
            this.setData({
                provinceCurrent: current,
                cityOptions: itemList,
                cityCurrent: -1,
                districtCurrent: -1
            })
            params.cityCode = ""
            params.districtCode = ""
        } else if(type === 'city') {
            this.setData({
                districtOptions: itemList,
                cityCurrent: current,
                districtCurrent: -1
            })
            params.districtCode = ""
        } else if(type === 'district') {
            this.setData({districtCurrent: current})
        }
        this.setData({
            params: params
        })
        this.getTenantByParams(params)
    },
    /* 根据current获取当前选中的值 */
    getValueByCurrent(current,type) {
        let code = this.data[type+'Options'][current].value
        return code
    },
    // 获取用户位置信息
    getUserLocation(e) {
        let cityObj = wx.getStorageSync('cityObj')
        if(!Object.keys(cityObj).length) {
            getLocatonPermission().then(res=> {
                wx.setStorage({
                    key: 'location',
                    data: res
                })
                let latlng = {}
                latlng.lat = res.latitude
                latlng.lng = res.longitude
                getCityNameCode(latlng).then(res=> {
                    let cityObj = res.data
                    const params = {
                        provinceCode: cityObj.provinceCode,
                        cityCode: cityObj.cityCode,
                        districtCode: cityObj.districtCode
                    }
                    this.setData({cityObj})
                    this.getListByName(cityObj)
                    this.getTenantByParams(params)
                })
            })
        }
    },
    /**
     * 进入首页
     */
    goHome() {
        this.validateForm().then(res => {
            if(res) {
                enterMini({openid: this.data.openid, tenantId: this.data.tenantId}).then(item=> {
                    if(item.code === 0) {
                        const tenantObj = {
                            tenantCurrent: this.data.tenantCurrent,
                            tenantId: this.data.tenantId
                        }
                        wx.setStorage({
                            key: 'tenant',
                            data: tenantObj
                        })
                        // 进入首页
                        const path = this.data.path
                        const fromType = this.data.fromType
                        if(fromType === 'page') {
                            wx.redirectTo({
                                url: path,
                            })
                        } else {
                            wx.switchTab({
                                url: path,
                            })
                        }
                    }
                })
            }
        })
    }
})