import 'dart:async';

import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:wakelock/wakelock.dart';

import '../../base/YSNetWorking.dart';
import '../../base/YSTools.dart';

class YSCouponCardView extends StatefulWidget {
  final Map item;
  final List array;
  final bool isShow;
  const YSCouponCardView({Key key, @required this.item, this.isShow = false, @required this.array}) : super(key: key);

  @override
  _YSCouponCardViewState createState() => _YSCouponCardViewState();
}

class _YSCouponCardViewState extends State<YSCouponCardView> {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 267,
      width: ysWidth(context),
      decoration: BoxDecoration(
        color: Color(widget.item['color']),
        borderRadius: BorderRadius.all(Radius.circular(9)),
        boxShadow: [
          BoxShadow(color: Colors.black38,blurRadius: 10)
        ]
      ),
      margin: EdgeInsets.only(top: widget.item['index']*44*1.0),
      child: LayoutBuilder(
        builder: (context, constraints) {
          return widget.isShow?Stack(
            children: [
              Container(
                height: 50,
                padding: EdgeInsets.only(left: 40,right: 40),
                alignment: Alignment.centerLeft,
                child: Row(
                  children: [
                    Container(
                      width: constraints.maxWidth-130,
                      child: Text(widget.item['name'],style: TextStyle(fontSize: 18,color: Colors.white),maxLines: 1,),
                    ),
                    Container(
                      width: 50,
                      height: 18,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(50))
                      ),
                      child: Text('共${widget.item['count']}张',style: TextStyle(fontSize: 10,color: Color(widget.item['color'])),),
                      alignment: Alignment.center,
                    )
                  ],
                ),
              ),
              Container(
                decoration: BoxDecoration(
                  image: DecorationImage(image: AssetImage('lib/images/编组 12_fy.png'))
                ),
                margin: EdgeInsets.only(top: 50),
                width: ysWidth(context)-20,
                height: 158,
                padding: EdgeInsets.only(left: 70,right: 30,top: 30,bottom: 38),
                child: Container(
                  height: 90,
                  child: Column(
                    children: [
                      Container(
                        alignment: Alignment.centerLeft,
                        height: 30,
                        child: Text('编号：${widget.item['no']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        height: 30,
                        child: Text('时间：${widget.item['month']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        height: 30,
                        child: Text('失效日期：${widget.item['date']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),),
                      )
                    ],
                  ),
                ),
              ),
              Positioned(
                left: 0,
                bottom: 0,
                width: ysWidth(context),
                height: 108,
                child: Stack(
                  children: [
                    Image.asset('lib/images/矩形备份 17_fy.png',color: Color(widget.item['color']),),
                    Padding(
                      padding: EdgeInsets.only(left: ysWidth(context)/2-67,top: 55),
                      child: Image.asset('lib/images/编组 9_fy.png',height: 40,width: 134,),
                    ),
                    GestureDetector(
                      onTap: (){
                        ysShowBottomAlertView(context, YSCodeAlertView(array: widget.array,item: widget.item,callback: (){
                          CustomerNotification().dispatch(context);
                        },),isBarr: true);
                      },
                      behavior: HitTestBehavior.opaque,
                      child: Container(
                        height: 40,
                        width: 134,
                        margin: EdgeInsets.only(left: ysWidth(context)/2-67,top: 55),
                        alignment: Alignment.center,
                        child: Text('核销码',style: TextStyle(fontSize: 16,color: Colors.white),),
                      ),
                    )
                  ],
                )
              )
            ],
          ):Column(
            children: [
              Container(
                height: 50,
                padding: EdgeInsets.only(left: 40,right: 40),
                alignment: Alignment.centerLeft,
                child: Row(
                  children: [
                    Container(
                      width: constraints.maxWidth-130,
                      child: Text(widget.item['name'],style: TextStyle(fontSize: 18,color: Colors.white),maxLines: 1,),
                    ),
                    Container(
                      width: 50,
                      height: 20,
                      child: Text('共${widget.item['count']}张',style: TextStyle(fontSize: 14,color: Colors.white),),
                      alignment: Alignment.center,
                    )
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 167),
                height: 50,
                padding: EdgeInsets.only(left: 40,right: 40),
                alignment: Alignment.centerLeft,
                child: Row(
                  children: [
                    Container(
                      width: constraints.maxWidth-130,
                      child: Text(widget.item['name'],style: TextStyle(fontSize: 18,color: Colors.white),maxLines: 1,),
                    ),
                    Container(
                      width: 50,
                      height: 20,
                      child: Text('共${widget.item['count']}张',style: TextStyle(fontSize: 14,color: Colors.white),),
                      alignment: Alignment.center,
                    ),
                  ],
                ),
              )
            ],
          );
        },
      ),
    );
  }
}

class YSWriteOffView extends StatefulWidget {
  final VoidCallback voidCallback;
  const YSWriteOffView({Key key, @required this.voidCallback}) : super(key: key);

  @override
  _YSWriteOffViewState createState() => _YSWriteOffViewState();
}

class _YSWriteOffViewState extends State<YSWriteOffView> {
  @override
  void initState() {
    Future.delayed(Duration(seconds: 1)).then((value) {
      Navigator.pop(context);
      widget.voidCallback();
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        height: 150,
        width: 150,
        decoration: BoxDecoration(
          color: Colors.pinkAccent,
          borderRadius: BorderRadius.all(Radius.circular(10))
        ),
        alignment: Alignment.center,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.check_circle,size: 50,color: Colors.white,),
            Padding(
              padding: EdgeInsets.only(top: 10),
              child: Text('已核销',style: TextStyle(fontSize: 15,color: Colors.white,decoration: TextDecoration.none),)
            )
          ],
        ),
      )
    );
  }
}


class YSCodeAlertView extends StatefulWidget {
  final List array;
  final Map item;
  final VoidCallback callback;
  const YSCodeAlertView({Key key, this.array, this.item, @required this.callback}) : super(key: key);

  @override
  _YSCodeAlertViewState createState() => _YSCodeAlertViewState();
}

class _YSCodeAlertViewState extends State<YSCodeAlertView> with SingleTickerProviderStateMixin{
  TabController _tabController;
  Timer _timer;
  @override
  void initState() {
    _tabController = TabController(
      vsync: this,
      length: widget.array.length,
      initialIndex: widget.array.indexOf(widget.item)
    );
    getTimer();
    super.initState();
  }
  @override
  void dispose() {
    if(_timer!=null){
      _timer.cancel();
    }
    super.dispose();
  }
  getTimer() {
    _timer =Timer.periodic(Duration(seconds: 3), (timer) async{
      Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'transfer/coupon/checkTicketInformation', {'idcard':User().idCard,'couponId':widget.item['couponId']});
      if(dict!=null){
        bool isCheck = dict['data']??false;
        if(isCheck){
          ysShowCenterAlertView(context, YSWriteOffView(voidCallback: (){
            widget.callback();
            Navigator.pop(context);
          },),isTrans: true);
          // ysFlutterToast(context, '已核销');

        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.only(topRight: Radius.circular(20),topLeft: Radius.circular(20)),
      child: Container(
        height: 570,
        decoration: BoxDecoration(
          color: Color(0xFFF5F5F5),
        ),
        child: DefaultTabController(
          length: widget.array.length,
          child: false?Column(
            children: [
              Container(
                color: Color(0xFFFF6D96),
                height: 50,
                width: MediaQuery.of(context).size.width,
                child: Row(
                  children: [
                    Container(
                      width: ysWidth(context)-40,
                      padding: EdgeInsets.only(left: 20,right: 20),
                      child: TabBar(
                        controller: _tabController,
                        indicatorColor: Color(0xFFFF6D96),
                        isScrollable: true,
                        labelColor: Colors.white,
                        indicatorWeight: 3,
                        indicatorSize: TabBarIndicatorSize.label,
                        labelStyle: TextStyle(fontSize: 14),
                        unselectedLabelColor: Colors.white60,
                        tabs: widget.array.map((f) {//text: '· ${f['title']}'
                          return Tab(
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Text(f['couponName'])
                              ],
                            ),
                          );
                        }).toList(),
                      ),
                    ),
                    GestureDetector(
                      onTap: (){Navigator.pop(context);},
                      child: Image.asset('lib/images/clear_fy.png',height: 20,width: 20,),
                    )
                  ],
                ),
              ),
              SizedBox(
                height: 520,
                width: MediaQuery.of(context).size.width,
                child: TabBarView(
                  controller: _tabController,
                  children: widget.array.map((f) {
                    return YSCodeAlertInfoView(item: f,);
                  }).toList(),
                ),
              )
            ],
          ):Column(
            children: [
              Container(
                color: Color(0xFFFF6D96),
                height: 50,
                width: MediaQuery.of(context).size.width,
                child: Row(
                  children: [
                    Container(
                      width: ysWidth(context)-40,
                      padding: EdgeInsets.only(left: 20,right: 20),
                      child: Text(widget.item['couponName'],style: TextStyle(fontSize: 14,color: Colors.white),),
                      alignment: Alignment.center,
                    ),
                    GestureDetector(
                      onTap: (){Navigator.pop(context);},
                      child: Image.asset('lib/images/clear_fy.png',height: 20,width: 20,),
                    )
                  ],
                ),
              ),
              SizedBox(
                height: 520,
                width: MediaQuery.of(context).size.width,
                child: YSCodeAlertInfoView(item: widget.item,),
              )
            ],
          ),
        ),
      ),
    );
  }
}

class YSCodeAlertInfoView extends StatefulWidget {
  final Map item;
  const YSCodeAlertInfoView({Key key, this.item}) : super(key: key);

  @override
  _YSCodeAlertInfoViewState createState() => _YSCodeAlertInfoViewState();
}

class _YSCodeAlertInfoViewState extends State<YSCodeAlertInfoView> {
  String _codeStr = '';
  @override
  void initState() {
    Wakelock.enable();
    YSScreenChange().change(255);
    Future.delayed(Duration(seconds: 0)).then((value) {
      _getCodeData();
    });
    super.initState();
  }

  _getCodeData() async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'transfer/coupon/getTicketCode', {'idcard':User().idCard,'couponId':widget.item['couponId']});
    if(dict!=null){
      _codeStr = dict['message'];
      setState(() {});
    }
  }
  @override
  void dispose() {
    YSScreenChange().change(100);
    Wakelock.disable();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        GestureDetector(
          onTap: (){
            _getCodeData();
          },
          behavior: HitTestBehavior.opaque,
          child: Container(
            height: 200,
            width: 200,
            color: Colors.white,
            margin: EdgeInsets.only(top: 20),
            child: _codeStr.isNotEmpty?QrImage(data: _codeStr):SizedBox(),
          ),
        ),
        Container(
          height: 40,
          child: Text('$_codeStr',style: TextStyle(fontSize: 16,color: Colors.grey),),
          alignment: Alignment.center,
        ),
        ClipRRect(
          child: Container(
            height: 260,
            color: Colors.white,
            width: ysWidth(context),
            child: Stack(
              children: [
                // Transform.rotate(
                //   angle: 2,
                //   child: Container(
                //     color: Colors.red,
                //   ),
                // ),
                Column(
                  children: List.generate(
                    4,(index) => Expanded(
                      child: Row(
                        children: List.generate(
                          4,(index) => Expanded(
                            child: Center(
                              child: Transform.rotate(
                                angle: -0.8,
                                child: Text(
                                  '${widget.item['hospitalName']}',
                                  style: TextStyle(
                                    color: Color(0xFFC8C9CC).withOpacity(0.5),
                                    fontSize: 14,
                                    decoration: TextDecoration.none,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.only(left: 20,right: 20),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                        height: 35,
                        child: Text(widget.item['couponName'],style: TextStyle(fontSize: 18,color: Color(0xFF444444)),maxLines: 1,),
                        alignment: Alignment.center,
                      ),
                      Container(
                        height: 30,
                        child: Text('编号：${widget.item['couponCode']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),maxLines: 1,),
                        alignment: Alignment.center,
                      ),
                      Container(
                        height: 30,
                        child: Text('母亲姓名：${widget.item['pregnantWomanName']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),maxLines: 1,),
                        alignment: Alignment.center,
                      ),
                      Container(
                        height: 30,
                        child: Text('时间：${widget.item['applicableRange']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),maxLines: 1,),
                        alignment: Alignment.center,
                      ),
                      Container(
                        height: 30,
                        child: Text('发券机构：${widget.item['hospitalName']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),maxLines: 1,),
                        alignment: Alignment.center,
                      ),
                      Container(
                        height: 30,
                        child: Text('失效日期：${widget.item['applicableEntTime']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),maxLines: 1,),
                        alignment: Alignment.center,
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
        )
      ],
    );
  }
}



//        DottedBorder(
//           color: Color(0xFFFF6D96),
//           borderType: BorderType.RRect,
//           radius: Radius.circular(9),
//           strokeWidth: 1,
//           child: Container(
//             height: 185,
//             width: ysWidth(context)-40,
//             child: Column(
//               children: [
//                 Container(
//                   height: 35,
//                   child: Text(widget.item['couponName'],style: TextStyle(fontSize: 18,color: Color(0xFF444444)),maxLines: 1,),
//                   alignment: Alignment.centerLeft,
//                 ),
//                 Container(
//                   height: 30,
//                   child: Text('编号：${widget.item['couponCode']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),maxLines: 1,),
//                   alignment: Alignment.centerLeft,
//                 ),
//                 Container(
//                   height: 30,
//                   child: Text('母亲姓名：${widget.item['pregnantWomanName']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),maxLines: 1,),
//                   alignment: Alignment.centerLeft,
//                 ),
//                 Container(
//                   height: 30,
//                   child: Text('时间：${widget.item['applicableRange']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),maxLines: 1,),
//                   alignment: Alignment.centerLeft,
//                 ),
//                 Container(
//                   height: 30,
//                   child: Text('发券机构：${widget.item['hospitalName']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),maxLines: 1,),
//                   alignment: Alignment.centerLeft,
//                 ),
//                 Container(
//                   height: 30,
//                   child: Text('失效日期：${widget.item['applicableEntTime']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),maxLines: 1,),
//                   alignment: Alignment.centerLeft,
//                 ),
//               ],
//             ),
//             padding: EdgeInsets.only(left: 50,right: 50),
//           ),
//         )


class YSCouponCardNewView extends StatefulWidget {
  final Map item;
  final List array;
  const YSCouponCardNewView({Key key, @required this.item, this.array}) : super(key: key);

  @override
  _YSCouponCardNewViewState createState() => _YSCouponCardNewViewState();
}

class _YSCouponCardNewViewState extends State<YSCouponCardNewView> {
  int _type = 1;
  @override
  void initState() {
    _type = int.parse(widget.item['type']??'1');
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        // CustomerValueNotification({'item':widget.item,'array':widget.array}).dispatch(context);
        ysShowBottomAlertView(context, YSCodeAlertView(array: widget.array,item: widget.item,callback: (){
          CustomerNotification().dispatch(context);
        }),isBarr: true);
      },
      behavior: HitTestBehavior.opaque,
      child: Container(
        color: Colors.white,
        height: 150,
        child: LayoutBuilder(
          builder: (context,conSize){
            int typeId = widget.item['typeId']??1;
            return Stack(
              children: [
                Padding(
                  padding: EdgeInsets.only(left: 80,top: 2),
                  child: DottedBorder(
                    color: _type==1?Color(0xFFFF6D96):Color(0xFF6EA0EF),
                    borderType: BorderType.RRect,
                    radius: Radius.circular(10),
                    strokeWidth: 1,
                    child: Container(
                      width: conSize.maxWidth-80,
                      height: 142,
                      padding: EdgeInsets.only(left: 14),
                      child: Container(
                        child: Column(
                          children: [
                            Container(
                              height: 41.5,
                              padding: EdgeInsets.only(left: 5,right: 5),
                              alignment: Alignment.center,
                              child: Text(widget.item['couponName'],style: TextStyle(fontSize: 18,color: _type==1?Color(0xFFFF6D96):Color(0xFF6EA0EF)),maxLines: 1,),
                            ),
                            Padding(
                              child: DashLine(color: Color(0xFF979797),height: 0.5,),
                              padding: EdgeInsets.only(left: 13,right: 13)
                            ),
                            Container(
                              height: 100,
                              alignment: Alignment.center,
                              padding: EdgeInsets.only(left: 50,right: 20),
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Container(
                                    height: 20,
                                    alignment: Alignment.centerLeft,
                                    child: Text('编号：${widget.item['couponCode']}',style: TextStyle(fontSize: 12,color: Color(0xFF444444)),maxLines: 1,),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: 5,bottom: 5),
                                    height: 20,
                                    alignment: Alignment.centerLeft,
                                    child: Text('时间：${widget.item['applicableRange']}',style: TextStyle(fontSize: 12,color: Color(0xFF444444)),maxLines: 1),
                                  ),
                                  Container(
                                    height: 20,
                                    alignment: Alignment.centerLeft,
                                    child: Text('失效日期：${widget.item['applicableEntTime']}',style: TextStyle(fontSize: 12,color: Color(0xFF444444)),maxLines: 1),
                                  )
                                ],
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
                Container(
                  width: 94,
                  decoration: BoxDecoration(
                    image: DecorationImage(image: AssetImage('lib/images/${
                        typeId==1?'编组 8备份m':typeId==2?'编组 8备份m(1)':typeId==3?'编组 8备份m(2)':typeId==4?'fy_coipon_2':typeId==5?'编组 8备份 2':'fy_coupon_1'
                    }.png'))
                  ),
                  alignment: Alignment.center,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      // RichText(text: TextSpan(
                      //   text: '共',
                      //   style: TextStyle(fontSize: 14,color: Colors.white,fontWeight: FontWeight.bold),
                      //   children: [
                      //     TextSpan(
                      //       text: ' ${widget.item['count']} ',
                      //       style: TextStyle(fontSize: 24)
                      //     ),
                      //     TextSpan(
                      //       text: '张'
                      //     )
                      //   ]
                      // )),
                      Padding(
                        padding: EdgeInsets.only(top: 10,bottom: 20),
                        child: Image.asset('lib/images/${_type==1?'fy_mom':'fy_child'}.png',height: 25,width: 25,),
                      ),
                      Stack(
                        children: [
                          Image.asset('lib/images/${
                              typeId==1?'编组 9m':typeId==2?'编组 9m(1)':typeId==3?'编组 9m(2)':typeId==4?'fy_hx_2':typeId==5?'编组 9备份':'fy_hx_1'
                            }.png',height: 20,width: 56,),
                          Container(
                            padding: EdgeInsets.only(left: 15),
                            height: 20,
                            width: 56,
                            child: Text('核销码',style: TextStyle(fontSize: 7,color: Colors.white),),
                            alignment: Alignment.centerLeft,
                          )
                        ],
                      )
                    ],
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}
