/*
 * @author lsy
 * @date   2019-09-09
 **/
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:gengmei_flutter_plugin/ScanImagePlugn.dart';
import 'package:gmalpha_flutter/AlbumModel/bean/DirBean.dart';

import 'AlbumModel.dart';

class AlbumPage extends StatefulWidget {
  AlbumModel model;

  AlbumPage(String provider, bool showCamera, int maxCount,
      List<String> selectedList) {
    model = new AlbumModel(provider, showCamera, maxCount, selectedList);
  }

  @override
  State<StatefulWidget> createState() => AlbumState(model);
}

class AlbumState extends State<AlbumPage> {
  final AlbumModel _model;

  AlbumState(this._model);

  @override
  void initState() {
    super.initState();
    _model.initScanImages(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: GestureDetector(
              onTap: () => Navigator.pop(context, ""),
              child: Center(
                child: Container(
                  padding: EdgeInsets.fromLTRB(16, 0, 0, 0),
                  child: Text("取消"),
                ),
              )),
          centerTitle: true,
          title: GestureDetector(
              onTap: () {
                _model.changPopState();
              },
              child: StreamBuilder<String>(
                  stream: _model.titleData.stream,
                  initialData: _model.titleData.data,
                  builder: (context, data) {
                    return Row(
                      children: <Widget>[
                        Expanded(
                          child: Container(),
                        ),
                        data.data == null
                            ? Text(
                                MainDirExplain,
                                style: TextStyle(fontSize: 18),
                              )
                            : Text(data.data, style: TextStyle(fontSize: 18)),
                        Container(
                          margin: EdgeInsets.fromLTRB(1, 0, 0, 0),
                          child: Transform(
                            transform: Matrix4.identity()
                              ..rotateZ(_model.showPop ? 1.6 : 4.7), // 旋转的角度
                            origin: Offset(10, 10), // 旋转的中心点
                            child: Icon(
                              Icons.chevron_right,
                              size: 20,
                            ),
                          ),
                        ),
                        Expanded(
                          child: Container(),
                        ),
                      ],
                    );
                  })),
          actions: <Widget>[
            Center(
                child: GestureDetector(
                    onTap: () => _model.onNext(context),
                    child: Container(
                      margin: EdgeInsets.fromLTRB(0, 0, 16, 0),
                      child: Text(
                        "下一步",
                        style: TextStyle(fontSize: 16),
                      ),
                    )))
          ],
        ),
        body: Stack(
          children: <Widget>[
            mainView(),
            popWindow(),
          ],
        ));
  }

  @override
  void dispose() {
    super.dispose();
    _model.dispose();
  }

  mainView() {
    return StreamBuilder<List<ScanImageItem>>(
      stream: _model.albumLive.stream,
      initialData: _model.albumLive.data,
      builder:
          (BuildContext context, AsyncSnapshot<List<ScanImageItem>> imgList) {
        print("FINALL  $imgList  ${imgList.data}");
        if (imgList.data == null) {
          return Center(child: CircularProgressIndicator());
        }
        if (imgList.data != null && imgList.data.isEmpty) {
          return Center(
            child: Text("没有发现照片哦"),
          );
        }
        return GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              crossAxisSpacing: 5,
              mainAxisSpacing: 5,
              childAspectRatio: 1),
          itemCount:
              _model.showCamera ? imgList.data.length + 1 : imgList.data.length,
          itemBuilder: (BuildContext context, int index) {
            if (index == 0 && _model.showCamera) {
              return GestureDetector(
                  onTap: () => _model.nativeCamera(context),
                  child: Container(
                      color: Colors.yellow,
                      child: Column(
                        children: <Widget>[
                          Expanded(
                            child: Container(),
                          ),
                          Icon(Icons.camera_alt),
                          Container(
                            margin: EdgeInsets.fromLTRB(0, 5, 0, 0),
                            child: Text("本地相机"),
                          ),
                          Expanded(
                            child: Container(),
                          ),
                        ],
                      )));
            }
            int newIndex = _model.showCamera ? index - 1 : index;
            if (imgList.data[newIndex] == null ||
                imgList.data[newIndex].path == null) {
              return Icon(
                Icons.photo,
                size: 20,
              );
            }
            return GestureDetector(
                onTap: () => _model.clickItem(context, newIndex),
                child: Container(
                  decoration: BoxDecoration(
                      image: DecorationImage(
                          image: FileImage(File(imgList.data[newIndex].path)),
                          fit: BoxFit.cover),
                      borderRadius: BorderRadius.all(Radius.circular(3.0))),
                  margin: EdgeInsets.only(left: 2, top: 2, right: 2, bottom: 2),
                  child: Stack(
                    alignment: AlignmentDirectional.topEnd,
                    children: <Widget>[
                      _model.isSelect(newIndex)
                          ? Icon(
                              Icons.check_circle,
                              color: Colors.amberAccent,
                              size: 25,
                            )
                          : Icon(
                              Icons.check_circle_outline,
                              color: Colors.grey,
                              size: 25,
                            ),
                      _model.isFullSelect() && !_model.isSelect(newIndex)
                          ? Container(
                              width: double.maxFinite,
                              height: double.maxFinite,
                              color: Colors.white60,
                            )
                          : Container()
                    ],
                  ),
                ));
          },
        );
      },
    );
  }

  popWindow() {
    return StreamBuilder<List<DirBean>>(
        stream: _model.dirLive.stream,
        initialData: _model.dirLive.data,
        builder: (BuildContext context, AsyncSnapshot<List<DirBean>> snapshot) {
          if (snapshot.data == null) {
            return Container();
          } else {
            return Stack(
              children: <Widget>[
                Container(
                  width: double.maxFinite,
                  height: double.maxFinite,
                  color: Colors.black54,
                ),
                popWindowList(snapshot)
              ],
            );
          }
        });
  }

  popWindowList(AsyncSnapshot<List<DirBean>> snapshot) {
    return Container(
        padding: EdgeInsets.fromLTRB(16, 3, 16, 3),
        color: Colors.white,
        height: 280,
        child: ListView.separated(
            separatorBuilder: (context, index) {
              return Divider();
            },
            itemCount: snapshot.data.length,
            itemBuilder: (context, index) {
              return GestureDetector(
                onTap: () => _model.selectDir(index),
                child: Row(
                  children: <Widget>[
                    Container(
                      width: 50,
                      height: 50,
                      child: Image.file(
                        snapshot.data[index].pic,
                        fit: BoxFit.cover,
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
                      child: Text(
                          "${snapshot.data[index].dirName} (${snapshot.data[index].picCount})"),
                    ),
                    Expanded(
                      child: Container(),
                    ),
                    Icon(Icons.chevron_right)
                  ],
                ),
              );
            }));
  }
}
