/*
 * @Author: WuXiangNan
 * @Date: 2021-06-21 15:24:44
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-05-18 15:47:53
 * @Description: 
 */

import 'package:app_package/app_package.dart';
import 'package:cabinet_package/src/models/auth_company.dart';
import 'package:cabinet_package/src/models/directory_list.dart';
import 'package:cabinet_package/src/models/file_list.dart';
import 'package:cabinet_package/src/service/imp/cabinet_service_imp.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:dio/dio.dart';

class CabinetStore with ChangeNotifier {
  final BuildContext context;
  late Map args;
  WisWatarMarkInstance instance = WisWatarMarkInstance();
  CabinetStore(this.context) {
    args =
        ModalRoute.of(context)!.settings.arguments as Map<dynamic, dynamic>? ??
            {};
    // 去除缓存上次选中的公司id
    stageCompanyId =
        WisStorageUtil.get(key: 'cabinetSelectedCompany').toString();
    toGetData();
  }

  String directoryPath = '';

  String? pwd = '';

  String? searchValue;

  String? stageCompanyId;

  List<DirectoryList>? treeList = [];

  List<FileList>? fileList = [];

  List<DirectoryList> pathList = [];

  final fileScorllViewKey = GlobalKey<WisScrollViewState>();

  // 公司列表
  List<AuthCompany>? companyList = [];

  // 选择公司
  AuthCompany? selectedCompany;

  //当前员工的信息
  EmployeesInfoModel? get userInfo => GetIt.I.get<AuthGlobalStore>().info;

  // 操作类型
  String operatorType = '';

  bool notNull = true;

  toGetData() async {
    await toGetCompanyList();
    onInit();
  }

  onInit() {
    if (pathList.length == 0) {
      toGetCabinetDirectoryList(true, null);
    } else {
      toGetCabinetDirectoryList(false, pathList[pathList.length - 1].id);
    }
  }

  onRefresh() {
    if (pathList.length == 0) {
      toGetCabinetDirectoryList(true, null);
    } else {
      toGetCabinetDirectoryList(false, pathList[pathList.length - 1].id);
      toGetCabinetFileList();
    }
  }

  Map<String, dynamic> folderParams = {
    'pageNum': 1,
    'pageSize': 20,
    'isPage': false,
  };

  Map<String, dynamic> fileParams = {
    'pageNum': 1,
    'pageSize': 20,
    'isPage': true,
  };

  // 获取目录列表
  Future toGetCabinetDirectoryList(isFirstLevel, parentId,
      {bool isLoad = false}) async {
    notNull = true;
    operatorType = '';
    WLoadingUtil.show(bg: false);
    var res = await CabinetServiceImp().getCabinetDrectoryList({
      'isFirstLevel': isFirstLevel,
      'parentId': parentId,
      'companyId': selectedCompany!.code,
      'isPage': false,
    });
    WLoadingUtil.hide();
    treeList = res.data!.list;
    notNull = treeList!.length > 0 || fileList!.length > 0;
    notifyListeners();
  }

  bool unHadAuth = false;

  // 获取文件列表
  Future toGetCabinetFileList({bool isLoad = false}) async {
    notNull = true;
    operatorType = '';
    if (!isLoad) {
      fileParams['pageNum'] = 1;
      fileList = [];
    }
    var res = await CabinetServiceImp().getCabinetFileList({
      'cabinetDirectoryId': pathList[pathList.length - 1].id ?? null,
      ...fileParams
    });
    if (res.responseJSON.code == '403' && (treeList?.length ?? 0) == 0) {
      unHadAuth = true;
      notifyListeners();
      return;
    }

    var _data = res.data;
    final _list = _data?.list ?? [];
    notNull = treeList!.length > 0 || _list.length > 0;
    if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      fileScorllViewKey.currentState?.isLast();
    } else {
      fileParams['pageNum']++;
    }
    _list.forEach((item) {
      fileList!.forEach((item2) {
        if (item.name == item2.name) _list.remove(item);
      });
    });
    isLoad ? fileList!.addAll(_list) : fileList = _list;
    notifyListeners();
  }

  // 进入文件夹下级
  toOpenFloder(data) async {
    notNull = true;
    pathList.add(data);
    getPath(pathList);
    WLoadingUtil.show(bg: false);
    operatorType = '';
    await toGetCabinetDirectoryList(false, data.id);
    await toGetCabinetFileList();
    WLoadingUtil.hide();
    notifyListeners();
  }

  // 返回上级目录
  toUpLevel() async {
    notNull = true;
    unHadAuth = false;
    operatorType = '';
    pathList.removeAt(pathList.length - 1);
    if (pathList.length > 0) {
      await toGetCabinetDirectoryList(false, pathList[pathList.length - 1].id);
      await toGetCabinetFileList();
    } else {
      await toGetCabinetDirectoryList(true, null);
      fileList = [];
    }
    getPath(pathList);
  }

  // 构建文件夹路径
  getPath(list) {
    var path = [];
    list.forEach((item) {
      path.add(item.name);
    });
    if (path.length < 5) {
      directoryPath = '\\';
      directoryPath = directoryPath + path.join('\\');
    } else {
      directoryPath = '...\\';
      directoryPath = directoryPath +
          path.getRange(path.length - 4, path.length).join('\\');
    }
  }

  // 获取公司列表
  toGetCompanyList() async {
    var res = await CabinetServiceImp().getCabinetauthCompanyDict();
    companyList = res.data ?? [];
    companyList!.forEach((item) {
      if (item.code == stageCompanyId) {
        selectedCompany = item;
      }
    });
    if (selectedCompany == null) selectedCompany = companyList![0];
    notifyListeners();
  }

  Future<List<AuthCompany>?> getCompanyList() async => companyList;

  // 选择公司弹窗
  toOpenBottomModal() async {
    final res = await WPickerUtil.single<AuthCompany>(
      context,
      title: Text('选择公司'),
      getData: (() => getCompanyList().then((value) => value!)),
      initialValue: AuthCompany(code: selectedCompany!.code),
    );
    if (res != null) {
      selectedCompany = res;
      WisStorageUtil.set(
          key: 'cabinetSelectedCompany', data: selectedCompany!.code);
      toGetCabinetDirectoryList(true, null);
      notifyListeners();
    }
  }

  // 校验机密文件密码
  Future comparePwd() async {
    if (pwd == null || pwd == '') {
      return;
    }
    await CabinetServiceImp().postCabinetPwdMatch({'origPsw': pwd}).then((res) {
      return res['data'];
    });
  }

  // 关闭校验机密文件密码窗口
  closeModal(context) {
    pwd = null;
    Navigator.pop(context);
  }

  // 文件搜索
  toSearchFile(value) async {
    operatorType = 'filter';
    if (value != null && value != '') {
      treeList = [];
      var res = await CabinetServiceImp().getCabinetFileList({
        'isPage': true,
        'pageNum': 1,
        'pageSize': 20,
        'name': value,
        'companyId': selectedCompany!.code
      });
      fileList = res.data!.list;
      notNull = treeList!.length > 0 || fileList!.length > 0;
      notifyListeners();
    } else {
      this.toGetCabinetDirectoryList(false, pathList[pathList.length - 1].id);
      this.toGetCabinetFileList();
    }
  }

  // 目录搜索
  toSearchFolder(value) async {
    operatorType = 'filter';
    if (value == null || value == '') {
      this.toGetCabinetDirectoryList(true, null);
    } else {
      var list = [];
      treeList!.forEach((item) {
        list.add(item);
      });
      treeList = [];
      list.forEach((item) {
        if (item.name.contains(value)) {
          treeList!.add(item);
        }
      });
      notNull = treeList!.length > 0 || fileList!.length > 0;
      notifyListeners();
    }
  }

  // 预览文件
  routeToPreview(url, name) async {
    // 添加水印
    instance.addWatermark(
        context,
        userInfo!.name! +
            userInfo!.phone!.substring(userInfo!.phone!.length - 4));

    await WisPreviewUtil.show(
        url: url,
        name: name,
        options: Options(headers: {'Cookie': CookieUtil.instance.value}));
    // 去除水印
    instance.removeWatermark();
  }

  /// 预览详情图片
  void onShowImage(image) async {
    // 添加水印
    instance.addWatermark(
        context,
        userInfo!.name! +
            userInfo!.phone!.substring(userInfo!.phone!.length - 4));
    List<ImageProvider> images = [];
    images.add(CachedNetworkImageProvider(
        '${APPConfig.baseURL}serve/cabinetFile/preview/$image',
        headers: {'Cookie': CookieUtil.instance.value ?? ''}));
    await WisPhotoViewUtil.show(images, 0);
    // 去除水印
    instance.removeWatermark();
  }
}
