import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:zhiying_base_widget/pages/upload_wechat_page/bloc/upload_wechat_bloc.dart';
import 'package:zhiying_base_widget/pages/upload_wechat_page/bloc/upload_wechat_event.dart';
import 'package:zhiying_base_widget/pages/upload_wechat_page/bloc/upload_wechat_repository.dart';
import 'package:zhiying_base_widget/pages/upload_wechat_page/bloc/upload_wechat_state.dart';
import 'package:zhiying_base_widget/pages/upload_wechat_page/model/upload_wechat_model.dart';
import 'package:zhiying_base_widget/widgets/others/action_selected_alert/action_selected_alert.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class UploadWeChatPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<UploadWeChatBloc>(
      create: (_) => UploadWeChatBloc(UploadWeChatRepository())..add(UploadWeChatInitEvent()),
      child: _UploadWeChatPage(),
    );
  }
}

class _UploadWeChatPage extends StatefulWidget {
  @override
  __UploadWeChatPageState createState() => __UploadWeChatPageState();
}

class __UploadWeChatPageState extends State<_UploadWeChatPage> {
  /// 是否上传中
  bool _isUploading = false;
  bool _canSubmit = true;
  TextEditingController _editingController;
  File _qrCodeImg;

  /// 选择图片
  void _onAddImage() async {
    Logger.debug('上传图片');

    var status = await Permission.photos.status;
    if (status != PermissionStatus.granted) {
      status = await Permission.photos.request();
    }
    if (status == PermissionStatus.denied) {
      Fluttertoast.showToast(msg: '暂无权限，图片选择失败');
      return null;
    }

    final picker = ImagePicker();
    PickedFile file = await picker.getImage(source: ImageSource.gallery);

    if (file == null) return;

    setState(() {
      _qrCodeImg = File(file.path);
    });
    // File resultFile = await EncodeUtil.compressImage(file, 800);
  }

  /// 点击提交事件
  void _submitOnClick() {
    if (!_isUploading) {

      String wxAccount = _editingController?.text?.toString();
      if (EmptyUtil.isEmpty(wxAccount)) {
        Fluttertoast.cancel();
        Fluttertoast.showToast(msg: '微信号不能为空');
        return;
      }
      if (EmptyUtil.isEmpty(_qrCodeImg)) {
        Fluttertoast.cancel();
        Fluttertoast.showToast(msg: '请上传二维码');
        return;
      }

      setState(() {
        _isUploading = true;
      });
      BlocProvider.of<UploadWeChatBloc>(context).add(UploadWeChatSubmitEvent(file: _qrCodeImg, wxAccount: wxAccount));
    }
  }

  @override
  void initState() {
    _editingController = TextEditingController();
    super.initState();
  }

  @override
  void dispose() {
    _editingController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: HexColor.fromHex('#FFF9F9F9'),
      appBar: _buildAppBarWidget(),
      body: SingleChildScrollView(
        child: BlocConsumer<UploadWeChatBloc, UploadWeChatState>(
          listener: (context, state) {},
          buildWhen: (prov, current) {
            if (current is UploadWeChatInitErrorState) {
              return false;
            }
            if (current is UploadWeChatSubmitErrorState) {
              _isUploading = false;
            }
            if (current is UploadWeChatSubmitSuccessState) {
              _isUploading = false;
              Fluttertoast.showToast(msg: '上传成功');
            }
            return true;
          },
          builder: (context, state) {
            if (state is UploadWeChatLoadedState) {
              if (!EmptyUtil.isEmpty(state?.model?.wxAccount)) {
                _editingController.text = state.model.wxAccount;
              }
              return _buildMainWidget(state?.model);
            }
            return _buildMainWidget(null);
          },
        ),
      ),
    );
  }

  Widget _buildMainWidget(UploadWeChatModel model) {
    return Column(
      children: <Widget>[
        _buildWeChatImageWidget(model),
        _createLine(),
        _createInput('微信号', _editingController),
        Padding(padding: const EdgeInsets.symmetric(horizontal: 12.5, vertical: 15), child: _buildSubmitButtonWidget()),
      ],
    );
  }

  /// 二维码图片
  Widget _buildWeChatImageWidget(UploadWeChatModel model) {
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.only(top: 5),
      padding: const EdgeInsets.only(top: 15, bottom: 15),
      decoration: BoxDecoration(
        color: HexColor.fromHex('#FFFFFFFF'),
      ),
      child: Column(
        children: <Widget>[
          GestureDetector(
            onTap: () => _onAddImage(),
            behavior: HitTestBehavior.opaque,
            child: Container(
              height: 90,
              width: 90,
              // color: Colors.red,
              child: !EmptyUtil.isEmpty(_qrCodeImg)
                  ? Image.file(
                      _qrCodeImg,
                      fit: BoxFit.cover,
                    )
                  : !EmptyUtil.isEmpty(model?.wxQrcode)
                      ? CachedNetworkImage(
                          imageUrl: model?.wxQrcode ?? '',
                          fit: BoxFit.cover,
                        )
                      : Image.asset(
                          'assets/images/qrcode/default_qrcode.png',
                          package: 'zhiying_base_widget',
                        ),
            ),
          ),
          const SizedBox(height: 6),
          GestureDetector(
            onTap: () => _onAddImage(),
            behavior: HitTestBehavior.opaque,
            child: Text(
              '点击上传二维码',
              style: TextStyle(color: HexColor.fromHex('#FF999999'), fontSize: 13),
            ),
          )
        ],
      ),
    );
  }

  /// 阴影
  Widget _createLine() {
    return Container(
      width: double.infinity,
      height: 0.5,
      margin: EdgeInsets.only(left: 12.5, right: 12.5),
      color: HexColor.fromHex('#FFF7F7F7'),
    );
  }

  Widget _createInput(String title, TextEditingController controller, {VoidCallback onTap}) {
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.only(left: 12.5, right: 12.5),
        height: 48,
        color: Colors.white,
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text(
                title ?? '',
                style: TextStyle(fontSize: 13, color: Color(0xff333333), fontWeight: FontWeight.bold),
              ),
            ),
            Expanded(
              child: CupertinoTextField(
                decoration: BoxDecoration(color: Colors.transparent),
                textInputAction: TextInputAction.done,
                controller: controller,
                textAlign: TextAlign.right,
                placeholder: '请输入微信号',
                style: TextStyle(
                  fontSize: 13,
                  color: Color(0xff999999),
                ),
              ),
            ),
            onTap == null
                ? Container()
                : Icon(
                    Icons.arrow_forward_ios,
                    size: 12,
                    color: Color(0xff999999),
                  )
          ],
        ),
      ),
      onTap: onTap,
    );
  }

  /// 提交按钮
  Widget _buildSubmitButtonWidget() {
    return Material(
      child: Container(
        height: 48,
        width: double.infinity,
        color: Colors.white,
        child: RaisedButton(
          child: Text(
            _isUploading ? '提交中...' : '提交',
            style: TextStyle(fontSize: 15),
          ),
          textColor: HexColor.fromHex('#FFFFFF'),
          color: HexColor.fromHex('#FFFF4242'),
          disabledColor: HexColor.fromHex('#F5F5F5'),
          disabledTextColor: HexColor.fromHex('#999999'),
          elevation: 5,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(52 / 2)),
          onPressed: _canSubmit ? _submitOnClick : null,
        ),
      ),
    );
  }

  /// appbar
  Widget _buildAppBarWidget() {
    return AppBar(
      backgroundColor: HexColor.fromHex('#FFFFFF'),
      brightness: Brightness.light,
      leading: IconButton(
        icon: Icon(
          Icons.arrow_back_ios,
          size: 22,
          color: HexColor.fromHex('#333333'),
        ),
        onPressed: () => Navigator.maybePop(context),
      ),
      title: Text(
        '填写微信号',
        style: TextStyle(color: HexColor.fromHex('#333333'), fontSize: 15, fontWeight: FontWeight.bold),
      ),
      centerTitle: true,
      elevation: 0,
    );
  }
}
