//index.js
//获取应用实例
import { getRequirementsImpl, } from "../../service/impl/hwRequirement.impl";
import { bannerApi } from "../../service/hwUser";
import { getStorageSync } from "../../utils/util";
const app = getApp()
let cover_animation: any = {}
Page({
    /**
     * 页面的初始数据
     */
    data: {
        'indicator_dots': false, //轮播指示点
        'autoplay': true, //轮播自动播放
        'circular': true, //轮播衔接动画
        'interval': 3000, //轮播间隔时间
        'duration': 1500, //轮播动画时间
        'condition_animation': {}, //上方条件动画
        'list_animation': {}, //下方列表动画
        'cover_animation': {}, //选择地址动画
        'swiper': [], // 轮播列表
        'industry': '行业', //行业
        'price': '单价', //单价
        'district': '不限区域', //区域
        'conditionList': [], //现行条件列表
        'condition': '', //现行条件
        'action_index': 0, //现行条件索引
        'industry_index': 0, //行业索引
        'industry_id': '', //行业id
        'price_index': 0, //单价索引
        'price_id': '', //单价id
        'province_id': '', //省份ID
        'city_id': '', //城市ID
        'area_id': '', //地区ID
        'industryList': [{
            id: '',
            name: '不限行业'
        },
        {
            id: 0,
            name: '教育培训'
        },
        {
            id: 1,
            name: 'IT互联网'
        },
        {
            id: 2,
            name: '仓储物流'
        },
        {
            id: 3,
            name: '酒店餐饮'
        },
        {
            id: 4,
            name: '家政保洁'
        },
        {
            id: 5,
            name: '维修保养'
        },
        {
            id: 6,
            name: '会务会展'
        },
        {
            id: 7,
            name: '专业服务'
        },
        {
            id: 8,
            name: '生产制造'
        },
        {
            id: 9,
            name: '其他行业'
        },
        ], //行业列表
        'priceList': [{
            id: '',
            name: '不限'
        },
        {
            id: 1,
            name: '3K以下'
        },
        {
            id: 2,
            name: '3K-5K'
        },
        {
            id: 3,
            name: '5K-8K'
        },
        {
            id: 4,
            name: '8K-12K'
        },
        {
            id: 5,
            name: '12K-20K'
        },
        {
            id: 6,
            name: '20K-30K'
        },
        {
            id: 7,
            name: '30K以上'
        },
        ], // 单价列表
        'list': [], //需求列表
        'pageNo': 1,
        'isLast': false,
        'offline': false,
        'loading': true,
        'list_length': false,
        'show': false,
        'transition': true,
        'fixTop': 0,
        'scrollTop': 0,
        swiperIndex: 0
    },
    swiperChange(e: any) {
        this.setData({
            swiperIndex: e.detail.current
        })
    },
    /**
     * 展示删选条件
     * @condition {string}  条件  当获取的条件不等于data里面的条件时 不做改变   不等时 改变条件 以及对应的展示条件
     */
    chooseCondition(e: any) {
        const condition = e.currentTarget.dataset.condition === this.data.condition ? '' : e.currentTarget.dataset.condition;
        this.doAnimation(e.currentTarget.dataset.condition === this.data.condition)
        // this.doAnimation(false)
        // let action_index = this.data.condition === this.data.action_index ? [] : this.data[`${condition}_index`];
        this.setData({
            condition,
            // action_index
        })
    },
    /**
     * 展开区域选择
     * 
     */
    openArea() {
        this.doAnimation(true)
        cover_animation.left(0).step();
        this.setData({
            cover_animation: cover_animation.export(),
            condition: '',
        })
    },

    /**
     * 点击选择条件
     * 根据不同的条件插入不同的值
     */
    choose(e: any) {
        const index = e.currentTarget.dataset.index;
        const id = e.currentTarget.dataset.id;
        let condition = this.data.condition;
        let list: any[] = []
        if (condition === 'industry') {
            list = this.data.industryList
        } else {
            list = this.data.priceList
        }

        this.setData({
            [condition]: list[index].name,
            [`${condition}_index`]: index,
            [`${condition}_id`]: id,
            condition: '',
            list: [],
            loading: true
        }, () => {
            this.getList(1)
        })
        this.doAnimation(true)

    },

    /**
     * 保存地区
     * @district {string} 地区
     * @province_id {} 省份ID
     * @city_id {} 城市ID
     * @area_id {} 地区ID
     */
    saveDistrict(e: any) {
        cover_animation.left(750 + 'rpx').step();
        this.setData({
            cover_animation: cover_animation.export(),
            district: e.detail.area_name,
            province_id: e.detail.province_id,
            city_id: e.detail.city_id,
            area_id: e.detail.area_id,
            list: []
        }, () => {
            this.getList(1)
        })
    },
    /**
     * 关闭地区选择
     * @cover_animation 地区选择动画
     */
    coloseDistrict() {
        cover_animation.left(750 + 'rpx').step();
        this.setData({
            cover_animation: cover_animation.export()
        })
        this.doAnimation(true)
    },
    /**
     * 执行条件动画
     */
    doAnimation(status: boolean) {
        // const condition_animation = this.condition_animation;
        // const list_animation = this.list_animation;
        // const condition_length = status ? 0 : -412 + 'rpx'
        // const list_length = status ? 548 + 'rpx' : 201 + 'rpx'
        // condition_animation.top(condition_length).step();
        // list_animation.top(list_length).step();
        // this.setData({
        //   condition_animation: condition_animation.export(),
        //   list_animation: list_animation.export(),
        // })
        const fixTop = this.data.fixTop;
        const scrollTop = this.data.scrollTop;
        if (fixTop > scrollTop) {
            this.setData({
                transition: status
            })
        }
    },
    /**
     * 跳转个人中心
     */
    toPerson() {
        if (wx.getStorageSync('userId') && wx.getStorageSync('userToken')) {
            wx.navigateTo({
                url: '/pages/person/person',
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '你还未登陆，是否立即登录',
                cancelColor: '#888A8E',
                confirmColor: '#31364C',
                success: res => {
                    if (res.confirm) {
                        wx.reLaunch({
                            url: '/pages/login/login',
                        })
                    }
                }
            })
        }

    },
    /**
     * 跳转详情页
     */
    toDetail(e: any) {
        if (this.data.transition) {
            const id = e.currentTarget.dataset.id;
            wx.navigateTo({
                url: `/pages/detail/detail?id=${id}&&status=1`,
            })
        }
    },
    /**
     * 获取需求列表
     * @pageNo {number} 页码
     * @pageSize {number} 数据条数
     * @province_code {number} 省份代码
     * @city_code {number} 城市代码
     * @country_code {number} 地区代码
     * @trade_type {number} 行业类型
     * @priceType {number} 价格代号(1-7)(不限的话不传此参数)
     * @platform_id {number} 接单人用户所属平台id
     */
    getList(pageNo?: number, province_code?: number, city_code?: number, country_code?: number, trade_type?: number, priceType?: number) {
        let _pageNo: number = pageNo || this.data.pageNo
        let platform_id = 1
        const userInfo = wx.getStorageSync('userInfo')
        if (userInfo) {
            platform_id = userInfo.platformId
        }
        const param = Object.assign({
            pageNo,
            pageSize: 10,
            province_code,
            city_code,
            country_code,
            trade_type,
            priceType,
            platform_id
        }, {
            pageNo: _pageNo,
            province_code: this.data.province_id,
            city_code: this.data.city_id,
            country_code: this.data.area_id,
            trade_type: this.data.industry_id,
            priceType: this.data.price_id
        })
        getRequirementsImpl(param).then(res => {
            console.log('res=>', res);

            if (typeof res === 'string') {
                // 如果没有网络  展示网络故障界面
                if (res === 'offline' && this.data.list.length === 0) {
                    this.setData({
                        offline: true,
                        loading: false,
                        list_length: false
                    })
                }
            }
            if (<responseOptionsType>res) {
                const data = <responseOptionsType>res
                if (data.errCode === 0) {


                    if (_pageNo === 1 && data.data.requirements.length === 0) {
                        // this.doAnimation(false);
                        this.setData({
                            loading: false,
                            list_length: true,
                            offline: false
                        })
                        return
                    }
                    // 在成功后页数加一方便日后调用
                    _pageNo++;
                    data.data.requirements = data.data.requirements.map((value: any) => {
                        if (getStorageSync(`orderDetail_${value.id}`)) {
                            value.status = 5
                        }
                        return value
                    })
                    this.setData({
                        pageNo: _pageNo,
                        [`list[${_pageNo - 2}]`]: data.data.requirements,
                        isLast: data.data.isLast,
                        offline: false,
                        list_length: false,
                        loading: false
                    })
                }
            }
        }).catch(() => {
            this.setData({
                loading: false,
                list_length: true,
                offline: false
            })
        })
    },
    /**
     * 获取首页banner图
     */
    getBanner() {
        bannerApi().then(res => {
            const data = <responseOptionsType>res
            if (data.errCode === 0) {
                this.setData({
                    swiper: data.data.bannerList
                })
            }
        })
    },
    reload() {
        // 获取需求列表
        this.setData({
            list: [],
            pageNo: 1,
            scrollTop: 0
        }, () => {
            // 获取首页banner图
            this.getBanner();
            this.getList();
        })
        // app.utils.getHwUserInfo();
    },
    checkLogin() {
        if (wx.getStorageSync('userId') && wx.getStorageSync('userToken')) {
            if (wx.getStorageSync('userInfo').registerFrom === 0) {
                wx.reLaunch({
                    url: '/pages/success/success',
                })
            } else {
                this.reload();
                this.setData({
                    show: false
                })
            }
        } else {
            wx.reLaunch({
                url: '/pages/login/login',
            })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function () { this.getBanner(); },

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

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.setData({
            route: this.route
        })
        this.checkLogin()
        // this.reload()
        /**
         * 初始化动画
         * @condition_animation 条件框动画
         * @list_animation 需求列表动画
         * @cover_animation 地址选择动画
         */
        // this.condition_animation = wx.createAnimation({
        //   duration: 700,
        //   timingFunction: 'ease',
        // })
        // this.list_animation = wx.createAnimation({
        //   duration: 600,
        //   timingFunction: 'ease',
        // })
        cover_animation = wx.createAnimation({
            duration: 600,
            timingFunction: 'ease',
        })
        // 获取系统信息算出像素比
        wx.getSystemInfo({
            success: res => {
                this.setData({
                    per: 750 / res.windowWidth
                })
            }
        })
        // 获取绝对定位的高度
        wx.createSelectorQuery().select('.choose-area').boundingClientRect((rect) => {
            this.setData({
                fixTop: rect.top,
            })
        }).exec();
        if (app.globalData.webview) {
            wx.navigateTo({
                url: app.globalData.webview,
                success: () => {
                    app.globalData.webview = null
                }
            })
        }

    },

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

    },

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

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        this.setData({
            list: [],
            pageNo: 1,
            scrollTop: 0
        }, () => {
            this.getList()
        })
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        const isLast = this.data.isLast;
        if (isLast) {
            // wx.showToast({
            //   icon: 'none',
            //   title: '已经是最后一页了',
            // })
        } else {
            this.getList()
        }
    },

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

    },
    onPageScroll: function (res) {
        let top = res.scrollTop;
        this.setData({
            scrollTop: top
        });
    }
})