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/widgets/selected_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'dart:io';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:convert';
import 'package:liftmanager/utils/url.dart';
import 'package:liftmanager/utils/time_format.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'package:liftmanager/internal/bbs/model/shop_detail.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'dart:math';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:liftmanager/utils/theme_utils.dart';

class ProductDetail extends StatefulWidget {
  ProductDetail(this.id);

  final String id;
  

  @override
  State<StatefulWidget> createState() {
    return ProductDetailState();
  }
}

class ProductDetailState extends State<ProductDetail> {
  
  @override
  void initState() {
    super.initState();
    getShopDetail();
  }

  bool _hasData = false;
  ShopDetailModel detailObj;

  Future getShopDetail() async {
    await NewApiService().getShopDetail(int.parse(widget.id),1,
        onSuccess: (res) {
      if (res != null) {
        _hasData = true;
        detailObj = res;
        setState(() {});
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }


  showAlertEvent(){
    showAlert(
                              context,
                              "提示",
                              "确定登录？",
                              "确定",
                              () {
                                NavigatorUtils.push(context, AccountRouter.loginPage, clearStack: true);
                              },
                              txt2: "取消",
                              onPre2: () {
                                NavigatorUtils.goBack(context);
                              },
                            );
  }


  Future changeFav(type) async {
    await NewApiService().shopFav(detailObj.id, type, 1, onSuccess: (res) {
      toasts("收藏成功");
      initCollect();
      getShopDetail();
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future cancelFav() async {
    await NewApiService().shopFavCancel(detailObj.favoriteId, onSuccess: (res) {
      toasts("取消收藏成功");
      initCollect();
      getShopDetail();
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  _launchPhone(url) async {
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        throw 'Could not launch $url';
      }
    }

  initCollect(){
    String collectInit = randomInt(1111,9999).toString() + DateTime.now().millisecondsSinceEpoch.toString();
    FastNotification.push("collectAction",collectInit);
  }

  randomInt(int min, int max) {
    return new Random().nextInt(max) % (max - min + 1) + min;
  }

  @override
  Widget build(BuildContext context) {

    double width = MediaQuery.of(context).size.width;

    return Scaffold(
      resizeToAvoidBottomPadding: false,//不让键盘弹上去
      appBar: MyAppBar(
        centerTitle: "商品详情",
      ),
      body: _hasData?Stack(
          children: <Widget>[
            Container(
              child: ListView(
                children: <Widget>[
                  Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.only(left:ScreenUtil().setWidth(15),right:ScreenUtil().setWidth(15),top:ScreenUtil().setWidth(10),bottom:ScreenUtil().setWidth(10)),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(width: 0.5, color: Colours.line),
                        
                      ),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children:<Widget>[
      //                   Column(
      //                     children: detailObj.imgs.split(",").asMap().keys.map((i){
      //                         return 
      //                         Container(
      //                           padding: EdgeInsets.only(bottom:10),
      //                     child: ClipRRect(
      //                     borderRadius: BorderRadius.circular(ScreenUtil().setWidth(10)),
      //                     child: Container(
      //                       // width:width,
      //                       // height: ScreenUtil().setWidth(220),
      //                       child:
      //                       Swiper(
      //   itemBuilder: (BuildContext context, index) {
      //     return Container(
      //       width: width,
      //       height: ScreenUtil().setWidth(220),
      //       key: Key(detailObj.imgs.split(",")[index]),
      //       child:
      //           LoadNetworkImage(
      //         detailObj.imgs.split(",")[index],
      //         width: width,
      //         height: ScreenUtil().setWidth(220),
      //         fit: BoxFit.fill,
      //       ),
      //     );
      //   },
      //   pagination: SwiperPagination(
      //       builder: DotSwiperPaginationBuilder(
      //           color: Colors.grey,
      //           activeColor: Colors.white,
      //           size: 6,
      //           activeSize: 6)),
      //   itemCount: detailObj.imgs.split(",").length,
      //   scrollDirection: Axis.horizontal,
      //   autoplay: true,
      //   onTap: (index) {
      //     // print(index);
      //   },
      // ),
      //                       // LoadNetworkImage(
      //                       //   detailObj.imgs.split(",")[i],
      //                       //   fit: BoxFit.cover,
                              
      //                       // ),
      //                     ),
      //                   ),
      //                   );
      //                       }).toList(),
      //                   ),
                        Container(
                          width: width,
            height: ScreenUtil().setWidth(220),
                                padding: EdgeInsets.only(bottom:10),
                          child: ClipRRect(
                          borderRadius: BorderRadius.circular(ScreenUtil().setWidth(10)),
                          child: Container(
                            // width:width,
                            // height: ScreenUtil().setWidth(220),
                            child:
                            Swiper(
        itemBuilder: (BuildContext context, index) {
          return Container(
            width: width,
            height: ScreenUtil().setWidth(220),
            key: Key(detailObj.imgs.split(",")[index]),
            child:
                LoadNetworkImage(
              detailObj.imgs.split(",")[index],
              width: width,
              height: ScreenUtil().setWidth(220),
              fit: BoxFit.fill,
              isWater: true,
            ),
          );
        },
        pagination: SwiperPagination(
            builder: DotSwiperPaginationBuilder(
                color: Colors.grey,
                activeColor: Colors.white,
                size: 6,
                activeSize: 6)),
        itemCount: detailObj.imgs.split(",").length,
        scrollDirection: Axis.horizontal,
        autoplay: false,
        onTap: (index) {
          // print(index);
        },
      ),
                            // LoadNetworkImage(
                            //   detailObj.imgs.split(",")[i],
                            //   fit: BoxFit.cover,
                              
                            // ),
                          ),
                        ),
                        ),
                        SizedBox(
                          height:5
                        ),
                        Text(
                          detailObj.name??"",
                          style: TextStyle(
                            fontSize:ScreenUtil().setSp(16)
                          ),
                          textAlign:TextAlign.start,
                        ),
                        Text(
                          detailObj.brandName??"",
                          style: TextStyle(
                            color:Color(0xff666666),
                            fontSize:ScreenUtil().setSp(14)
                          ),
                          textAlign:TextAlign.start,
                        ),
                        Row(
                          children: <Widget>[
                            Text(
                              "推荐价格：",
                              style: TextStyle(
                                color:Color(0xff666666),
                                fontSize:ScreenUtil().setSp(14)
                              ),
                              textAlign:TextAlign.start,
                            ),
                            Text(
                              detailObj.price!=null?detailObj.price.toString():"",
                              style: TextStyle(
                                color:Color(0xffff0000),
                                fontSize:ScreenUtil().setSp(16)
                              ),
                              textAlign:TextAlign.start,
                            ),
                          ],
                        ),
                        
                        SizedBox(
                          height:15
                        ),
                      ]
                    ),
                  ),
                  
                  
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        padding:EdgeInsets.only(left:ScreenUtil().setWidth(15),right:ScreenUtil().setWidth(15),top:ScreenUtil().setWidth(10),bottom:ScreenUtil().setWidth(5)),
                        child: Text(
                          "商品简介",
                          style: TextStyle(
                                fontSize:ScreenUtil().setSp(16),
                                
                          ),
                          textAlign:TextAlign.left,
                        ),
                      ),
                      Container(
                        padding:EdgeInsets.only(left:ScreenUtil().setWidth(15),right:ScreenUtil().setWidth(15),top:ScreenUtil().setWidth(10),bottom:ScreenUtil().setWidth(50)),
                        child: Text(
                          detailObj.descr,
                          style: TextStyle(
                                color:Color(0xff999999),
                                fontSize:ScreenUtil().setSp(14),
                                
                          ),
                          textAlign:TextAlign.left,
                        ),
                      ),
                    ],
                  ),
                  Container(
                    height:5,
                    color:ThemeUtils.getDialogTextFieldColor(context)
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        padding:EdgeInsets.only(left:ScreenUtil().setWidth(15),right:ScreenUtil().setWidth(15),top:ScreenUtil().setWidth(10),bottom:ScreenUtil().setWidth(5)),
                        child: Text(
                          "供应商: ${detailObj.manufacturer}",
                          style: TextStyle(
                                color:Color(0xff999999),
                                fontSize:ScreenUtil().setSp(14),
                                
                          ),
                          textAlign:TextAlign.left,
                        ),
                      ),
                      Container(
                        padding:EdgeInsets.only(left:ScreenUtil().setWidth(15),right:ScreenUtil().setWidth(15),top:ScreenUtil().setWidth(10),bottom:ScreenUtil().setWidth(50)),
                        child: Text(
                          "Tel: ${detailObj.telephone} ${detailObj.contactPerson != null ? '(' + detailObj.contactPerson + ')' : ''}",
                          style: TextStyle(
                                color:Color(0xff999999),
                                fontSize:ScreenUtil().setSp(14),
                                
                          ),
                          textAlign:TextAlign.left,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height:ScreenUtil().setWidth(70))
                ],
              ),
                ]
              )
              
            ),
            Positioned(
              bottom:0,
              left:0,
              child:Container(
                width: width,
                child: Row(
                  children:<Widget>[
                    Container(
                      height:ScreenUtil().setWidth(70),
                      width:width/2,
                      color:Colors.white,
                      padding: EdgeInsets.only(left:ScreenUtil().setWidth(10),right:ScreenUtil().setWidth(10),top:ScreenUtil().setWidth(10)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: <Widget>[
                          GestureDetector(
                            onTap: (){

                              if(FlutterStars.SpUtil.getString(Constant.userId) == "-1"){
                                showAlertEvent();
                              }else {
                                
                                String initThis = randomInt(1111,9999).toString() + DateTime.now().millisecondsSinceEpoch.toString();

                                fluwx.shareToWeChat(fluwx.WeChatShareWebPageModel(
                                  scene: fluwx.WeChatScene.SESSION,
                                  webPage: "$jumpUrl/h5/index.html?num=$initThis&page=/bbs/productDetail&id=${widget.id}",
                                  title: detailObj.name,
                                  description: detailObj.descr,
                                  thumbnail: detailObj.imgs.split(",")[0],
                                )).then((result){

                                },
                                onError: (msg){
                                  // print(msg);
                                });

                              }

                            },
                            child: Container(
                            // padding: EdgeInsets.only(left:25,right:30),
                            child:Column(
                              children:<Widget>[
                                Icon(
                                  IconData(
                                    0xe6f4,
                                    fontFamily:"myfont"
                                  ),
                                  size: 26.0,
                                  color:Color(0xff333333),
                                ),
                                Text(
                                  "分享",
                                  style: TextStyle(
                                    color:Color(0xff000000),
                                    fontSize:ScreenUtil().setSp(14)
                                  ),
                                  textAlign:TextAlign.start,
                                ),
                              ]
                            )
                          ),
                          ),
                          GestureDetector(
                            onTap: () {
                              if(FlutterStars.SpUtil.getString(Constant.userId) == "-1"){
                                showAlertEvent();
                              }else {

                                      if (detailObj.isFavorite == 1) {
                                        cancelFav();
                                      } else {
                                        changeFav(3);
                                      }
                              }
                            },
                            child: Container(
                            child:Column(
                              children:<Widget>[
                                Icon(
                                  IconData(
                                    detailObj.isFavorite == 1
                                                ? 0xe654
                                                : 0xe604,
                                    fontFamily:"myfont"
                                  ),
                                  size: 26.0,
                                  color:Color(detailObj.isFavorite == 1
                                            ? 0xff0388FD
                                            : 0xff333333),
                                ),
                                
                                Text(
                                  detailObj.isFavorite == 1
                                            ? "已收藏"
                                            : "收藏",
                                  style: TextStyle(
                                    color:Color(detailObj.isFavorite == 1
                                                    ? 0xff0388FD
                                                    : 0xff000000),
                                    fontSize:ScreenUtil().setSp(14)
                                  ),
                                  textAlign:TextAlign.start,
                                ),
                              ]
                            )
                          ),
                          )
                        ],
                      )
                    ),
                    Container(
                      height:ScreenUtil().setWidth(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: () {
                          
                          print(222);

                          if(FlutterStars.SpUtil.getString(Constant.userId) == "-1"){
                                showAlertEvent();
                              }else {
                          _launchPhone("tel:"+detailObj.telephone);}
                        },
                      ),
                    ),
                  ]
                )
              )
            )
          ],
      
    ): Center(
              child: Text("正在加载..."),
            ),
    );
  }
}
