import 'package:flutter/material.dart';
import 'package:liftmanager/res/gaps.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/internal/search/search_router.dart';
import 'package:liftmanager/widgets/app_search_bar.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'package:liftmanager/widgets/my_card.dart';
import 'package:liftmanager/internal/wode/wode_router.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liftmanager/mvp/base_page_state.dart';
import 'package:liftmanager/internal/wode/presenter/order_list_presenter.dart';
import 'package:liftmanager/internal/search/presenter/base_list_provider.dart';
import 'package:liftmanager/internal/bbs/model/liftcase_model.dart';
import 'package:liftmanager/widgets/state_layout.dart';
import 'package:provider/provider.dart';
import 'package:liftmanager/utils/time_format.dart';
import 'package:liftmanager/utils/log_util.dart';
import 'package:liftmanager/widgets/my_refresh_list.dart';
import 'dart:convert';
import 'package:liftmanager/utils/fast_notification.dart';

class PiaoWait extends StatefulWidget {
  // QuestionList(this.index);

  // final String index;
  
  bool checkAll = false;
  @override
  PiaoWaitState createState() => PiaoWaitState();
}

class PiaoWaitState extends State<PiaoWait> {
   int _page = 1;
    List<int>idList = [];
    List<int>commentListWidget=[];
    List<dynamic>listCase;
    bool _hasData = false;
   @override
  void initState() {
    super.initState();
    getLiftCasesListNoPage();
    print(66666);

    FastNotification.addListener("initThisPiao",(initThisStringPiao){     
      if(mounted){
        getLiftCasesListNoPage();
      }
    });
    
  }

  Future getLiftCasesListNoPage() async {
    await NewApiService().getLiftCasesListNoPage(
        onSuccess: (res) {
      if (res != null) {
        _hasData = true;
        listCase = res;
        res.forEach((item){
          // print(JsonEncoder().convert(item));
          // print(item.id);
          commentListWidget.add(item.id);
        });
        
        // LogUtil.d(JsonEncoder().convert(listCase));
        print(123);
        setState(() {});
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }
  


  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    double width = MediaQuery.of(context).size.width;
    String checkFalse = "tab_first/check_false";
    String checkTrue = "tab_first/check_true";

    return Scaffold(
          // resizeToAvoidBottomPadding: true,
          appBar: MyAppBar(
          centerTitle: "待开发票",
          // actions:<Widget>[
          //   FlatButton(
          //     child: Text("发票抬头"),
          //     textColor: Colours.dark_text,
          //     highlightColor: Colors.transparent,
          //     onPressed: () {
          //       NavigatorUtils.push(context, WodeRouter.piaotou);
                
          //     },
          //   )
          // ],
        ),
          body: _hasData?Stack(
            children: <Widget>[
              listCase.length>0?Container(
            // color: Color(0xFFF1F4FC),
            child: ListView(
              children: <Widget>[
                
                OrderListItemWidget(idList:idList,lists:listCase,
                                changeState:(id){
                    setState(() {
                      print(557);
                      if(idList.contains(id)){
                        idList.remove(id);
                      }else {
                        idList.add(id);
                      }
                      print(idList);
                      print(commentListWidget);
                      if(commentListWidget.length==idList.length){
                        widget.checkAll = true;
                        print(widget.checkAll);
                      print(555);
                      }else {
                        widget.checkAll = false;
                        print(widget.checkAll);
                      print(556);
                      }
                      print(idList);
                      print(557);
                    });
                  }
                              )
              ],
            ),
          ):Center(child:Text("暂无数据")),
          listCase.length>0?Positioned(
              bottom:0,
              left:0,
              child:Container(
                width: width,
                child: Row(
                  children:<Widget>[
                    Container(
                      height:ScreenUtil().setWidth(70),
                      width:width/2,
                      color:Colors.white,
                      child: GestureDetector(
                        onTap: (){
                          print(commentListWidget);
                          setState(() {
                            widget.checkAll = !widget.checkAll;
                            if(widget.checkAll == false){
                              idList = [];
                            }else {
                              idList = [];
                              commentListWidget.forEach((item){
                                idList.add(item);
                              });
                            }
                          });
                          print(idList);
                          print(89888);
                          print(commentListWidget);
                        },
                        child:Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          LoadAssetImage(
                                // image: AssetImage(i['img']),
                                widget.checkAll == true?checkTrue:checkFalse,
                                width: ScreenUtil().setWidth(20),
                                height:ScreenUtil().setWidth(20),
                                // alignment: Alignment.centerLeft,
                        ),
                        SizedBox(
                          width:5
                        ),
                        Text("全选",style: TextStyle(fontSize:ScreenUtil().setSp(16)),)
                        ],
                      )
                      )
                    ),
                    Container(
                      height:70,
                      width:width/2,
                      color: Color(0xff0388FD),
                      child: FlatButton(
                        // padding: EdgeInsets.all(15.0),
                        child: Text("下一步",style: TextStyle(fontSize:ScreenUtil().setSp(16)),),
                        textColor: Colors.white,
                        onPressed: () {
                          
                          if(idList.length>0){
                            String str = "";
                            idList.forEach((item){
                              str += (item.toString() + ",");
                            });
                            print(str.substring(0, str.length));
                            print(456);
                            double price = 0.0;
                            listCase.forEach((subitem){
                              idList.forEach((i){
                                if(subitem.id == i){
                                  price += subitem.payCost;
                                }
                              });
                            });
                            
                            NavigatorUtils.push(context, "${WodeRouter.kaipiao}?ids=${str.substring(0, str.length)}&price=${price.toString()}");
                            idList = [];
                            print(idList);
                          }else {
                            toasts("请选择一项");
                          }
                          
                           
                        },
                      ),
                    ),
                  ]
                )
              )
            ):Container(child:null)
            ],
          ):Center(
              child: Text("正在加载..."),
            )
        );
    
    
  }




}


class OrderListItemWidget extends StatelessWidget {
  OrderListItemWidget({Key key, this.data,this.changeState,this.idList,this.lists}) : super(key: key);
  LiftCasesDetailModel data;
  Function changeState;
  List<int>idList;
  List<dynamic>lists;
  String checkFalse = "tab_first/check_false";
  String checkTrue = "tab_first/check_true";


  List<Widget> getListWdiget(context) => lists.asMap().keys.map((i){
    double width = MediaQuery.of(context).size.width;
    return Container(
      padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
      width: width,
      decoration: BoxDecoration(
        border: Border(
                  bottom: BorderSide(width: 0.5, color: Colours.line),
                ),
      ),
      // height: 100,
      child: Row(
        children: <Widget>[
          GestureDetector(
              child: Container(
                padding: EdgeInsets.only(top:ScreenUtil().setWidth(10),left:ScreenUtil().setWidth(5),right:ScreenUtil().setWidth(5),bottom:ScreenUtil().setWidth(10)),
                child: LoadAssetImage(
                        // image: AssetImage(i['img']),
                        idList.contains(lists[i].id)?checkTrue:checkFalse,
                        width: ScreenUtil().setWidth(20),
                        height:ScreenUtil().setWidth(20),
                        // alignment: Alignment.centerLeft,
                ),
                
              ),
              onTap: (){
                
                changeState(lists[i].id);
              },
            ),
            Expanded(
              child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          NavigatorUtils.push(
              context, "${WodeRouter.orderDetail}?id=${lists[i].id}");
        },
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          // mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(
                  left: ScreenUtil().setWidth(10),
                  right: ScreenUtil().setWidth(10),
                  top: ScreenUtil().setWidth(5)),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(ScreenUtil().setWidth(22)),
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(ScreenUtil().setWidth(22)),
                child: LoadNetworkImage(
                  lists[i].avatarUrl,
                  width: ScreenUtil().setWidth(43),
                  height: ScreenUtil().setWidth(43),
                  // alignment: Alignment.centerLeft,
                ),
              ),
              
            ),
            Expanded(
              // flex: 1,
              // fit: FlexFit.loose,
              child: Container(
                padding: EdgeInsets.only(right: ScreenUtil().setWidth(15)),
                child: Column(
                  children: <Widget>[
                    Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Text(
                                lists[i].name,
                                style: TextStyle(
                                    color: Color(0xff333333),
                                    fontSize: ScreenUtil().setSp(17)),
                                textAlign: TextAlign.start,
                              ),
                              Container(
                                padding: EdgeInsets.only(left: 5),
                                child: Text(
                                  lists[i].dataTable == 1 ? '问诊服务' : '出诊服务',
                                  style: TextStyle(
                                    color: Color(0xff0288FF),
                                    fontSize: ScreenUtil().setSp(14),
                                  ),
                                  textAlign: TextAlign.start,
                                ),
                              )
                            ],
                          ),
                          // Container(
                          //   child: Text(
                          //     OrderConstant.getStatusName(data.statuz, data.dataTable, arrivedFlag: data.arrivedFlag, userType: 'USER'),
                          //     style: TextStyle(
                          //       color: [].indexOf(data.statuz) == -1
                          //           ? Color(0xff0288FF)
                          //           : Color(0xffF84203),
                          //       fontSize: ScreenUtil().setSp(14),
                          //     ),
                          //     textAlign: TextAlign.end,
                          //   ),
                          // )
                        ],
                      ),
                    ),
                    Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Text(
                                lists[i].createTime != null
                                    ? DateUtils.instance.getFormartData(
                                        timeSamp: lists[i].createTime,
                                        format: "yyyy-MM-dd")
                                    : '',
                                style: TextStyle(
                                  color: Color(0xff999999),
                                  fontSize: ScreenUtil().setSp(13),
                                ),
                                textAlign: TextAlign.start,
                              ),
                              Container(
                                padding: EdgeInsets.only(left: 5),
                                child: Text(
                                  lists[i].brandName ?? '',
                                  style: TextStyle(
                                    color: Color(0xff999999),
                                    fontSize: ScreenUtil().setSp(13),
                                  ),
                                  textAlign: TextAlign.start,
                                ),
                              )
                            ],
                          ),
                        ],
                      ),
                    ),
                    Container(
                      // margin: EdgeInsets.only(top: 6),
                      child: Row(
                        children: <Widget>[
                          Container(
                            width: width*0.6,
                            padding: EdgeInsets.only(right: 5),
                            child: Text(
                              lists[i].expression ?? '',
                              style: TextStyle(
                                color: Color(0xff666666),
                                fontSize: ScreenUtil().setSp(15),
                              ),
                              textAlign: TextAlign.start,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 6),
                      child: Row(
                        children: <Widget>[
                          Container(
                            padding: EdgeInsets.only(right: 5),
                            child: Text(
                              lists[i].payCost != null
                                  ? "￥${lists[i].payCost.toString()}"
                                  : '',
                              style: TextStyle(
                                color: Color(0xffFD0808),
                                fontSize: ScreenUtil().setSp(15),
                              ),
                              textAlign: TextAlign.start,
                            ),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      ),
            )
        ],
      ),
      
    );
  }).toList();

  @override
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: getListWdiget(context),
      ),
    );
  }

  

 
}
