import 'dart:io';
import 'package:chat/data/WebData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/LoadingDialog.dart';
import 'package:flutter/material.dart';

import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:video_player/video_player.dart';
import '../data/UserData.dart';
import '../utils/TokenMgr.dart';
import "package:dio/dio.dart";
import '../utils/HttpUtil.dart';
import '../utils/ShadowButton.dart';

var cardWidth;

class VerificationCenterPage extends StatefulWidget {
  VerificationCenterPage({Key key}) : super(key: key);

  _VerificationCenterPageState createState() => _VerificationCenterPageState();
}

class _VerificationCenterPageState extends State<VerificationCenterPage> {
  String code = '';
  String videoUrl = '';
  String buttonStr = '';
  File videoFile;
  int state = 3;
  bool isPostVideo = false;
  bool isShowPlayButton = true;
  VideoPlayerController _controller;
  static const Separate_Size = 17.0;

  bool isLoadingFish = false;

  @override
  void initState() {
    super.initState();
    getInfo();
  }

  @override
  void dispose() {
    if (_controller != null) {
      _controller.dispose();
    }

    super.dispose();
  }

  getInfo() async {
    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);

    // 0=审核中，1=申请成功，2=申请失败,3未申请
    Response res = await HttpUtil().post('user/female/authInfo',
        data: data, failback: () => Navigator.of(context).pop());
    Map resData = res.data;
    if (resData['code'] == 0) {
      code = resData['data']['Code'];
      state = resData['data']['Status'];
      if (state == 0 || state == 1) {
        isPostVideo = true;
        videoUrl = resData['data']['AttestationValue'];
        _controller = VideoPlayerController.network(videoUrl)
          ..initialize().then((_) {
            setState(() {});
          });
        _controller.addListener(() {
          if (_controller.value.position >= _controller.value.duration) {
            isShowPlayButton = true;
            setState(() {});
          }
        });
        buttonStr = I18n.of(context).under_review;
      }
      isLoadingFish = true;
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    Size screenSize = MediaQuery.of(context).size;
    cardWidth = screenSize.width;

    Widget content = Scaffold(
        appBar: AppBar(
          backgroundColor: AppColors.NewAppbarBgColor,
          title: Text(
            I18n.of(context).certification_center,
            style: TextStyle(color: AppColors.NewAppbarTextColor),
          ),
          centerTitle: true,
          leading: CustomUI.buildCustomLeading(context),
          elevation: 0,
        ),
        body: SafeArea(
            child: Container(
                padding: EdgeInsets.symmetric(horizontal: 10),
                color: const Color(0xFFF4F4F4),
                height: MediaQuery.of(context).size.height,
                child: SingleChildScrollView(
                  child: _buildBody(),
                ))));
    return CustomUI.buildPageLoading(context, content, !isLoadingFish);
  }

  BoxDecoration getCardDecoration() {
    return new BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Color.fromRGBO(230, 230, 230, 1),
            offset: Offset(0, 10),
            blurRadius: 8,
          )
        ],
        borderRadius: BorderRadius.all(Radius.circular(10)));
  }

  Widget _buildBody() {
    return Column(
      children: <Widget>[
        _buildVideo(),
        _buildTip1(),
        SizedBox(height: Separate_Size),
        _buildTip2(),
        SizedBox(height: Separate_Size),
        _buildTip3(),
        SizedBox(height: Separate_Size),
        _buildRegisterButton(),
        Container(
          margin: EdgeInsets.only(top: 10.5, bottom: Separate_Size),
          child: Text(
            I18n.of(context).after_authentication,
            style: TextStyle(fontSize: 12, color: Constants.GreyTextColor),
          ),
        ),
      ],
    );
  }

  Widget _buildVideo() {
    Widget stack = Stack(
      children: <Widget>[
        Container(
          height: 230,
          alignment: Alignment.center,
          child: _controller != null && _controller.value.initialized
              ? AspectRatio(
                  aspectRatio: _controller.value.aspectRatio,
                  child: VideoPlayer(_controller),
                )
              : Container(),
        ),
        InkWell(
            highlightColor: Colors.transparent,
            radius: 0,
            onTap: () {
              setState(() {
                if (!_controller.value.isPlaying) {
                  _controller.seekTo(Duration());
                  _controller.play();
                  isShowPlayButton = false;
                  setState(() {});
                }
              });
            },
            child: Container(
                height: 230,
                alignment: Alignment.center,
                child: Container(
                  color: Colors.black38,
                  child: Icon(
                    Icons.play_arrow,
                    size: _controller != null && _controller.value.isPlaying
                        ? 0
                        : 50,
                    color: Colors.white,
                  ),
                )))
      ],
    );
    Widget img = Container(
      child: Image.asset(
        'assets/images/login/rzzx.png',
        height: 230,
      ),
    );
    return (videoUrl == '') ? img : stack;
  }

  Widget _buildTip1() {
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.only(top: 15, left: 20, right: 20, bottom: 15),
      width: cardWidth,
      child: Column(
        children: <Widget>[
          Container(
              padding: EdgeInsets.only(bottom: 10),
              alignment: Alignment.centerLeft,
              child: Text(
                I18n.of(context).certification_conditions,
                textScaleFactor: 1.0,
                style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Constants.BlackTextColor),
              )),
          Container(
              padding: EdgeInsets.only(bottom: 5),
              alignment: Alignment.centerLeft,
              child: Text(I18n.of(context).conditions1, textScaleFactor: 1.0)),
          Align(
              alignment: Alignment.centerLeft,
              child: Text(I18n.of(context).conditions2, textScaleFactor: 1.0)),
        ],
      ),
      decoration: getCardDecoration(),
    );
  }

  Widget _buildTip2() {
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.only(top: 15, left: 20, right: 20, bottom: 15),
      width: cardWidth,
      child: Column(
        children: <Widget>[
          Container(
              padding: EdgeInsets.only(bottom: 10),
              alignment: Alignment.centerLeft,
              child: Text(
                I18n.of(context).verification_method,
                textScaleFactor: 1.0,
                style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Constants.BlackTextColor),
              )),
          Container(
              alignment: Alignment.centerLeft,
              child: Text(I18n.of(context).method3, textScaleFactor: 1.0)),
          Container(
              padding: EdgeInsets.only(bottom: 10, top: 10),
              alignment: Alignment.center,
              child: Text(
                code,
                textScaleFactor: 1.0,
                style: TextStyle(
                    fontSize: 30,
                    fontWeight: FontWeight.w600,
                    color: const Color(0xFFFF4523)),
              )),
          Align(
              alignment: Alignment.centerLeft,
              child: Text(I18n.of(context).method4, textScaleFactor: 1.0)),
        ],
      ),
      decoration: getCardDecoration(),
    );
  }

  Widget _buildTip3() {
    var str = '';
    if (state == 0) {
      str = I18n.of(context).certificating;
    } else if (state == 2) {
      str = I18n.of(context).re_upload2;
    } else {
      str = I18n.of(context).not_authenticate;
    }
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.only(top: 15, left: 20, right: 20, bottom: 15),
      width: cardWidth,
      child: Column(
        children: <Widget>[
          Container(
              padding: EdgeInsets.only(bottom: 10),
              alignment: Alignment.centerLeft,
              child: Text(
                I18n.of(context).certification_status,
                textScaleFactor: 1.0,
                style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Constants.BlackTextColor),
              )),
          Container(
              padding: EdgeInsets.only(bottom: 5),
              alignment: Alignment.centerLeft,
              child: Text(str, textScaleFactor: 1.0)),
        ],
      ),
      decoration: getCardDecoration(),
    );
  }

  void _sendVideo() async {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return LoadingDialog(
            text: "",
          );
        });
    videoFile = await ImagePicker.pickVideo(source: ImageSource.camera);

    Navigator.of(context).pop();
    if (videoFile != null) {
      var size = await videoFile.length();
      if (size > 104857600) {
        showToast(I18n.of(context).video_more_big);
        videoFile = null;
        return;
      }

      Map data = {"type": 5, "userId": UserData().basicInfo.userId};
      data['sign'] = TokenMgr().getSign(data);
      Response res = await HttpUtil().uploadFile(
          videoFile, data, 'upload/file/postflie', 'video',
          isShowLoading: true);
      var resData = res.data;
      if (resData['code'] == 0) {
        showToast(I18n.of(context).success);
        videoUrl = resData['msg'];
        isPostVideo = true;
        _controller = VideoPlayerController.file(videoFile)
          ..initialize().then((_) {
            // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
            setState(() {});
          });
        _controller.addListener(() {
          if (_controller.value.position >= _controller.value.duration) {
            isShowPlayButton = true;
            setState(() {});
          }
        });
        buttonStr = I18n.of(context).submit;
        setState(() {});
      }
    }
  }

  void postInfo() async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "videoUrl": WebData().deleteDemain(videoUrl),
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('user/auth/video', data: data);
    Map resData = res.data;
    if (resData['code'] == 0) {
      showToast(resData['msg']);
      state = 0;
      buttonStr = I18n.of(context).under_review;
      setState(() {});
    }
  }

  //构建注册按钮
  Widget _buildRegisterButton() {
    Text text = new Text(
        buttonStr == '' ? I18n.of(context).upload_video : buttonStr,
        textScaleFactor: 1.0,
        style: TextStyle(fontSize: 15, color: Colors.white));

    LinearGradient gradientColor = new LinearGradient(colors: <Color>[
      Constants.ConfrimButtonColor,
      Constants.ConfrimButtonColor,
    ]);
    return new Container(
      margin: EdgeInsets.only(top: 5.5),
      height: 44,
      width: MediaQuery.of(context).size.width * 0.86,
      child: ShadowButton().builder(gradientColor, text,
          state == 0 ? () {} : (videoUrl == '' ? _sendVideo : postInfo)),
    );
  }
}
