/*
 * @Author: XianKaiQun
 * @Date: 2020-09-11 09:34:52
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-09-20 12:31:33
 * @Description: 
 */
import 'package:app_package/app_package.dart';
import 'package:dynamic_package/src/models/dynamic_item.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:dynamic_package/src/api/api.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

import '../models/dynamic_detail.dart';

class DetailStore extends GetxController {
  var item = DynamicItemModel().obs;
  var detail = DynamicDetailModel().obs;
  final scrollViewKey = GlobalKey<WisScrollViewState>();
  var photosProvider = <ImageProvider>[].obs;
  var content = ''.obs;
  getDetail() async {
    item.value = Get.arguments['item'];
    var _urls =
        (item.value.url ?? '') == '' ? <String>[] : item.value.url!.split(',');

    var res = await DynamicServiceImpl()
        .getDynamicDetail({'id': Get.arguments['id']});
    detail.value = res.data ?? DynamicDetailModel();

    var _content = (res.data?.detailContent ?? '')
        .replaceAllMapped(RegExp(r'<img src="/\w+/'), (match) {
      return '<img width="100%" src="${APPConfig.baseURL}';
    });
    content.value =
        _content.replaceAllMapped(RegExp(r'&nbsp;'), (match) => ' ');

    ///图片
    photosProvider.value = _urls.map((e) {
      return CachedNetworkImageProvider(AppParseUtil.image(e));
    }).toList();
  }

  var className = '--'.obs;

  /// 获取类型列表
  Future onGetClassList() async {
    var _item = Get.arguments['item'];
    var res = await DynamicServiceImpl().getClassIdList();

    res.data?.forEach((item) {
          if (_item.classId == item.id)
            {
              className.value = item.name ?? '--';
            };
        });
  }

  /// 预览文件
  route2perview(url, name) {
    WisPreviewUtil.show(
      url: url,
      name: name,
    );
  }

  final List<String> fileArr = [
    'pdf',
    'docx',
    'xlsx',
    'xls',
    'doc',
    'pptx',
    'ppt'
  ];

  /// 是否支持查看文件类型
  isPreviewType(type) {
    if (fileArr.indexWhere((element) =>
            element == type.substring(type.lastIndexOf('.') + 1)) !=
        -1) {
      return true;
    } else {
      return false;
    }
  }

  /// 域名前缀
  final String baseUrl = APPConfig.baseURL;

  /// 点击附件
  viewFile(itemData) async {
    final String baseUrl = APPConfig.baseURL;
    const fileTypes = [
      'pdf',
      'doc',
      'docx',
      'xls',
      'xlsx',
      'pptx',
      'ppt',
    ];
    if (fileTypes.contains(itemData.fileSuffix)) {
      route2perview(
        baseUrl + 'file/download/' + itemData.fileId,
        itemData?.fileName,
      );
    } else {
      onShowImage(itemData.fileId);
    }
  }

  /// 附件点击查看
  onHandleFile(file) {
    /// 非图片
    if (file['type'].indexOf('image') == -1) {
      if (isPreviewType(file['name'])) {
        route2perview(
          baseUrl + 'file/download/' + file['id'],
          file['name'],
        );
      } else {
        WToastUtil.show('暂不支持此类文件预览，请使用电脑下载查看。');
      }

      /// 图片
    } else {
      onShowImage(file['id']);
    }
  }

  void onShowImage(image) async {
    List<ImageProvider> images = [];
    images.add(CachedNetworkImageProvider(AppParseUtil.image(image)));
    WisPhotoViewUtil.show(images, 0);
  }
}
