
import 'package:flutter/material.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';

import 'package:twong/api/index.dart';
import 'package:twong/pages/tabs.dart';
import 'package:twong/providers/message.dart';
import 'package:twong/providers/order_num.dart';
import 'package:twong/providers/user.dart';
import 'package:twong/utils/index.dart';
import 'package:twong/config/style.dart';
import 'package:twong/router/index.dart';
import 'package:twong/utils/image_utils.dart';
import 'package:twong/widgets/fsuper.dart';

class UserPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _UserPageState();
  }
}

class _UserPageState extends State<UserPage> {
  @override
  void initState() {
    super.initState();
    loadData();
  }

  void loadData() async {
    Network.inst.getUserInfo().then((res){
      // setState(() {});
    }).catchError((err, stack) {
      Log.e(err.toString() + stack.toString());
      BotToast.showText(text: err.toString());
    });

    // Network.inst.getOrderData().then((res) {
    //   // Provider.of<OrderNumModel>(context, listen: false).update(res);
    // }).catchError((err, stack) {
    //   Log.e(err.toString() + stack.toString());
    // });
  }

  Widget _buildHeader() {
    if (Cache.user == null) return Container(height: 124.px,
        color: DColors.Main, child: Center(child: Utils.loadingWidget));
    return Container(
        color: DColors.Main,
        padding: EdgeInsets.only(left: 12.px, right: 12.px),
        child: Column(
            children: [
              Container(height: 32.px, child: Row(
                children: [
                  Spacer(),
                  IconButton(icon: Icon(Icons.settings, color: Colors.white),
                      highlightColor: Colors.transparent,
                      onPressed: () async {
                        await Navigator.pushNamed(context, RouteNames.setting);
                        if (Cache.user == null && TabsState.inst != null) {
                          TabsState.inst.doItemTap(0);
                        }
                      }),
                  Consumer<MessageModel>(
                    builder: (context, model, child) =>
                        FSuper(
                          child1: Icon(IconFonts.message, color: Colors.white),
                          padding: EdgeInsets.only(left: 12.px, right: 12.px),
                          onClick: () =>
                              Navigator.pushNamed(context, RouteNames.message),
                          redPoint: model.data != null && model.data.length > 0,
                          redPointText: model.data == null ? "" : model.data
                              .length.toString(),
                          redPointColor: Colors.white,
                          redPointTextStyle: TextStyle(color: Colors.red,
                              fontSize: 10.px, fontWeight: FontWeight.bold),
                        ),
                  )
                ],
              )),
              Consumer<UserModel>(
                builder: (context, model, child) =>
                model.info == null ? Container()
                    : Row(
                  children: [
                    InkWell(
                      onTap: () {
                        Navigator.pushNamed(context, RouteNames.account);
                      },
                      child: Container(
                          margin: EdgeInsets.only(left: 12.px),
                          child: CircleAvatar(
                            radius: 34.px,
                            backgroundImage: CachedNetworkImageProvider(
                                model.info.avatar),
                          )),
                    ),
                    Expanded(child: Container(
                      margin: EdgeInsets.only(left: 22.px),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(model.info.nickname,
                              style: TextStyle(color: Colors.white,
                                  fontSize: 16.px)),
                          Text("我的ID: ${model.info.uid}",
                              style: TextStyle(color: Colors.white,
                                  fontSize: 12.px))
                        ],
                      ),
                    )),
                  ],
                ),
              )
            ])
    );
  }

  Widget _buildOrder(dynamic data) {
    List<String> titles = ['待付款', '待发货', '待收货', '待评价'];
    List<IconData> icons = [
      Icons.credit_card,
      Icons.shop,
      Icons.assignment_returned,
      Icons.message_outlined
    ];
    List<String> dataKeys =
    ["unpaid_count", "unshipped_count", "received_count", "evaluated_count"];

    List<Widget> widgets = [];
    for (var i = 0; i < titles.length; i ++) {
      widgets.add(Expanded(child: FSuper(
        text: titles[i],
        padding: EdgeInsets.all(12.px),
        margin: EdgeInsets.only(top: 20.px),
        child1: Icon(icons[i]),
        child1Margin: EdgeInsets.only(bottom: 20.px),
        redPoint: data != null && data[dataKeys[i]] > 0,
        redPointText: data == null ? "" : data[dataKeys[i]].toString(),
        redPointOffset: Offset(-20.px, -6.px),
        onClick: () => Navigator.pushNamed(context, RouteNames.order, arguments: i),
      )));
    }

    widgets.add(Expanded(child: FSuper(
      text: "客服",
      padding: EdgeInsets.all(12.px),
      margin: EdgeInsets.only(top: 20.px),
      child1: Icon(Icons.phone),
      child1Margin: EdgeInsets.only(bottom: 20.px),
      onClick: () => Utils.notOpen(),
    )));

    return Container(
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(6.px)
      ),
      child: Column(
        children: <Widget>[
          InkWell(
            onTap: () { Navigator.pushNamed(context, RouteNames.order, arguments: 0); },
            child: Container(
                padding: EdgeInsets.only(left: 16.px, right: 12.px, top: 12.px, bottom: 4.px),
                child: Row(children: [
                  Expanded(
                      child: Text("我的订单", style: TextStyle(fontSize: 14.px,
                        fontWeight: FontWeight.bold))),
                  Text("查看所有订单 ", style: TextStyle(color: Colors.grey)),
                  Icon(Icons.keyboard_arrow_right, color: Colors.grey)
                ])),
          ),
          Divider(),
          Row(children: widgets)
        ],
      ),
    );
  }

  Widget _buildMenuList() {
    List<String> titles = ['收藏管理', '地址管理'];
    List<IconData> icons = [
      Icons.favorite,
      Icons.room,
    ];
    List<String> routers = [
      RouteNames.favours,
      RouteNames.address
    ];

    List<Widget> widgets = [];
    for (var idx = 0; idx < titles.length; idx++) {
      widgets.add(InkWell(
        highlightColor: Colors.transparent,
        onTap: () { Navigator.pushNamed(context, routers[idx]); },
        child: Container(
            height: 40.px,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(6.px)
            ),
            padding: EdgeInsets.only(left: 10.px, right: 10.px),
            margin: EdgeInsets.only(bottom: 8.px, left: 12.px, right: 12.px),
            child: Row(children: [
              Icon(icons[idx]),
              Container(width: 16.px),
              Expanded(child: Text(titles[idx])),
              Icon(Icons.keyboard_arrow_right, color: Colors.grey)
            ])
        ),
      ));
    }
    return Column(children: widgets);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: DColors.Main,
      body: SafeArea(
        child: Container(
          color: DColors.back,
          child: ListView(
            physics: NeverScrollableScrollPhysics(),
            children: <Widget>[
              _buildHeader(),
              Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [DColors.Main, DColors.back],
                    ),
                  ),
                  padding: EdgeInsets.all(8.px),
                  child: Consumer<OrderNumModel>(
                    builder: (context, model, child) => _buildOrder(model.data),
                  )
              ),
              _buildViper(),
              _buildMenuList(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildViper() {
    if(!Cache.isVip) {
      return Container();
    }
    return Container(
      padding: EdgeInsets.only(top: 6.px, left: 10.px, right: 10.px, bottom: 8.px),
      child: Row(
        children: [
          Expanded(child: InkWell(
            onTap: () => Navigator.pushNamed(context, RouteNames.vipCenter),
            child: Container(
              height: 48.px,
              margin: EdgeInsets.only(right: 6.px),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(6.px)
              ),
              child: Row(
                children: [
                  Container(
                    margin: EdgeInsets.only(left: 12.px, right: 12.px),
                    child: Icon(Icons.keyboard),
                  ),
                  Expanded(child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text("会员中心", style: TextStyle(color: Colors.black, fontSize: 13.px)),
                      Text("点击查看您的会员权益", style: TextStyle(color: Colors.grey, fontSize: 10.px)),
                    ],
                  ))
                ],
              ),
            ),
          )),
          Expanded(child: InkWell(
            onTap: () => Navigator.pushNamed(context, RouteNames.promotion),
            child: Container(
              height: 48.px,
              margin: EdgeInsets.only(left: 6.px),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(6.px)
              ),
              child: Row(
                children: [
                  Container(
                    margin: EdgeInsets.only(left: 12.px, right: 12.px),
                    child: Icon(Icons.keyboard),
                  ),
                  Expanded(child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text("推广中心", style: TextStyle(color: Colors.black, fontSize: 13.px)),
                      Text("点击查看您的推广信息", style: TextStyle(color: Colors.grey, fontSize: 10.px)),
                    ],
                  ))
                ],
              ),
            ),
          )),
        ],
      ),
    );
  }
}