import { _decorator, Component, instantiate, Node, Prefab, ScrollView } from 'cc';
import { base_ui } from '../../fw/base_ui';
import { mailbox_read_item } from './mailbox_read_item';
import { http } from '../../http';
import { config } from '../../config';
import { mail_item_data } from '../../data';
import { uiManager } from '../../manager/uiManager';
import { mailbox_details } from './mailbox_details';
import { reward_tips_view } from '../reward_tips_view/reward_tips_view';
import { ClientEvent } from '../../lib/clientEvent';
import { tools } from '../../tools';
const { ccclass, property } = _decorator;

@ccclass('mailbox')
export class mailbox extends base_ui {
    @property(Node) btn_back:Node = null

    @property(Node) img_empty:Node = null
    @property(Node) content_bg:Node = null
    @property(Node) content_scrollView:Node = null
    @property(Node) content:Node = null
    @property(Prefab) read_item:Prefab = null
    @property(Node) btn_delete_read:Node = null
    @property(Node) btn_get_all:Node = null

    @property(Node) details_bg:Node = null

    private data_list:mail_item_data[] = []
    private page:number = 1
    private limit:number = 15
    private is_loading:boolean = false
    private is_request:boolean = true
    start() {
        this.onButtonListen(this.btn_back, ()=>{
            this.close()
        })
        this.onButtonListen(this.btn_delete_read, ()=>{
            uiManager.showModal('删除已读?', '', (res)=>{
                if(res.confirm) {
                    this.requestDelete(1,0, ()=>{
                        this.requestListData(false,()=>{
                            uiManager.showToast('已删除')
                        })
                    })
                }
            })
        })
        this.onButtonListen(this.btn_get_all, ()=>{
            uiManager.showModal('全部领取?', '', (res)=>{
                if(res.confirm) {
                    this.requestRetrieve(1,0,()=>{
                        this.requestListData(false, ()=>{
                            uiManager.showToast('领取成功')
                        })
                    })
                }
            })
        })
        this.content_scrollView.on(ScrollView.EventType.SCROLL_TO_BOTTOM, this.onScrollToBottom, this)

        this.content_bg.active = false
        this.img_empty.active = false
        this.requestListData(false)
    }

    private onScrollToBottom() {
        if(this.is_request==false) { 
            return
        }
        if(this.is_loading) { 
            return 
        }
        console.log('滑动到底部开始加载数据=',this.page)
        this.requestListData(true)
    }

    private showEmpty(show:boolean) {
        if(show) {
            this.content_bg.active = false
            this.img_empty.active = true
        } else {
            this.content_bg.active = true
            this.img_empty.active = false
        }
    }

    private requestListData(is_load_more:boolean, suc_cb=null) {
        if(is_load_more==false) {
            this.page = 1
        }

        this.is_loading = true
        uiManager.Instance().showLoading()
        let opt = {'page':this.page, 'limit':this.limit}
        http.post(config.API.mail_lists,opt, (err,d)=>{
            setTimeout(()=>{
                this.is_loading = false
                uiManager.Instance().hideLoading()
            },500)
            if(!err){
                let nd = JSON.parse(d)
                if(nd.code === config.status.SUCCESS){
                    // console.log("mail data", nd.content)
                    if(this.page==1) {
                        this.data_list = []
                        this.content.removeAllChildren()
                    }
                    this.data_list = this.data_list.concat(nd.content)
                    if(this.data_list.length > 0) {
                        this.showEmpty(false)
                        for (let index = 0; index < this.data_list.length; index++) {
                            const element = this.data_list[index];
                            let item = instantiate(this.read_item)
                            item.parent = this.content
                            item.getComponent(mailbox_read_item).initView(element,this.onClickItem.bind(this))
                        }

                        this.page += 1
                        if(nd.content.length<this.limit) {
                            this.is_request = false
                        }
                    } else {
                        this.is_request = false
                        this.showEmpty(true)
                    }
                }
                suc_cb && suc_cb()
            }
        })
    }

    private onClickItem(item:mailbox_read_item) {
        this.details_bg.active = true
        this.details_bg.getComponent(mailbox_details).initView(item.getData(), 
        (v:mailbox_details)=>{
            uiManager.showModal('删除已读?', '', (res)=>{
                if(res.confirm) {
                    this.details_bg.active = false
                    this.requestDelete(0,v.getData().id, ()=>{
                        uiManager.showToast('已删除')
                        this.deleteDataLocalHandle(item)
                    })
                }
            })
        }, (v:mailbox_details)=>{
            this.details_bg.active = false
            let data = v.getData()
            if(data.state==0) {
                this.requestRetrieve(0,v.getData().id, ()=>{
                    uiManager.showToast('领取成功')
                    data.state = 1
                    item.setData(data)
                })
            }
        })
    }

    // 领取邮件 stype 0:普通领取 1:一键领取
    private requestRetrieve(stype:number, id:number, success_cb) {
        let opt = {'stype':stype, 'id':id}
        uiManager.Instance().showLoading('正在领取...')
        http.post(config.API.mail_retrieve,opt,  (err,d)=>{
            uiManager.Instance().hideLoading()
            if(!err){
                let nd = JSON.parse(d)
                if(nd.code === config.status.SUCCESS){
                    let list = nd.content
                    uiManager.Instance().showUi(config.UI.ui_reward_tips_view, null, (node:Node)=>{
                        node.getComponent(reward_tips_view).initView(list)
                        success_cb && success_cb()
                    })
                    
                    this.retrieveLaterRedDotHandle(stype)
                }
            }
        })
    }

    private retrieveLaterRedDotHandle(stype:number) {
        if(stype==1) {
            tools.user_red_dot_data.mail_unread_number = 0
        } else {
            tools.user_red_dot_data.mail_unread_number -=1
        }
        ClientEvent.dispatchEvent(config.UI_EVENT.UPDATE_MAIL_RED_DOT_STATUS)
    }

    // 删除邮件 stype 0:普通删除 1:一键删除
    private requestDelete(stype:number, id:number, success_cb) {
        let opt = {'stype':stype, 'id':id}
        uiManager.Instance().showLoading('正在删除...')
        http.post(config.API.mail_del,opt,  (err,d)=>{
            uiManager.Instance().hideLoading()
            if(!err){
                let nd = JSON.parse(d)
                if(nd.code === config.status.SUCCESS){
                    success_cb && success_cb()
                }
            }
        })
    }

    private deleteDataLocalHandle(item:mailbox_read_item) {
        if(item.node.isChildOf(this.content)) {
            this.content.removeChild(item.node)
            for (let index = 0; index < this.data_list.length; index++) {
                const element = this.data_list[index];
                if(element.id==item.getData().id) {
                    this.data_list.splice(index,1)
                    break
                }
            }
            if(this.data_list.length<=0) {
                this.showEmpty(true)
            }
        }
    }
}

