import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';
import '../util/api.dart';
import '../util/models.dart';
import '../showDialog.dart';

class OrderTakingPage extends StatefulWidget {

  OrderTakingPage({
    Key key
  }): super(key: key);

  _OrderTakingPageState createState() => _OrderTakingPageState();
}

class _OrderTakingPageState extends State < OrderTakingPage > with AutomaticKeepAliveClientMixin {

  ScrollController _scrollController = ScrollController(); //初始化滚动轴监控对象
  List listObj = [];


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getOrderList().then((resp) {
      setState(() {
        listObj = resp.orderList;
      });
    });
    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        print("滑到底部了");
        // getOrderList().then((resp) {
        //   setState(() {
        //     listObj.addAll(resp.orderList);
        //   });
        // });
      }
      //print(_scrollController.position.pixels);
    });

  }

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _scrollController.dispose();
    print('接单页listView滚动监听销毁了');
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      child: Scaffold(
        appBar: AppBar(
          title: Text('接单', style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(36)), ),
          centerTitle: true,
          backgroundColor: Color.fromRGBO(64, 98, 254, 1),
          actions: < Widget > [
            Container(
              child: PopupMenuButton < String > (
                icon: Icon(Icons.add_circle_outline),
                offset: Offset(0, 60),
                padding: EdgeInsets.zero,
                //child: IconButton(icon: Image.asset('lib/images/icon_shaixuan.png', scale: 1.8, ),onPressed: (){},),
                itemBuilder: (BuildContext context) => < PopupMenuEntry < String >> [
                  PopupMenuItem < String > (
                    child: Text("hahahahahh"),
                  ),
                  PopupMenuDivider(height: 1.0),
                  PopupMenuItem < String > (
                    child: Text("hahahahahh"),
                  ),
                  PopupMenuDivider(height: 1.0),
                  PopupMenuItem < String > (
                    child: Text("hahahahahh"),
                  ),
                  PopupMenuDivider(height: 1.0),
                ]
              )
            ),
          ],
        ),
        body: Container(
          padding: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20), ScreenUtil.getInstance().setWidth(20), ScreenUtil.getInstance().setWidth(20), 0),
          decoration: BoxDecoration(
            color: Color.fromRGBO(246, 246, 254, 1)
          ),
          child: RefreshIndicator( //下拉刷新组件
            onRefresh: _onRefresh, //回调方法
            child: ListView.builder(
              controller: _scrollController,
              itemCount: listObj.length + 1,
              itemBuilder: (BuildContext context, int index) { //itemBuilder实际上就是一个map的循环
                if (index < listObj.length) {
                  return OrderCardContainer(order: listObj[index], index: index, callback: (val) => deleteOrder(val));
                }
                return _getMoreWidget();
              },
            )
          ),
        )
      ),
    );
  }

  Widget _getMoreWidget() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: < Widget > [
            Text(
              '加载中...',
              style: TextStyle(fontSize: 16.0),
            ),
            Container(
              width: ScreenUtil.getInstance().setWidth(50),
              height: ScreenUtil.getInstance().setHeight(50),
              child: CircularProgressIndicator()
            )

          ],
        ),
      ),
    );
  }

  Future < Null > _onRefresh() async {
    await getOrderList().then((resp) {
      setState(() {
        listObj = resp.orderList;
      });
    });
  }

  void deleteOrder(val) {
    setState(() {
      listObj.removeAt(val);
      if (listObj.length < 4) {
        getOrderList().then((resp) {
          setState(() {
            listObj.addAll(resp.orderList);
          });
        });
      }
    });
  }

}


class OrderCardContainer extends StatefulWidget {
  final OrderList order;
  final int index;
  final callback;
  OrderCardContainer({
    Key key,
    @required this.order,
    @required this.index,
    @required this.callback
  }): super(key: key);

  _OrderCardContainerState createState() => _OrderCardContainerState();
}

class _OrderCardContainerState extends State < OrderCardContainer > with SingleTickerProviderStateMixin {
  Animation < double > animation;
  AnimationController controller;
  String str = "联系方式";
  bool animationStatus = true;
  @override
  initState() {
    super.initState();
    controller = new AnimationController(
      duration: const Duration(milliseconds: 200), vsync: this);
    animation = new Tween(begin: 0.0, end: 230.0).animate(controller);
    animation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        //动画执行结束时反向执行动画
        setState(() {
          animationStatus = false;
          str = "收起";
        });
      } else if (status == AnimationStatus.dismissed) {
        //动画恢复到初始状态时执行动画（正向）
        setState(() {
          animationStatus = true;
          str = "联系方式";
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      color: Colors.white,
      elevation: 3.0,
      child: Container(
        padding: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(30), ScreenUtil.getInstance().setWidth(30), ScreenUtil.getInstance().setWidth(30), 0),
        child: Column(
          children: < Widget > [
            orderNoRow(widget.order.orderNo, widget.order.createTime),
            orderAddress(widget.order.startAddress, widget.order.endAddress),
            orderItem('货物名称', widget.order.itemName, 15),
            orderItem('货物件数', '${widget.order.itemNo}件', 30),
            orderCutLine(),
            orderBtn(context, animationStatus, controller, str),
            AnimatedOpen(animation: animation, openInfo: widget.order, )
          ],
        ),
      )
    );
  }
  dispose() {
    //路由销毁时需要释放动画资源
    controller.dispose();
    super.dispose();
  }

  Widget orderBtn(BuildContext context, bool animationStatus, AnimationController controller, String str) {
    return Container(
      margin: EdgeInsets.only(bottom: ScreenUtil.getInstance().setHeight(20)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: < Widget > [
          GestureDetector(
            child: Container(
              width: ScreenUtil.getInstance().setWidth(100),
              height: ScreenUtil.getInstance().setHeight(48),
              color: Colors.white,
              child: Center(
                child: Text(str, style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(24), color: Color.fromRGBO(64, 98, 254, 1)), ),
              )
            ),
            onTap: () {
              if (animationStatus) {
                //动画恢复到初始状态时执行动画（正向）
                controller.forward();
              } else {
                //动画执行结束时反向执行动画
                controller.reverse();
              }
            },
          ),
          GestureDetector(
            child: Container(
              width: ScreenUtil.getInstance().setWidth(94),
              height: ScreenUtil.getInstance().setWidth(48),
              decoration: BoxDecoration(
                color: Color.fromRGBO(252, 97, 128, 1),
                borderRadius: BorderRadius.all(Radius.circular(4.0))
              ),
              child: Center(
                child: Text("接单", style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(24), color: Colors.white), ),
              ),
            ),
            onTap: () {
              showDialog < Null > (
                context: context, //BuildContext对象
                barrierDismissible: false,
                builder: (BuildContext context) {
                  return new LoadingDialog( //调用对话框
                    text: '是否确认接单', childCallback: (val) {
                      if (val) {
                        widget.callback(widget.index);
                      } else {
                        return;
                      }
                    },
                  );
                });
            },
          )
        ],
      )
    );
  }
}




class AnimatedOpen extends AnimatedWidget {
  final OrderList openInfo;
  AnimatedOpen({
    Key key,
    Animation < double > animation,
    @required this.openInfo
  }): super(key: key, listenable: animation);

  Widget build(BuildContext context) {
    final Animation < double > animation = listenable;
    return Container(
      height: ScreenUtil.getInstance().setHeight(animation.value),
      child: orderDetailInfo(openInfo),
    );
  }
}
Widget orderNoRow(int orderNo, String createTime) { //订单号及时间
  return Container(
    margin: EdgeInsets.only(bottom: ScreenUtil.getInstance().setHeight(30)),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: < Widget > [
        Text("订单号：${orderNo}", style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1), fontSize: ScreenUtil.getInstance().setSp(24)), ),
        Text(createTime, style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1), fontSize: ScreenUtil.getInstance().setSp(24)), ),
      ],
    ),
  );
}

Widget orderAddress(String startAddress, String endAddress) { //运送路线
  return Container(
    margin: EdgeInsets.only(bottom: ScreenUtil.getInstance().setHeight(20)),
    child: Row(children: < Widget > [
      Text('${startAddress} ---> ${endAddress}', style: TextStyle(color: Colors.black, fontSize: ScreenUtil.getInstance().setSp(30)), ),
    ], )
  );
}

Widget orderCutLine() { //分割线
  return Container(
    margin: EdgeInsets.only(bottom: ScreenUtil.getInstance().setHeight(20)),
    height: ScreenUtil.getInstance().setHeight(1),
    color: Color.fromRGBO(223, 223, 223, 1),
  );
}


Widget orderDetailInfo(OrderList obj) { //卡片展开信息
  return Container(
    child: Wrap(
      children: < Widget > [
        orderCutLine(),
        orderPhone('发件电话', obj.sendPhone, 15),
        orderItem('发件地址', obj.sendAddress, 30),
        orderPhone('收件电话', obj.getPhone, 15),
        orderItem('收件地址', obj.getAddress, 30),
      ],
    )
  );
}

Widget orderItem(String key, String value, int marginBottom) { //货物名称，件数
  return Container(
    margin: EdgeInsets.only(bottom: ScreenUtil.getInstance().setHeight(marginBottom)),
    child: Row(children: < Widget > [
      Text('${key}：${value}', style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1), fontSize: ScreenUtil.getInstance().setSp(24)), ),
    ], )
  );
}

Widget orderPhone(String key, String value, int marginBottom) {
  return InkWell(
    child: Container(
      margin: EdgeInsets.only(bottom: ScreenUtil.getInstance().setHeight(marginBottom)),
      child: Row(children: < Widget > [
        Text('${key}：', style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1), fontSize: ScreenUtil.getInstance().setSp(24)), ),
        Text('${value}', style: TextStyle(color: Color.fromRGBO(64, 98, 254, 1), fontSize: ScreenUtil.getInstance().setSp(24)), ),
      ], )
    ),
    onLongPress: () async {
      String  phone = 'tel:${value}';
      print(phone);
      if(await canLaunch(phone)){
        await (launch(phone));
      }else{
        throw 'Could not launch $value';
      }
    },
  );
}

