import 'dart:async';

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';
import 'YSCouponCardView.dart';

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

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

class _YSCommunityListItemViewState extends State<YSCommunityListItemView> {
  @override
  Widget build(BuildContext context) {
    String statusStr = widget.item['status']==0?'使用':widget.item['status']==1?'已使用':'已废弃';
    return GestureDetector(
      onTap: (){
        if(widget.item['status']==0){
          // ysShowCenterAlertView(context, YSTipsAlertView(
          //   tipsStr: '是否确认使用社区服务体验券？',
          //   valueSetter: (value){},
          // ));
          ysShowBottomAlertView(context, YSCommunityAlertView(item: widget.item,callback: (){
            CustomerNotification().dispatch(context);
          }),isBarr: true);
        }
      },
      behavior: HitTestBehavior.opaque,
      child: Container(
        height: 150,
        width: ysWidth(context)-30,
        decoration: BoxDecoration(
            image: DecorationImage(image: AssetImage('lib/images/${widget.item['status']==0?'fy_mf_coupon1':'fy_mf_coupon2'}.png'))
        ),
        child: Column(
          children: [
            Container(
              height: 50,
              width: ysWidth(context)-80,
              alignment: Alignment.centerLeft,
              child: RichText(
                maxLines: 1,
                text: TextSpan(
                    text: '${widget.item['couponName']}   ',
                    style: TextStyle(fontSize: 18,color: Colors.white),
                    children: [
                      // TextSpan(
                      //     text: '${widget.item['pregnantWomanName']}',
                      //     style: TextStyle(fontSize: 12,color: Colors.white54)
                      // )
                    ]
                ),
              ),
            ),
            Container(
              height: 100,
              width: ysWidth(context)-80,
              alignment: Alignment.center,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    child: Text('可用机构：${widget.item['hospitalName']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),),
                    alignment: Alignment.centerLeft,
                    height: 20,
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 5,bottom: 5),
                    child: Text('发券时间：${widget.item['createTime']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),),
                    alignment: Alignment.centerLeft,
                    height: 20,
                  ),
                  Container(
                    child: Row(
                      children: [
                        Container(
                          child: Text(widget.item['writeOffTime']!=null?'使用时间：${widget.item['writeOffTime']}':'',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),),
                          width: ysWidth(context)-130,
                        ),
                        Container(
                          width: 50,
                          height: 20,
                          decoration: BoxDecoration(
                              color: widget.item['status']!=0?Color(0xFFBDBDBD):Color(0xFFF07F9E),
                              borderRadius: BorderRadius.all(Radius.circular(50))
                          ),
                          child: Text(statusStr,style: TextStyle(fontSize: 10,color: Colors.white),),
                          alignment: Alignment.center,
                        )
                      ],
                    ),
                    alignment: Alignment.centerLeft,
                    height: 20,
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

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

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

class _YSCommunityAlertViewState extends State<YSCommunityAlertView> {
  Timer _timer;
  String _codeStr = '';
  @override
  void initState() {
    getTimer();
    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/getCommunityVerificationCode', {'idcard':User().idCard,'id':widget.item['id']});
    if(dict!=null){
      _codeStr = dict['message'];
      setState(() {});
    }
  }

  @override
  void dispose() {
    if(_timer!=null){
      _timer.cancel();
    }
    YSScreenChange().change(100);
    Wakelock.disable();
    super.dispose();
  }
  getTimer() {
    _timer =Timer.periodic(Duration(seconds: 3), (timer) async{
      Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'transfer/coupon/verifiedCommunityVoucher', {'idcard':User().idCard,'couponId':widget.item['id']});
      if(dict!=null){
        bool isCheck = dict['data']??false;
        if(isCheck){
          ysShowCenterAlertView(context, YSWriteOffView(voidCallback: (){
            widget.callback();
            Navigator.pop(context);
          },),isTrans: true);
          // ysFlutterToast(context, '已核销');
          // widget.callback();
          // Navigator.pop(context);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.only(topRight: Radius.circular(20),topLeft: Radius.circular(20)),
      child: Container(
        height: 450,
        decoration: BoxDecoration(
          color: Color(0xFFF5F5F5),
        ),
        child: 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: 400,
              width: MediaQuery.of(context).size.width,
              child: 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: 20,
                    // child: Text('$_codeStr',style: TextStyle(fontSize: 16,color: Colors.grey),),
                    alignment: Alignment.center,
                  ),
                  ClipRRect(
                    child: Container(
                      height: 160,
                      color: Colors.white,
                      width: ysWidth(context),
                      child: Stack(
                        children: [
                          // Transform.rotate(
                          //   angle: 2,
                          //   child: Container(
                          //     color: Colors.red,
                          //   ),
                          // ),
                          Column(
                            children: List.generate(
                              2,(index) => Expanded(
                              child: Row(
                                children: List.generate(
                                  2,(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['hospitalName']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),maxLines: 1,),
                                  alignment: Alignment.center,
                                ),
                                Container(
                                  height: 30,
                                  child: Text('发券时间：${widget.item['createTime']}',style: TextStyle(fontSize: 14,color: Color(0xFF444444)),maxLines: 1,),
                                  alignment: Alignment.center,
                                ),
                              ],
                            ),
                          )
                        ],
                      ),
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
