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';
import '../util/session.dart';
import '../util/util.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 < OrderList > orderList = []; //订单列表
  bool hasNextPage = true;
  List lineList = []; //线路列表
  String stationId;
  List < bool > checkStatusList = [];
  bool showLineStatus = true;
  String lineIdStr = '';
  String oldLineIdStr = '';
  int page = 1;
  @override
  void initState() {
    super.initState();
    getKey('stationId').then((value) {
      setState(() {
        stationId = value;
      });
      getLine(value).then((childValue) {
        getOrderList(value, lineIdStr, page).then((resp) {
          if (isNotError(context, resp)) {
            setState(() {
              orderList = OrderListObj.fromJson(resp.data).data.items;
              hasNextPage = OrderListObj.fromJson(resp.data).data.hasNextPage;
            });
          }
        });
      });
    });
    _scrollController.addListener(() {
      if (!showLineStatus) {
        setState(() {
          showLineStatus = true;
        });
        switchLine(context);
      }
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        print('滑动到底部了');
        if (hasNextPage) {
          page = ++page;
          getOrderList(stationId, lineIdStr, page).then((resp) {
            if (isNotError(context, resp)) {
              OrderListObj tempObj =OrderListObj.fromJson(resp.data);
              setState(() {
                orderList.addAll(tempObj.data.items);
                hasNextPage = tempObj.data.hasNextPage;
              });
            }
          });
        }
      }
    });
  }


  Future getLine(String value) async {
    await getLineFromStation(value).then((resp) {
      if (isNotError(context, resp)) {
        setState(() {
          checkStatusList = [];
          lineList = StationLine.fromJson(resp.data).data;
          for (int i = 0; i < lineList.length; i++) {
            checkStatusList.add(true);
            if (i < lineList.length - 1) {
              lineIdStr += lineList[i].id.toString() + ',';
            } else {
              lineIdStr += lineList[i].id.toString();
            }
          }
          stationId = value;
        });
        return lineIdStr;
      }
    });
  }

  @override
  bool get wantKeepAlive => true;


  @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 > [
            IconButton(icon: Icon(Icons.add_circle_outline),
              onPressed: () {
                setState(() {
                  showLineStatus = !showLineStatus;
                });
                if (!showLineStatus) {
                  getKey('stationId').then((value) {
                    if (stationId != value) {
                      getLine(value);
                    }
                  });
                } else {
                  switchLine(context);
                }
              }, )
          ]
        ),
        body: Stack(
          children: < Widget > [
            RefreshIndicator(
              onRefresh: _onRefresh, //回调方法
              child: InkWell(
                child: 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: ListView.builder(
                    controller: _scrollController,
                    physics: AlwaysScrollableScrollPhysics(),
                    itemCount: orderList.length + 1,
                    itemBuilder: (BuildContext context, int index) { //itemBuilder实际上就是一个map的循环
                      if (index < orderList.length) {
                        return OrderCardContainer(order: orderList[index], index: index, callback: (val) => deleteOrder(val));
                      }
                      if (hasNextPage) {
                        return _getMoreWidget();
                      } else {
                        return _noMoreWidegt();
                      }
                    },
                  )
                ),
                onTap: () {
                  setState(() {
                    showLineStatus = true;
                  });
                  switchLine(context);
                },
              ),
            ),
            Positioned(
              top: 0,
              right: 0,
              child:
              Offstage(
                offstage: showLineStatus,
                child: Container(
                  width: ScreenUtil.getInstance().setWidth(350),
                  height: ScreenUtil.getInstance().setHeight(500),
                  margin: EdgeInsets.fromLTRB(0, 1, 1, 0),
                  padding: EdgeInsets.fromLTRB(1, 0, 1, 0),
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(0, 0, 0, 0.7),
                    borderRadius: BorderRadius.all(Radius.circular(4.0))
                  ),
                  child: ListView.builder(
                    itemCount: lineList.length,
                    itemBuilder: (BuildContext context, int index) { //itemBuilder实际上就是一个map的循环
                      if (index < lineList.length) {
                        return _lineWidget(lineList[index], index, checkStatusList[index]);
                      }
                    },
                  ),
                ),
              )
            )
          ],
        )
      ),
    );
  }

  Widget _lineWidget(LineObj lineObj, int index, bool checked) {
    return InkWell(
      child: Container(
        height: ScreenUtil.getInstance().setHeight(80),
        decoration: BoxDecoration(
          border: BorderDirectional(bottom: BorderSide(color: Colors.white))
        ),
        child: Row(
          children: < Widget > [
            Padding(
              padding: EdgeInsets.only(right: 10),
              child: checked ? Icon(Icons.check, color: Colors.white, ) : Icon(Icons.check, color: Color.fromRGBO(0, 0, 0, 0.0)),
            ),
            Expanded(
              flex: 1,
              child: Center(
                child: Text(lineObj.name, style: TextStyle(color: Colors.white))
              )
            )
          ],
        ),
      ),
      onTap: () {
        setState(() {
          checkStatusList[index] = !checked;
        });
      },
    );
  }

  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()
            )

          ],
        ),
      ),
    );
  }

  Widget _noMoreWidegt() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Text(
          '没有更多数据了...',
          style: TextStyle(fontSize: 16.0),
        ),
      ),
    );
  }

  Future < Null > _onRefresh() async {
    await getKey('stationId').then((value) {
      page = 1;
      getOrderList(value, lineIdStr, page).then((resp) {
        if(isNotError(context, resp)){
          setState(() {
            orderList = OrderListObj.fromJson(resp.data).data.items;
          });
        }
      });
    });
  }

  void deleteOrder(val) { //确认接单后的操作
    setState(() {
      orderList.removeAt(val);
      if (orderList.length < 4) {
        if (hasNextPage) {
          setState(() {
            page = ++page;
          });
          getOrderList(stationId, lineIdStr, page).then((resp) {
            if (resp.success && resp.code == 1) {
              setState(() {
                orderList.addAll(resp.data.items);
                hasNextPage = resp.data.hasNextPage;
              });
            }
          });
        }
      }
    });
  }

  void switchLine(BuildContext context) { //切换线路
    lineIdStr = '';
    for (int i = 0; i < checkStatusList.length; i++) {
      if (checkStatusList[i]) {
        lineIdStr += lineList[i].id.toString() + ',';
      }
    }
    lineIdStr = lineIdStr.substring(0, lineIdStr.length - 1);
    if(oldLineIdStr==lineIdStr) return;
    setState(() {
      orderList = [];
      hasNextPage =true;
    });
    getOrderList(stationId, lineIdStr, page).then((resp) {
      if(isNotError(context, resp)){
          OrderListObj tempObj =OrderListObj.fromJson(resp.data);
          setState(() {
            orderList = tempObj.data.items;
            hasNextPage = tempObj.data.hasNextPage;
          });
          oldLineIdStr =lineIdStr;
      }
    });
  }
}


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.receiptCompanyName, widget.order.sendCompanyName),
            orderItem('货物名称', widget.order.goods, 15),
            orderItem('货物件数', '${widget.order.goodsQuantity}件', 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: () {
              getKey('stationId').then((value) {
                print(value);
              });
              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(String orderNo, int 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.sendCompanyPhone, 15),
        orderItem('发件地址', obj.sendCompanyAddress, 30),
        orderPhone('收件电话', obj.receiptCompanyPhone, 15),
        orderItem('收件地址', obj.receiptCompanyAddress, 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';
      }
    },
  );
}