// 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: [],
        positionParams: {},
        params: {}, // 筛选条件
        path: '/pages/FirstPage/index',
        fromType: 'tabbar',
        tenantId: '',
        tenantCurrent: -1, // 当前选择的租户数据index
        tenantCode: null,
        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,
                        positionParams
                    })
                    // 获取租户信息
                    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
                        })
                    } else {
                        this.getUserLocation()
                    }
                })
            }
        }
        const tenantObj = wx.getStorageSync('tenant')
        if(tenantObj) {
            const {tenantCurrent, tenantId} = tenantObj
            this.setData({tenantCurrent, tenantId})
        }
        const openid = wx.getStorageSync('openid')
        const unionid = wx.getStorageSync('unionid')
        if(openid) {
            this.setData({openid,unionid})
        } else {
            getOpenidData().then(res=> {
                this.setData({openid: res.openid, unionid: res.unionid})
            })
        }
    },
    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
        let tenantCode = this.data.tenantOptions[tenantCurrent].code
        this.setData({
            tenantCurrent,
            tenantId,
            tenantCode
        })
        this.validate('tenantId')
    },
    /**
     * 根据name查找list
     */
    getListByName(obj) {
        let provinceOptions = this.data.provinceOptions
        let positionParams = this.data.positionParams
        let params = this.data.params
        params.provinceCode = obj.provinceCode
        params.cityCode = obj.cityCode
        params.districtCode = obj.districtCode
        positionParams = {...positionParams,...params}
        if(provinceOptions.length) {
            provinceOptions.forEach((item,index)=> {
                if(item.citycode === obj.provinceCode) {
                    positionParams.provinceCurrent = index
                    positionParams.provinceName = item.name
                    positionParams.cityOptions = item?.itemList || []
                    if(positionParams.cityOptions.length) {
                        positionParams.cityOptions.forEach((i, j)=> {
                            if(i.citycode === obj.cityCode) {
                                positionParams.cityCurrent = j
                                positionParams.cityName = i.name
                                positionParams.districtOptions = i?.itemList || []
                                if (positionParams.districtOptions.length) {
                                    positionParams.districtOptions.forEach((m, n) => {
                                        if(m.citycode === obj.districtCode) {
                                            positionParams.districtCurrent = n
                                            positionParams.districtName = m.name
                                        }
                                    })
                                }
                            }
                        })
                    }
                }
            })
        }
        this.setData({positionParams, 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 positionParams = this.data.positionParams
        let params = this.data.params
        let options = []
        if(type === 'province') {
            options = this.data.provinceOptions
        } else {
            options = positionParams[type+'Options']
        }
        let code = options[current].citycode
        params[type+'Code'] = code
        let name = options[current].name
        let itemList = options[current].itemList || []
        positionParams[type + 'Current'] = current
        positionParams[type + 'Name'] = name
        if(type === 'province') {
            positionParams.cityOptions = itemList
            positionParams.cityCurrent = -1
            positionParams.cityName = ''
            positionParams.districtOptions = []
            positionParams.districtCurrent = -1
            positionParams.districtName = ''
            params.cityCode = ""
            params.districtCode = ""
        } else if(type === 'city') {
            positionParams.districtOptions = itemList
            positionParams.districtCurrent = -1
            positionParams.districtName = ''
            params.districtCode = ""
        }
        positionParams = {
            ...positionParams,
            ...params
        }
        this.setData({
            params,
            positionParams
        })
        this.getTenantByParams(params)
    },
    /* 根据current获取当前选中的值 */
    getValueByCurrent(current,type) {
        let code = this.data[type+'Options'][current].value
        return code
    },
    // 获取用户位置信息
    getUserLocation(e) {
        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)
            })
        })
    },
    // 存储省市区信息
    setAreaInfo() {
        let positionParams = this.data.positionParams
        positionParams.areaName = positionParams.districtName || positionParams.cityName || positionParams.provinceName || '' 
        positionParams = {
            ...positionParams,
            ...this.data.params
        }
        wx.setStorageSync('positionParams', positionParams)
    },
    /**
     * 进入首页
     */
    goHome() {
        this.setAreaInfo()
        this.validateForm().then(res => {
            if(res) {
                enterMini({openid: this.data.openid, unionid: this.data.unionid, tenantId: this.data.tenantId}).then(item=> {
                    if(item.code === 0) {
                        const tenantObj = {
                            tenantCurrent: this.data.tenantCurrent,
                            tenantId: this.data.tenantId,
                            tenantCode: this.data.tenantCode,
                        }
                        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,
                            })
                        }
                    }
                })
            }
        })
    }
})