import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:zhiying_base_widget/dialog/global_dialog/intellect_search_goods_dialog/model/has_goods_dialog_style_model.dart';
import 'package:zhiying_base_widget/dialog/global_dialog/intellect_search_goods_dialog/model/intellect_dialog_data_model.dart';
import 'package:zhiying_base_widget/widgets/home/home_quick_entry/cached_network_image_util.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:zhiying_base_widget/widgets/wallet/wallet_detail/model/wallet_detail_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:provider/provider.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:flutter_alibc/flutter_alibc.dart';
import 'package:flutter_alibc/alibc_model.dart';

class IntellectSearchGoodsDialog extends StatefulWidget {
  final IntellectDialogDataModel model;

  const IntellectSearchGoodsDialog({Key key, this.model}) : super(key: key);

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

class _IntellectSearchGoodsDialogState
    extends State<IntellectSearchGoodsDialog> {
  HasGoodsDialogStyleModel _styleModel;
  UserInfoModel _userInfo;

  @override
  void initState() {
    //Clipboard.setData(ClipboardData(text: ""));
    requestStyle();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    _userInfo = Provider.of<UserInfoNotifier>(context).userInfo;
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: InkWell(
        onTap: () {
          Navigator.of(context).pop();
        },
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            GestureDetector(
              onTap: () {},
              child: Stack(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(top: 38.h, left: 92.w, right: 92.w),
                    padding: EdgeInsets.only(
                        top: (38 + 38).h,
                        left: 30.w,
                        right: 30.w,
                        bottom: 48.h),
                    decoration: BoxDecoration(
                        color:
                            HexColor.fromHex(_styleModel?.bgColor ?? "#FFFFFF"),
                        borderRadius: BorderRadius.circular(16)),
                    width: double.infinity,
                    child: Column(
                      children: <Widget>[_bulidTopItem(), _buildBottomItem()],
                    ),
                  ),
                  Container(
                    height: 76.h,
                    child: Center(
                        child: Container(
                      height: 76.h,
                      width: 216.w,
                      child: CachedNetworkImage(
                        imageUrl: _styleModel?.titleImg ?? "",
                        fit: BoxFit.fill,
                      ),
                    )),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  _bulidTopItem() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          width: 160.w,
          height: 160.w,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(6),
              image: DecorationImage(
                  image:
                      CachedNetworkImageProvider(widget.model?.thumbnail ?? ""),
                  fit: BoxFit.fill)),
        ),
        SizedBox(
          width: 19.w,
        ),
        Expanded(
            child: Container(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Column(
                children: <Widget>[
                  Text(
                    widget.model?.title ?? "",
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: Colors.black, fontSize: 24.sp),
                  ),
                  SizedBox(
                    height: 5.h,
                  ),
                  Row(
                    children: <Widget>[
                      Container(
                        decoration: BoxDecoration(
                            color: Colors.red,
                            borderRadius: BorderRadius.circular(2)),
                        padding: EdgeInsets.all(2),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            Container(
                              width: 30.w,
                              height: 30.w,
                              decoration: BoxDecoration(
                                  color: HexColor.fromHex(_styleModel
                                          ?.moduleList?.coupon?.bgColor ??
                                      "")),
                              child: Center(
                                child: Text(
                                  _styleModel?.moduleList?.coupon?.content ??
                                      "",
                                  style: TextStyle(
                                      color: HexColor.fromHex(_styleModel
                                              ?.moduleList?.coupon?.fontColor ??
                                          ""),
                                      fontSize: 20.sp),
                                ),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(left: 4, right: 4),
                              child: Text(
                                "¥" + (widget.model?.couponPrice ?? ""),
                                style: TextStyle(
                                    color: HexColor.fromHex(_styleModel
                                        ?.moduleList?.couponPrice?.fontColor),
                                    fontSize: 20.sp),
                              ),
                            )
                          ],
                        ),
                      ),
                      SizedBox(
                        width: 12.w,
                      ),
                      Container(
                        decoration: BoxDecoration(
                            color: HexColor.fromHex(
                                _styleModel?.moduleList?.commission?.bgColor),
                            borderRadius: BorderRadius.circular(2)),
                        padding: EdgeInsets.all(2),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            SizedBox(
                              height: 30.w,
                            ),
                            Center(
                              child: Padding(
                                padding:
                                    const EdgeInsets.only(left: 4, right: 4),
                                child: Text(
                                  (_styleModel?.moduleList?.commission
                                              ?.content ??
                                          "") +
                                      " ¥" +
                                      (widget.model?.commission ?? ""),
                                  style: TextStyle(
                                      color: HexColor.fromHex(_styleModel
                                              ?.moduleList
                                              ?.commission
                                              ?.fontColor ??
                                          ""),
                                      fontSize: 20.sp),
                                ),
                              ),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                ],
              ),
              SizedBox(
                height: 10.h,
              ),
              Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(bottom: 2),
                    child: Text(
                      _styleModel?.moduleList?.couponAfter?.content ?? "",
                      style: TextStyle(
                          fontSize: 20.sp,
                          color: HexColor.fromHex(_styleModel
                                  ?.moduleList?.couponAfterPrice?.fontColor ??
                              "")),
                    ),
                  ),
                  Padding(
                    padding:
                        const EdgeInsets.only(bottom: 2, left: 4, right: 4),
                    child: Text(
                      "¥",
                      style: TextStyle(
                          fontSize: 20.sp,
                          color: HexColor.fromHex(_styleModel
                                  ?.moduleList?.couponAfterPrice?.fontColor ??
                              "")),
                    ),
                  ),
                  Text(
                    widget?.model?.price ?? "",
                    style: TextStyle(
                      fontSize: 32.sp,
                      color: HexColor.fromHex(
                          _styleModel?.moduleList?.couponAfterPrice?.fontColor),
                    ),
                  )
                ],
              )
            ],
          ),
        ))
      ],
    );
  }

  _buildBottomItem() {
    return Column(
      children: <Widget>[
        SizedBox(
          height: 24,
        ),
        InkWell(
          child: Row(
            children: <Widget>[
              Expanded(
                  child: Container(
                margin: EdgeInsets.only(left: 20.w, right: 20.w),
                decoration: BoxDecoration(
                    color: HexColor.fromHex(
                        _styleModel?.moduleList?.saveBtn?.bgColor ?? ""),
                    borderRadius: BorderRadius.circular(50)),
                child: Center(
                    child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Text(
                    (_styleModel?.moduleList?.saveBtn?.content ?? "") +
                        " ¥" +
                        ((double.tryParse(widget?.model?.couponPrice??"0.0")??0) +
                                double.tryParse(
                                    widget?.model?.commission ?? '0'))
                            .toString()
                            .toString(),
                    style: TextStyle(
                        color: HexColor.fromHex(
                            _styleModel?.moduleList?.saveBtn?.fontColor),
                        fontSize: 24.sp),
                  ),
                )),
              ))
            ],
          ),
          onTap: () {
            openUrl();
          },
        ),
        SizedBox(
          height: 16,
        ),
        InkWell(
          child: Row(
            children: <Widget>[
              Expanded(
                  child: Container(
                margin: EdgeInsets.only(left: 20.w, right: 20.w),
                decoration: BoxDecoration(
                    color: HexColor.fromHex(
                        _styleModel?.moduleList?.viewGoodsBtn?.bgColor ?? ""),
                    borderRadius: BorderRadius.circular(50)),
                child: Center(
                    child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Text(
                    _styleModel?.moduleList?.viewGoodsBtn?.content ?? "",
                    style: TextStyle(
                        color: HexColor.fromHex(
                            _styleModel?.moduleList?.viewGoodsBtn?.fontColor ??
                                ""),
                        fontSize: 24.sp),
                  ),
                )),
              ))
            ],
          ),
          onTap: () {
            openGoodsDetails();
          },
        )
      ],
    );
  }

  void requestStyle() {
    NetUtil.request("/api/v1/cfg/clipboard_identified", onSuccess: (data) {
      _styleModel = HasGoodsDialogStyleModel.fromJson(
          json.decode(data['clipboard_identified']));
      setState(() {});
    });
  }

  void openUrl() async {
    ///跳转购买
    if (_userInfo?.token == null || _userInfo.token == '') {
      print('need login...');
      RouterUtil.goLogin(context);
      return;
    } else {
      if (widget?.model?.provider == 'taobao') {
        TradeResult result =
            await FlutterAlibc.openByUrl(url: widget?.model?.couponUrl);
        Logger.debug('${result.errorCode}   ${result.errorMessage} ');
      } else {
        RouterUtil.openWebview(widget?.model?.couponUrl, context);
      }
    }
  }

  ///打开详情
  void openGoodsDetails() {
    String provider = widget.model.provider;
    String goodId = widget.model.itemId;
    RouterUtil.route(SkipModel(skipIdentifier: "goods_details"),
        {"provider": provider, "good_id": goodId}, context).then((data){
          Navigator.pop(context);
    });
  }
}
