import 'dart:io';

import 'package:base/consts/external_assets_package_key.dart';
import 'package:base/utils/flutter_toast.dart';
import 'package:base/utils/http.dart';
import 'package:base/widgets/loading_dialog.dart';
import 'package:flutter/material.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:progress_dialog/progress_dialog.dart';

import '../../model/vehicle_basic_model.dart';

class TechnicalPage extends StatefulWidget {
  BasicBean baseBean;
  final String type; //1为装备 3为车辆
  //技术文档
  TechnicalPage(this.baseBean, this.type);

  @override
  _TechnicalPageState createState() {
    return _TechnicalPageState();
  }
}

class _TechnicalPageState extends State<TechnicalPage> {
  List<Instruction> basicList = [];

  @override
  void initState() {
    basicList = widget.type == '3' ? widget.baseBean.instruction : widget.baseBean.excel;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () {
          Navigator.of(context).pop();
        },
        child: Material(
            color: const Color(0xfff5f5f5),
            child: SingleChildScrollView(
              padding: const EdgeInsets.only(left: 10, right: 10, top: 15, bottom: 40),
              child: ListView.builder(
                  physics: const NeverScrollableScrollPhysics(),
                  key: const PageStorageKey('data'),
                  itemCount: basicList != null ? basicList.length : 0,
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, int index) => ListItemView(index, basicList[index])),
            )));
  }
}

class ListItemView extends StatelessWidget {
  ProgressDialog pr;

  ListItemView(this.row, this.bean, {Key key}) : super(key: key);
  int row;
  Instruction bean;
  bool _saving = false;

  String getImageStringName() {
    //根据文件类型判断图标
    String image = 'assets/images/icon_default.png';
    if (bean.name.contains('.doc')) {
      image = 'assets/images/word.png';
    } else if (bean.name.contains('.pdf')) {
      image = 'assets/images/pdf.png';
    } else if (bean.name.contains('.xls')) {
      image = 'assets/images/excel.png';
    }

    return image;
  }

  //String appName = bean.name;

  //EmergencyBean bean;
  @override
  Widget build(BuildContext context) {
    pr = ProgressDialog(
      context,
      type: ProgressDialogType.Download,
      isDismissible: false,
      showLogs: true,
    );
    return Container(
        alignment: Alignment.centerLeft,
        height: 50,
        padding: const EdgeInsets.all(10),
        margin: const EdgeInsets.only(top: 10),
        //设置圆角
        decoration: BoxDecoration(
          //背景
          color: Colors.white,
          //设置四周圆角 角度
          borderRadius: const BorderRadius.all(Radius.circular(5.0)),
          //设置四周边框
          border: Border.all(width: 1, color: Colors.white),
        ),
        child: Row(
          children: [
            Image.asset(
              getImageStringName(),
              width: 14,
              height: 14,
            ),
            Container(
                width: MediaQuery.of(context).size.width - 100,
                margin: const EdgeInsets.only(left: 10, right: 10),
                child: Text(
                  bean.name ?? '',
                  style: const TextStyle(fontSize: 12, color: Color(0xff333333)),
                  textAlign: TextAlign.left,
                  overflow: TextOverflow.ellipsis,
                )),
            Expanded(
              child: IconButton(
                  alignment: Alignment.centerRight,
                  icon: Image.asset(
                    'assets/images/down.png',
                    package: ExternalAssetsPackageKey.BASE,
                    width: 12,
                    height: 12,
                  ),
                  onPressed: () => showUpdate(
                        context,
                        bean.url,
                      )),
            )
          ],
        )

        // height:  getStringHeight(txtKey),
        );
  }

  showUpdate(BuildContext context, String url) async {
    await getDownload(context, url);
  }

  void getDownload(BuildContext context, String url) async {
    showDialog(
        context: context,
        builder: (ctx) {
          return LoadingDialog(
            barrierDismissible: true,
          );
        });
    //存放路径
    final path = await _apkLocalPath;

    File file = File(path + '/' + bean.name);
    if (await file.exists()) await file.delete();

    HttpManager().download(
        url: url,
        savePath: file.path,
        onReceiveProgress: (int count, int total) {},
        successCallback: (data) {
          Navigator.of(context).pop();
          install();
        },
        errorCallback: (data) {
          Navigator.of(context).pop();
          FlutterToast.toastCenter(data.message);
        },
        tag: null);
  }

  //下载结束打开文件
  Future<Null> install() async {
    String path = await _apkLocalPath;
    OpenFile.open(path + '/' + bean.name).then((value) {
      if (value.message != 'done') {
        FlutterToast.toastCenter(value.message);
      }
    });
  }

  Future<String> get _apkLocalPath async {
    final directory = await getExternalStorageDirectories(type: StorageDirectory.downloads);
    return directory[0].path;
  }
}
