import 'dart:io';
import 'dart:typed_data';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:chat/data/UserData.dart';
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/HttpUtil.dart';
import 'package:chat/utils/PicSwiper.dart';
import 'package:chat/utils/file_cache_mgr.dart';
import 'package:chat/utils/screen.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:multi_image_picker/multi_image_picker.dart';

import 'package:oktoast/oktoast.dart';
import '../data/UserData.dart';
import '../utils/TokenMgr.dart';

enum reason {
  advertising,
  rail,
  breakAppointment,
  sex,
  liar,
}

const int MaxImgNum = 4;

class InformUserPage extends StatefulWidget {
  @required
  final userId;
  final programId;
  final isProgram;
  @required
  final bool isMan;
  InformUserPage(
      {Key key,
      this.userId,
      this.programId,
      this.isMan = false,
      this.isProgram = false})
      : super(key: key);

  _InformUserPageState createState() => _InformUserPageState();
}

class _InformUserPageState extends State<InformUserPage> {
  int _socialType = 0;
  bool parkHidden = false;
  bool distanceHidden = false;
  bool msgHidden = false;
  String explain = '';

  //List imgFileList = [];

  //上传图片地址
  List<String> imgUrlList = [];

  BoxDecoration _getCardDecoration() {
    return new BoxDecoration(color: Colors.white);
  }

  @override
  void initState() {
    super.initState();
    print('InformUserPage initState');
  }

  @override
  Widget build(BuildContext context) {
    Widget appBar = new AppBar(
      title: Text(
        I18n.of(context).anonymous_report,
        textScaleFactor: 1.0,
      ),
      leading: CustomUI.buildCustomLeading(context),
      centerTitle: true,
      actions: <Widget>[
        new Container(
          alignment: Alignment.center,
          child: new InkWell(
            child: new Padding(
              padding:
                  EdgeInsets.only(right: 15, left: 15, top: 10, bottom: 10),
              child: new Text(I18n.of(context).submit,
                  textScaleFactor: 1.0, style: Constants.AppBarActionTextStyle),
            ),
            onTap: () async {
              if (imgUrlList == null || imgUrlList.length == 0) {
                showToast(I18n.of(context).bad_evaluate);
                return;
              }
              var data = {
                "reportuserId": UserData().basicInfo.userId,
                "userid": widget.userId,
              };
              data['sign'] = TokenMgr().getSign(data);
              data['type'] =
                  widget.programId == null ? 1 : (widget.isProgram ? 2 : 3);
              data['objectId'] =
                  widget.programId == null ? 0 : widget.programId;
              data['reason'] = _socialType + 1;
              String temp = "";
              imgUrlList.forEach((str) {
                temp += (temp == ""
                    ? WebData().deleteDemain(str)
                    : '|${WebData().deleteDemain(str)}');
              });
              data["imgurl"] = temp;
              data["explain"] = explain;
              Response res = await HttpUtil()
                  .post('report/user/insert', data: data, isShowLoading: true);
              Map resData = res.data;
              if (resData['code'] == 0) {
                CustomUI.buildOneConfirm(context,
                    I18n.of(context).waiting_results, I18n.of(context).ok, () {
                  Navigator.of(context).pop();
                  Navigator.of(context).pop();
                }, failcallbak: () {
                  Navigator.of(context).pop();
                });
              } else {
                showToast(resData['msg']);
              }
            },
          ),
        )
      ],
    );
    return Scaffold(
      body: SafeArea(
          child: Center(
        child: Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: _buildBody(),
        ),
      )),
      appBar: appBar,
    );
  }

  Widget _buildBody() {
    return new ListView(
      children: <Widget>[
        _userDetail(),
        _buildMoreInfo(),
        _buildTips(),
      ],
    );
  }

  Widget _buildTips() {
    return Container(
      margin: EdgeInsets.only(top: 5, left: 30, right: 30),
      child: Text(
        I18n.of(context).if_something,
        textScaleFactor: 1.0,
        style: TextStyle(fontSize: 12, color: Colors.grey[700]),
        textAlign: TextAlign.center,
      ),
    );
  }

  //下划线
  Widget _buildDivider() {
    return new Container(
      margin: EdgeInsets.zero,
      padding: EdgeInsets.zero,
      height: 1,
      width: MediaQuery.of(context).size.width,
      child: new Divider(
        color: Colors.grey[300],
      ),
    );
  }

  void _sendPicture() async {

    List<Asset> resultList = List<Asset>();

    resultList = await MultiImagePicker.pickImages(
      maxImages: MaxImgNum - imgUrlList.length,
      enableCamera: false,
      selectedAssets: [],
      cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
      materialOptions: MaterialOptions(
        actionBarColor: "#50A7F9",
        actionBarTitle: "Hibok",
        allViewTitle: "",
        useDetailsView: false,
        selectCircleStrokeColor: "#000000",
      ),
    );

    if (resultList != null && resultList.length > 0) {
      List<File> fileList = [];
      for (var i = 0; i < resultList.length; i++) {
        Asset photoEntity = resultList[i];
        ByteData byteData = await photoEntity.getByteData();
        File file =  await FileCacheMgr().writeFile('temp-photo-${DateTime.now().millisecondsSinceEpoch}-${photoEntity.name}', byteData.buffer.asInt8List(0));
        fileList.add(file);
      }
      Map data = {"type": 3, "userId": UserData().basicInfo.userId};
      data['sign'] = TokenMgr().getSign(data);
      Response res = await HttpUtil().uploadFiles(
          fileList, data, 'upload/post/postfiles', 'image',
          isShowLoading: true);
      var resData = res.data;
      if (resData['code'] == 0 && resData['msg'] != null) {
        imgUrlList.addAll(resData['msg'].split("|"));
        setState(() {});
      }
    }



//    var photos = await PhotoPicker.pickAsset(
//        context: context,
//        themeColor: Color(0xFFF0F0F0),
//        maxSelected: MaxImgNum - imgUrlList.length,
//        textColor: Color(0xFF3F3F3F),
//        pickType: PickType.onlyImage);
//
//    if (photos != null && photos.length > 0) {
//      List<File> fileList = [];
//      for (var i = 0; i < photos.length; i++) {
//        AssetEntity photoEntity = photos[i];
//        fileList.add(await photoEntity.file);
//      }
//      Map data = {"type": 3, "userId": UserData().basicInfo.userId};
//      data['sign'] = TokenMgr().getSign(data);
//      Response res = await HttpUtil().uploadFiles(
//          fileList, data, 'upload/post/postfiles', 'image',
//          isShowLoading: true);
//      var resData = res.data;
//      if (resData['code'] == 0 && resData['msg'] != null) {
//        imgUrlList.addAll(resData['msg'].split("|"));
//        setState(() {});
//      }
//    }
  }

  Widget _buildRadioButtom(str, radio, callback) {
    Widget left = Text(
      str,
      textScaleFactor: 1.0,
      style: TextStyle(fontSize: 14),
    );
    Widget right = new Expanded(
        child: new Align(
      alignment: Alignment.centerRight,
      child: radio,
    ));
    return InkWell(
      onTap: () {
        callback();
      },
      child: Container(
        padding: EdgeInsets.only(left: 15),
        child: new Row(
          children: <Widget>[left, right],
        ),
      ),
    );
  }

  //个人详情
  Widget _userDetail() {
    Widget tip =
        CustomUI.buildTopTip(15, I18n.of(context).report_reason, fontSize: 16);

    Widget radio1 = new Radio(
        value: reason.advertising.index,
        groupValue: _socialType, //当value和groupValue一致的时候则选中
        onChanged: (T) {
          setState(() {
            _socialType = T;
          });
        });
    Widget radio2 = new Radio(
        value: reason.rail.index,
        groupValue: _socialType, //当value和groupValue一致的时候则选中
        onChanged: (T) {
          setState(() {
            _socialType = T;
          });
        });
    Widget radio3 = new Radio(
        value: reason.breakAppointment.index,
        groupValue: _socialType, //当value和groupValue一致的时候则选中
        onChanged: (T) {
          setState(() {
            _socialType = T;
          });
        });
    Widget radio4 = new Radio(
        value: reason.sex.index,
        groupValue: _socialType, //当value和groupValue一致的时候则选中
        onChanged: (T) {
          setState(() {
            _socialType = T;
          });
        });
    Widget radio5 = new Radio(
        value: reason.liar.index,
        groupValue: _socialType, //当value和groupValue一致的时候则选中
        onChanged: (T) {
          setState(() {
            _socialType = T;
          });
        });

    List<Widget> basicList = [
      _buildRadioButtom(I18n.of(context).advertise, radio1, () {
        setState(() {
          _socialType = reason.advertising.index;
        });
      }),
      _buildDivider(),
      _buildRadioButtom(I18n.of(context).harassment, radio2, () {
        setState(() {
          _socialType = reason.rail.index;
        });
      }),
      _buildDivider(),
      _buildRadioButtom(I18n.of(context).false_photo, radio3, () {
        setState(() {
          _socialType = reason.breakAppointment.index;
        });
      }),
      _buildDivider(),
      _buildRadioButtom(I18n.of(context).erotic_vulgarity, radio4, () {
        setState(() {
          _socialType = reason.sex.index;
        });
      }),
      _buildDivider(),
      _buildRadioButtom(
          widget.isMan ? I18n.of(context).he_liar : I18n.of(context).she_liar,
          radio5, () {
        setState(() {
          _socialType = reason.liar.index;
        });
      }),
    ];
    var socialCard = new Container(
      decoration: _getCardDecoration(),
      width: MediaQuery.of(context).size.width,
      child: new Column(
        children: basicList,
      ),
    );
    return new Column(
      children: <Widget>[tip, socialCard],
    );
  }

  Widget _buildMoreInfo() {
    Widget tip = CustomUI.buildTopTip(15, I18n.of(context).provide_screenshots,
        fontSize: 15);
    Widget upButton = Container(
        child: InkWell(
            onTap: _sendPicture,
            child: Container(
                margin: EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10.0),
                    border: Border.all(color: Colors.grey)),
                width: 75,
                height: 75,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: Icon(
                    IconData(
                      0xe616,
                      fontFamily: 'iconfont',
                    ),
                    color: Colors.grey,
                  ),
                ))));
    List<Widget> list = imgUrlList.map((f) {
      return _buildImg(f);
    }).toList();
    if (list.length < MaxImgNum) {
      list.add(upButton);
    }
    var socialCard = new Container(
      width: MediaQuery.of(context).size.width,
      decoration: _getCardDecoration(),
      padding: EdgeInsets.only(bottom: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
              padding: EdgeInsets.only(left: 10, top: 10, bottom: 10),
              child: Wrap(
                  crossAxisAlignment: WrapCrossAlignment.start,
                  children: list)),
          _buildDivider(),
          Container(
              margin: EdgeInsets.only(top: 10, left: 14),
              child: fixedText(I18n.of(context).describe_details)),
          Container(
            padding: EdgeInsets.only(top: 2, left: 8, right: 14),
            child: TextField(
              keyboardAppearance: Brightness.light,
              style: TextStyle(textBaseline: TextBaseline.alphabetic),
              decoration: new InputDecoration(
                hintText: I18n.of(context).optional,
                hintStyle: TextStyle(fontSize: 14),
                border: InputBorder.none,
              ),
              maxLines: 5,
              maxLength: 200,
              onChanged: (str) {
                explain = str;
              },
            ),
          ),
        ],
      ),
    );

    return new Column(
      children: <Widget>[tip, socialCard],
    );
  }

  Widget _buildImg(f) {
    return Stack(
      children: <Widget>[
        InkWell(
            onTap: () {
              Navigator.of(context).push(
                new MaterialPageRoute(
                  builder: (context) {
                    return PicSwiper(
                      id: imgUrlList.indexOf(f),
                      pics: imgUrlList
                          .map((f) => PicSwiperItem(
                                f,
                                id: imgUrlList.indexOf(f),
                              ))
                          .toList(),
                    );
                  },
                ),
              );
            },
            child: Container(
                height: 75,
                width: 75,
                margin: EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5),
                decoration:
                    BoxDecoration(borderRadius: BorderRadius.circular(2.0)),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: f == null
                      ? Container()
                      : CachedNetworkImage(
                          imageUrl: f,
                          fit: BoxFit.cover,
                        ),
                ))),
        Positioned(
          right: 0,
          child: InkWell(
              onTap: () {
                imgUrlList.remove(f);
                setState(() {});
              },
              child: Image.asset(
                'assets/images/login/delete.png',
                height: 20,
              )),
        )
      ],
    );
  }
}
