/*
 * @Author: WuXiangNan
 * @Date: 2021-07-07 11:21:46
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-05-16 09:28:04
 * @Description: 
 */

import 'package:app_package/app_package.dart';
import 'package:cabinet_package/src/assets.gen.dart';
import 'package:cabinet_package/src/service/imp/cabinet_service_imp.dart';
import 'package:cabinet_package/src/view_stores/cabinet_store.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class DirectoryPage extends StatelessWidget {
  const DirectoryPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => CabinetStore(context),
      child: _PageView(),
    );
  }
}

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

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

class __PageViewState extends State<_PageView> {
  late CabinetStore cabinetStore;
  CabinetStore get _store => Provider.of(context, listen: false);
  late var screenWidth;
  late var colorScheme;

  @override
  Widget build(BuildContext context) {
    cabinetStore = Provider.of<CabinetStore>(context);
    colorScheme = WTheme.of(context).colorScheme;
    screenWidth = MediaQuery.of(context).size.width;

    return Scaffold(
      appBar: WAppBar(
        brightness: Brightness.light,
        title: WisText('${_store.args['appBarTitle']}',
            size: 19.pt, weight: FontWeight.w600, color: colorScheme.mainTitle),
        iconTheme: IconThemeData(
          color: colorScheme.mainTitle,
          size: 19.pt,
        ),
        backgroundColor: Colors.white,
        actions: [
          if (cabinetStore.pathList.length > 0)
            Wisdom(
              alignment: Alignment.center,
              margin: EdgeInsets.only(right: 10.0),
              child: WisText(
                '返回上级目录',
                color: colorScheme.mainTitle,
              ),
              onTap: () => cabinetStore.toUpLevel(),
            ),
        ],
      ),
      body: Wisdom.column(
        children: [
          if (cabinetStore.pathList.length > 0) ...[
            _buildPathShow()
          ] else if (cabinetStore.selectedCompany != null) ...[
            _buildCompanyShow(),
          ] else ...[
            WEmptyWidget(
              text: WisText('空空如也'),
            ),
          ],

          // 根目录下搜索目录
          if (cabinetStore.fileList!.length == 0 &&
              cabinetStore.treeList!.length == 0 &&
              cabinetStore.operatorType != 'filter')
            Wisdom()
          else if (cabinetStore.fileList!.length == 0 &&
              cabinetStore.pathList.length == 0)
            _buildSeachFolder()
          else
            // 子目录时搜索文件
            _buildSeachFile(),

          // 403无权限查看
          if (cabinetStore.unHadAuth)
            _buildUnHadAuth()
          else if (cabinetStore.notNull == false)
            _buildNullFolder()
          else
            Wisdom.column(
              margin: EdgeInsets.only(top: 15.pt),
              children: [
                if (cabinetStore.pathList.length > 0)
                  WisScrollView(
                      key: cabinetStore.fileScorllViewKey,
                      onInit: () => cabinetStore.onInit(),
                      onLoad: () =>
                          cabinetStore.toGetCabinetFileList(isLoad: true),
                      onRefresh: () => cabinetStore.onRefresh(),
                      slivers: [
                        if (cabinetStore.treeList!.length > 0) ...<Widget>[
                          _buildScrollFolderContent(),
                          SizedBox(
                            height: 10.0,
                          ).asSliver(),
                        ],
                        if (cabinetStore.fileList!.length > 0)
                          _buildScrollFileContent(),
                      ]).asExpanded()
                else
                  WisScrollView(
                    slivers: [
                      if (cabinetStore.treeList!.length > 0)
                        _buildScrollFolderContent(),
                    ],
                  ).asExpanded()
              ],
            ).asExpanded(),
        ],
      ),
    );
  }

  // 无权限访问
  Widget _buildUnHadAuth() {
    return Wisdom.column(
      color: Colors.white,
      width: screenWidth,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Wisdom(
          margin: EdgeInsets.only(bottom: 20),
          width: 200.0,
          child: Image(image: AssetList.$wqxck_png_image),
        ),
        WisText(
          '未授权，无权限访问',
          size: 16.0,
        ),
      ],
    ).asExpanded();
  }

  // 路径
  Widget _buildPathShow() {
    return Wisdom(
      width: MediaQuery.of(context).size.width,
      height: 40,
      child: Wisdom.row(
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: 10.pt),
        alignment: Alignment.centerLeft,
        children: [
          Wisdom(
            margin: EdgeInsets.only(right: 10),
            child: Image(
              height: 16.0,
              image: AssetList.$lj_icon_png_image,
            ),
          ),
          WisText(
            '${cabinetStore.directoryPath}',
            color: colorScheme.primary,
            size: 15.0,
          ),
        ],
      ),
    );
  }

  // 选择公司
  Widget _buildCompanyShow() {
    return Wisdom(
      width: MediaQuery.of(context).size.width,
      height: 40,
      child: Wisdom.wrap(
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: 10.pt),
        alignment: Alignment.centerLeft,
        onTap: () => cabinetStore.toOpenBottomModal(),
        children: [
          WisText(
            '${cabinetStore.selectedCompany?.name ?? ''}',
            size: 15.0,
          ),
          Icon(Icons.keyboard_arrow_right, size: 19.pt),
        ],
      ),
    );
  }

  // 目录搜索
  Widget _buildSeachFolder() {
    return Wisdom.column(
      color: Colors.white,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        WSearch(
          isDark: true,
          hintText: '请输入目录名搜索',
          onSubmitted: (value) => cabinetStore.toSearchFolder(value),
          onCancel: () => {
            cabinetStore.searchValue = null,
            cabinetStore.toSearchFolder(null),
          },
        ),
      ],
    );
  }

  // 文件搜索
  Widget _buildSeachFile() {
    return Wisdom.column(
      color: Colors.white,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        WSearch(
          isDark: true,
          hintText: '请输入文件名搜索',
          onSubmitted: (value) => cabinetStore.toSearchFile(value),
          onCancel: () => {
            cabinetStore.searchValue = null,
            cabinetStore.toSearchFile(null),
          },
        ),
      ],
    );
  }

  // 滚动目录内容区域
  _buildScrollFolderContent() {
    return WisCard(
      isSliver: true,
      margin: EdgeInsets.only(
        left: 15.pt,
        right: 15.pt,
      ),
      child: Column(
        children: [
          Wisdom.column(
              mainAxisSize: MainAxisSize.min,
              color: Colors.white,
              children: [
                Wisdom(
                  height: 10,
                  color: Colors.white,
                ),
                Wisdom.row(
                  padding: EdgeInsets.symmetric(horizontal: 15),
                  children: [
                    Wisdom(
                      margin: EdgeInsets.only(right: 10),
                      height: 15,
                      child: Image(image: AssetList.$jx_png_image),
                    ),
                    WisText(
                      '目录',
                      bold: true,
                    )
                  ],
                ),
              ]),
          _buildFolderList(),
          Wisdom(
            height: 10,
            color: Colors.white,
          )
        ],
      ),
    );
  }

  // 滚动文件内容区域
  _buildScrollFileContent() {
    return WisCard(
      margin: EdgeInsets.only(
        left: 15.pt,
        right: 15.pt,
      ),
      isSliver: true,
      child: Column(
        children: [
          Wisdom.column(color: Colors.white, children: [
            Wisdom(
              height: 10,
              color: Colors.white,
            ),
            Wisdom.row(
              padding: EdgeInsets.symmetric(horizontal: 15),
              children: [
                Wisdom(
                  margin: EdgeInsets.only(right: 10),
                  height: 15,
                  child: Image(image: AssetList.$jx_png_image),
                ),
                WisText(
                  '文件',
                  bold: true,
                  size: 15.0,
                )
              ],
            ),
          ]),
          _buildFileList(),
          Wisdom(
            height: 10,
            color: Colors.white,
          )
        ],
      ),
    );

    //   ],
    // );
  }

  // 无文件夹
  Widget _buildNullFolder() {
    return Wisdom.column(
      color: Colors.white,
      width: screenWidth,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Wisdom(
          margin: EdgeInsets.only(bottom: 20),
          width: screenWidth * 0.7,
          child: Image(image: AssetList.$kkry_png_image),
        ),
        if (cabinetStore.pathList.length > 0)
          WisText('当前目录为空')
        else ...<Widget>[
          WisText(
            '暂无目录信息',
            size: 16.0,
          ),
          SizedBox(
            height: 10,
          ),
          WisText(
            '点击左上角公司处可以切换公司',
            size: 14.0,
          ),
        ],
        // SizedBox(
        //   height: 10,
        // ),
      ],
    ).asExpanded();
  }

  // 文件夹列表
  Widget _buildFolderList() {
    return Column(
      children: [
        for (int i = 0; i < cabinetStore.treeList!.length; i++)
          Wisdom.column(
            mainAxisSize: MainAxisSize.min,
            onTap: () {
              cabinetStore.toOpenFloder(cabinetStore.treeList![i]);
            },
            // padding: EdgeInsets.only(bottom: 10),
            color: Colors.white,
            children: [
              Divider(height: 20),
              Wisdom.row(
                padding: EdgeInsets.symmetric(horizontal: 15),
                children: [
                  Wisdom(
                    height: 30,
                    margin: EdgeInsets.only(right: 10),
                    child: Image(image: AssetList.$wjj_icon_png_image),
                  ),
                  Wisdom.column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Wisdom(
                        width: MediaQuery.of(context).size.width * 0.8,
                        child: WisText(
                          '${cabinetStore.treeList![i].name ?? ''}',
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      WisText(
                        '${(cabinetStore.treeList![i].userSpace! / 1024).toStringAsFixed(2)}MB  ${cabinetStore.treeList![i].updateAt ?? ''}更新',
                        color: colorScheme.minor,
                      ),
                    ],
                  ).asFlexible(flex: 1),
                ],
              ),
            ],
          ),
      ],
    );
  }

  _toOpenSecretModel(row) {
    bool show = false;
    bool? truePwd = true;
    return showModalBottomSheet(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(10.pt),
            topRight: Radius.circular(10.pt),
          ),
        ),
        context: context,
        isScrollControlled: true,
        builder: (context) => StatefulBuilder(builder: (context, setState) {
              return AnimatedPadding(
                  padding: EdgeInsets.only(
                    bottom: MediaQuery.of(context).viewInsets.bottom, //软键盘高度
                  ),
                  duration: Duration(milliseconds: 100),
                  child: SafeArea(
                    child: Wisdom.column(
                        mainAxisSize: MainAxisSize.min,
                        padding: EdgeInsets.symmetric(horizontal: 10),
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Wisdom.row(
                            minHeight: 30.pt,
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: <Widget>[
                              Wisdom(
                                width: 100.pt,
                                alignment: Alignment.centerRight,
                                child: CloseButton(
                                  onPressed: () {
                                    truePwd = true;
                                    cabinetStore.closeModal(context);
                                  },
                                ),
                              ),
                            ],
                          ),
                          ConstrainedBox(
                              constraints: BoxConstraints(
                                maxHeight: 225,
                                minHeight: 100,
                              ),
                              child: Wisdom.column(
                                children: [
                                  Wisdom.row(
                                    children: [
                                      Image(
                                        image: AssetList.$js_icon_png_image,
                                        height: 20,
                                      ),
                                      SizedBox(width: 10),
                                      WisText(
                                        '机密文件',
                                        size: 16.0,
                                        bold: true,
                                      ),
                                    ],
                                  ),
                                  SizedBox(
                                    height: 15,
                                  ),
                                  WisText(
                                    '该文件属于机密文件，请输入登录密码查看。',
                                    size: 16.0,
                                  ),
                                  Wisdom(
                                    margin: EdgeInsets.symmetric(vertical: 15),
                                    child: TextFormField(
                                      onChanged: (v) {
                                        setState(() {
                                          cabinetStore.pwd = v;
                                        });
                                      },
                                      obscureText: !show,
                                      decoration: InputDecoration(
                                        hintText: '请输入账号登录密码',
                                        contentPadding: EdgeInsets.all(10.pt),
                                        isDense: true,
                                        fillColor: Color(0xE6E6E6FF),
                                        filled: false,
                                        suffix: Wisdom(
                                          onTap: () {
                                            setState(() {
                                              show = !show;
                                            });
                                          },
                                          child: Icon(
                                            FaIcons.eye,
                                            size: 15.pt,
                                            color: show
                                                ? colorScheme.primary
                                                : Colors.black38,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                  if (!truePwd!)
                                    Wisdom(
                                      alignment: Alignment.centerLeft,
                                      child: WisText(
                                        '密码错误',
                                        color: Color(0XFFFF495E),
                                        size: 14.0,
                                      ),
                                    ),
                                  Wisdom.row(
                                    children: [
                                      WButton(
                                        onPressed: () =>
                                            cabinetStore.closeModal(context),
                                        child: WisText('取消'),
                                        color: Color(0xFFF2F2F2),
                                      ),
                                      SizedBox(
                                        width: 5,
                                      ),
                                      Opacity(
                                        opacity:
                                            (cabinetStore.pwd?.length ?? 0) > 0
                                                ? 1
                                                : 0.3,
                                        child: WButton(
                                          onPressed: () async {
                                            if (cabinetStore.pwd == null ||
                                                cabinetStore.pwd == '') {
                                              return;
                                            }
                                            await CabinetServiceImp()
                                                .postCabinetPwdMatch({
                                              'origPsw': cabinetStore.pwd
                                            }).then((res) {
                                              setState(() {
                                                truePwd = res['data'];
                                              });
                                              if (truePwd!) {
                                                cabinetStore.pwd = '';
                                                cabinetStore
                                                    .closeModal(context);
                                                cabinetStore.routeToPreview(
                                                  baseUrl +
                                                      'serve/cabinetFile/preview/' +
                                                      row.id,
                                                  row.name + '.' + row.type,
                                                );
                                              }
                                            });
                                          },
                                          child: WisText('确认'),
                                        ),
                                      ).asExpanded()
                                    ],
                                  )
                                ],
                              )),
                        ]),
                  ));
            }));
  }

  final String baseUrl = APPConfig.baseURL;
  // 文件列表
  Widget _buildFileList() {
    return Column(children: [
      for (var i = 0; i < cabinetStore.fileList!.length; i++)
        Wisdom.column(
          color: Colors.white,
          children: [
            Divider(height: 20),
            Wisdom.row(
              padding: EdgeInsets.symmetric(horizontal: 15),
              onTap: () {
                var type = _getType(cabinetStore.fileList![i].type);
                if (cabinetStore.fileList![i].secretLevel == 'secret') {
                  return _toOpenSecretModel(cabinetStore.fileList![i]);
                } else {
                  if (type == 'image') {
                    cabinetStore.onShowImage(cabinetStore.fileList![i].id);
                  } else if (type == 'ppt' ||
                      type == 'pdf' ||
                      type == 'word' ||
                      type == 'excel') {
                    cabinetStore.routeToPreview(
                      baseUrl +
                          'serve/cabinetFile/preview/' +
                          cabinetStore.fileList![i].id!,
                      cabinetStore.fileList![i].name! +
                          '.' +
                          cabinetStore.fileList![i].type!,
                    );
                  } else {
                    _buildDialogModal(context);
                  }
                }
              },
              children: [
                Wisdom(
                  height: 28,
                  margin: EdgeInsets.only(right: 10),
                  child:
                      Image(image: _fileType(cabinetStore.fileList![i].type)),
                ),
                Wisdom.column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Wisdom.row(
                      children: [
                        if (cabinetStore.fileList![i].secretLevel == 'secret')
                          WTag(
                            child: WisText(
                              '机密',
                              size: 12.pt,
                            ),
                            color: Color(0XFFFF495E),
                          ),
                        Wisdom(
                          width: MediaQuery.of(context).size.width * 0.7,
                          child: WisText(
                            '${cabinetStore.fileList![i].name ?? ''}',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            size: 15.0,
                          ),
                        ),
                      ],
                    ),
                    WisText(
                      '${(cabinetStore.fileList![i].size! / 1024).toStringAsFixed(2)}MB  ${cabinetStore.fileList![i].createAt ?? ''} ${cabinetStore.fileList![i].createByName ?? ''}上传 ',
                      color: colorScheme.minor,
                      size: 13.0,
                    ),
                  ],
                )
              ],
            ),
          ],
        )
    ]);
  }

  _fileType(type) {
    type = _getType(type);
    switch (type) {
      case 'pdf':
        return AssetList.$pdf_icon_png_image;

      case 'ppt':
        return AssetList.$ppt_icon_png_image;

      case 'image':
        return AssetList.$pt_icon_png_image;

      case 'exe':
        return AssetList.$exe_png_image;

      case 'word':
        return AssetList.$w_icon_png_image;

      case 'excel':
        return AssetList.$x_icon_png_image;

      case 'zip':
        return AssetList.$ys_icon_png_image;

      case 'video':
        return AssetList.$v_icon_png_image;

      case 'other':
        return AssetList.$qtwj_png_image;
    }
  }

  _getType(type) {
    // 获取类型结果
    var result = '';
    // 图片格式
    var imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif'];
    // 进行图片匹配
    if (imglist.indexOf(type) != -1) {
      result = 'image';
      return result;
    }

    // 匹配 excel
    var excelist = ['xls', 'xlsx'];
    if (excelist.indexOf(type) != -1) {
      result = 'excel';
      return result;
    }

    // 匹配 word
    var wordlist = ['doc', 'docx'];
    if (wordlist.indexOf(type) != -1) {
      result = 'word';
      return result;
    }

    // 匹配 pdf
    var pdflist = ['pdf'];
    if (pdflist.indexOf(type) != -1) {
      result = 'pdf';
      return result;
    }

    // 匹配 ppt
    var pptlist = ['ppt', 'pptx'];
    if (pptlist.indexOf(type) != -1) {
      result = 'ppt';
      return result;
    }

    // 匹配 视频
    var videolist = ['mp4', 'm2v', 'mkv'];
    if (videolist.indexOf(type) != -1) {
      result = 'video';
      return result;
    }

    // 匹配 压缩包
    var ziplist = ['zip', 'rar'];
    if (ziplist.indexOf(type) != -1) {
      result = 'zip';
      return result;
    }

    // 匹配 exe
    var exelist = ['exe'];
    if (exelist.indexOf(type) != -1) {
      result = 'exe';
      return result;
    }
    // 其他 文件类型
    result = 'other';
    return result;
  }

  _buildDialogModal(BuildContext context) {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (context) {
        return Center(
            child: Container(
          height: 200.pt,
          width: 307.pt,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(3.pt),
          ),
          child: Wisdom.column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Center(
                child: Container(
                  padding: EdgeInsets.only(top: 20.pt),
                  child: Text(
                    '无法预览',
                    style: TextStyle(
                        fontSize: 18.pt,
                        color: Colors.black,
                        fontWeight: FontWeight.normal,
                        decoration: TextDecoration.none),
                  ),
                ),
              ),
              Wisdom(
                padding: EdgeInsets.symmetric(horizontal: 20),
                child: Text(
                  '该类型文件不支持在手机端预览，请在电脑端下载查看',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 16.pt,
                      color: colorScheme.minor,
                      fontWeight: FontWeight.normal,
                      decoration: TextDecoration.none),
                ),
              ),
              WButton(
                margin: EdgeInsets.only(bottom: 10),
                onPressed: () {
                  Navigator.pop(context);
                },
                child: WisText('我知道了'),
              ),
            ],
          ),
        ));
      },
    );
  }
}
