import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:ext_storage/ext_storage.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import 'package:mwf_app/service/notification_firebase.dart';
import 'package:mwf_app/model/customer_Info.dart';
import 'package:mwf_app/model/customer_list_model.dart';
import 'package:mwf_app/service/notification_count.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/alert.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/header.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/pref.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/model/chat_detail.dart';
import 'package:mwf_app/model/chat_detail_send.dart';
import 'package:mwf_app/set7/chat_home.dart';
import 'package:mwf_app/set7/received_message.dart';
import 'package:mwf_app/set7/sended_message.dart';
import 'package:need_resume/need_resume.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';

class ChatPages extends StatefulWidget {
  final String roomType;
  final String customerId;
  final String id;
  final String roomName;
  final String masterId;
  
  const ChatPages({
    this.customerId,
    this.id,
    this.roomName,
    this.roomType,
    this.masterId,
  });
  @override
  _ChatPagesState createState() => _ChatPagesState();
}

class _ChatPagesState extends ResumableState<ChatPages> {
  TextEditingController _text = TextEditingController();
  TextEditingController _dataBase64Img = TextEditingController();
  TextEditingController _dataBase64File = TextEditingController();
  TextEditingController _selectImage = TextEditingController();
  TextEditingController _selectDoc = TextEditingController();
  TextEditingController _filename = TextEditingController();
  TextEditingController description = TextEditingController();

  ScrollController _scrollController = ScrollController(
    initialScrollOffset: 100
  );
  StreamController<dynamic> streamController;
  
  int filesize = 0;
  String fullname;
  bool urlReady = true;
  bool firstTime = true;
  bool downloadSuccess = false;  

  List <Widget> listText = []; // Test stream
  List <Widget> listTemp = []; // Test stream
  List<Widget> chatList = [];

  var page = 1;
  var _totalPage = 0;
  var currentPage = "chatpage";
  
  int sum = 0;
  int countItem = 1;
  String roomType = '';
  String customerid = "";
  String customerDepart = "";

  static String roomName = '';
  static String masterId = '';

  double numberOfItems = 0.0;
  double minItemHeight = 60.0;
  double maxItemHeight = 150.0;
  
  final scrollDuration = Duration(seconds: 2);
  final ItemScrollController itemScrollController = ItemScrollController();
  final ItemPositionsListener itemPositionsListener = ItemPositionsListener.create();
  
  _scrollToBottom(leng) async {
    itemScrollController.jumpTo(index: leng+1);
  }

  @override
  void onReady() async {    
    itemPositionsListener.itemPositions.addListener(scrollListener);
    super.onReady();
    setInitChat();
    setStream();
    loadData();
    initFirebaseMessaging();
    
  }
  void scrollListener(){
    // final visibleIndexes = itemPositionsListener.itemPositions.value
    //     .toList()
    //     .map((itemPosition) => itemPosition.index);
    if(itemPositionsListener.itemPositions.value.isNotEmpty){
      final visibleIndexes = itemPositionsListener.itemPositions.value.toList()
        .map((itemPosition) => itemPosition.index).first+2;
    }
    //if(visibleIndexes.length > 0)
      // setState(() {
      //   len = visibleIndexes.last;
      // });
    
    // if(visibleIndexes.length > 0){
    //   print("visitbility : " + visibleIndexes.toString());
    // }
    //print('現在表示中アイテムのindexは $visibleIndexes');
    // if(visibleIndexes.length > 0){
    //   print(visibleIndexes.last.toString());
    //   len = visibleIndexes.last;
    // }
    
    // if(_scrollController.position.pixels == _scrollController.position.minScrollExtent){
    //     page = page+1;
    //     //loadDataAppend();
    //     //testAppend();
    //     print("loading more... " + page.toString());
    // }
  }

  @override
  void onResume() async {
    super.onResume(); 
    print("On resume");
    setInitChat();
    setStream();
    loadData();
  }

  //  Future<dynamic> testAppend() async {
  //     listTemp.insertAll(0,[Text('1test'), Text('2test'), Text('3test'),]); // แทนข้อมูลที่ดึงมาใหม่
  //     listText.insertAll(0,listTemp);
  //     print(listText);
  //     for(var lists in listText){
  //       streamController.add(lists);
  //     }
  //     listText.clear();
  //     listTemp.clear();
  //  }

   setInitChat(){
    roomName = widget.roomName;
    customerid = widget.customerId;
    roomType = widget.roomType;
    masterId = widget.masterId;      
    //task();
    getCustomerInfo(customerid);
    setDepartName();
    print("Room : " + roomName);
    print("Chat Room Id  : " + widget.id);
    print("Master Id :  " + masterId);
    print(AppStrings.profileFullName);
    print(" CA :: " + AppUrl.CA.toString());
    print(" CustomerID :: " + AppUrl.CustomerID.toString()); 
   }

  @override
  void dispose() {
    print("-------Dispose--------");
    IsolateNameServer.removePortNameMapping('downloading');
    _scrollController.removeListener(scrollListener);
    _scrollController.dispose();
    streamController?.close();
    streamController = null;
    page = 1;
    super.dispose();
  }

  Future getCustomerInfo(customerid) async {
    String seleCustomer = "";
    if(roomType == "individual"){
      var customerInfo = await CustomerInfo.getData();
      print(customerid);
      var detail = await CustomerList.getCustomerHead(customerid);
      print(detail);
      var selecCutomer = await CustomerList.getData();
      selecCutomer.forEach((v) async {
        final customer = CustomerList.fromJson(v);
        if(customer.customerId == customerid){
          seleCustomer = customer.customerSaleInfoId;
        }
      });
      
      if(detail != null || customerInfo != null){
        AppUrl.tsicid =  detail[0]['TSICID'].toString();
        AppUrl.branchId = detail[0]['BranchID'].toString();
        AppUrl.customerSeleInfo = seleCustomer.toString();
        AppUrl.customerAddress = customerInfo['CustomerAddress'].toString();
      }
    }
  }

  void initFirebaseMessaging() async {
    FirebaseMessaging firebaseMessaging = FirebaseMessaging();
    await ManageNotify.subScribesNotifyTopic(firebaseMessaging);
    // firebaseMessaging.subscribeToTopic("pea_notification").whenComplete(()=> print("Everything of pea_notification Okay.."));
    // firebaseMessaging.subscribeToTopic("fb0593bf-bee9-4350-845f-9aad236f7186").whenComplete(()=> print("Everything of group Okay.."));
    // firebaseMessaging.subscribeToTopic(masterId).whenComplete(()=> print("Everything of $masterId Okay.."));
    firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
        await handleMessageChat(message);
      },
      onBackgroundMessage: backgrounfHandler,
      onLaunch: (Map<String, dynamic> message) async {
        bool status = NotificationCount.getPrefBool("isLaunch") == null ? true : NotificationCount.getPrefBool("isLaunch");
        if(status == false){
          if(message.containsKey("data")){
            await ManageNotify.manageOnLaunch(message);
          }
        }
      },
      onResume: (Map<String, dynamic> message) async {
        if(message.containsKey("data")){
            NotificationCount.getCount();
            FirebaseNotificationModel datas = FirebaseNotificationModel.fromJson(message['data']);
            var receivedData = await ManageNotify.getDataNoti(datas);
            FirebaseNotificationModel data = FirebaseNotificationModel.fromJson(jsonDecode(receivedData));
            await ManageNotify.selectNotifyOnResume(data);
            message.clear();
          }
      },
    );

    firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, badge: true, alert: true));

    firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    });

    firebaseMessaging.getToken().then((String token) {
      assert(token != null);
      print("Token : $token");
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state){
    if(state == AppLifecycleState.inactive){
      setPref('bool', "isAppOpen", false);
      setPref('bool', "isLaunch", false);
    }
    print(state);
  }

  setDepartName(){
    if(widget.id == "32FB032C-7F6C-4BD2-ACB7-54817EDB8CEC"){
      customerDepart = roomName;
    }else{
      customerDepart = "";
    }
  }

  handleMessageChat(message) async {
    print("Handle chat");
    print(message);
    if(message.isNotEmpty){
      if(message.containsKey("data") && message.containsKey("notification")){
        FirebaseNotificationModel data = FirebaseNotificationModel.fromJson(message['data']);
        String type = data.notiType.toString().toLowerCase();
        String check = data.isGroupChat ? data.chatMasterId.toLowerCase() : data.ca;
        String myid = data.isGroupChat ? masterId : AppUrl.CA;

        if(type == "chat" && (myid == check && masterId == data.chatMasterId.toLowerCase())){
          String msg = data.body;
          String accountid = data.accountId;
          String time = data.time.length > 5 ? data.time.substring(0,5) : data.time;
 
          print("this is chat datxa :: " + msg);
          print("User id :: " + AppUrl.userID);
          print("Account id :: " + accountid.toString());
          if(data.type != "3"){
            if(accountid == AppUrl.userID){
              streamController.add(
                SendedMessage(
                  time: time,
                  filename: "",
                  readCount: 0,
                  msgType: data.type,
                  content: data.body,
                  msgId: data.mwfNotiTypeId,
                  fullname: data.chatFullname,
                  url: ChatDetail.getFile(data.mwfNotiTypeId),
                )
              ); 
            }else if( accountid !=  AppUrl.userID){
              streamController.add(
                ReceivedMessage(
                  time: time,
                  filename: "",
                  msgType: data.type,
                  content: data.body,
                  department: data.title,
                  fullname: data.chatFullname,
                  url: ChatDetail.getFile(data.mwfNotiTypeId),
                )
              );
              int storeCount = 0;
              if(data.isGroupChat){
                storeCount = NotificationCount.getCounts(masterId+"_store");
                setPref('int', masterId, 0);
                setPref('int', masterId+"_store", storeCount+1);
              }else{
                storeCount = NotificationCount.getCounts(data.ca+"_store");
                setPref('int', data.ca, 0);
                setPref('int', data.ca+"_store", storeCount+1);
              }
            }
            itemScrollController.scrollTo(
              index: countItem, 
              duration: Duration(milliseconds: 10),
              curve: Curves.easeInOutCubic
            );
          }else if(data.type == "3"){
            await loadWidgetFile();
          }
        }else{
          ManageNotify.showNotify(message);
          NotificationCount.handleCountChat(message);
          NotificationCount.setCount("chat");
          await NotificationCount.getNumberFromCustomer(context);
          //NotificationCount.handleCountChatNotify(message);
        }
      }
    }
  }

  int diffInDays(DateTime date1, DateTime date2) {
    return ((date1.difference(date2) -
                    Duration(hours: date1.hour) +
                    Duration(hours: date2.hour))
                .inHours /
            24)
        .round();
  }

  setStream() async {
    streamController = StreamController.broadcast();
    streamController.stream.listen((widgets) => setState(() {
        listText.add(widgets);
        countItem = countItem+1;
      })
    );
  }

  loadWidgetFile() async {
    ChatDetail.data.clear();
    final lists = await ChatDetail.getData(widget.id,'');
    var list = lists[0];
    var data = ChatDetail.fromJson(list);
    
      if (data.accountId != AppUrl.userID){
        streamController.add(
          ReceivedMessage(
            time: data.time,
            department: data.userRead[0].customerName,
            content: data.content,
            filename: data.fileName,
            msgType: data.type.toString(),
            url: ChatDetail.getFile(data.id),
            fullname: data.userRead[0].firstname + " " + 
              data.userRead[0].lastname,
          )
        );
      }else if(data.accountId == AppUrl.userID){
        streamController.add(
          SendedMessage(
            msgId: data.id,
            time:  data.time,
            content: data.content, 
            filename: data.fileName,
            readCount: data.readcnt,
            msgType: data.type.toString(),
            url: ChatDetail.getFile(data.id),
            fullname: data.userRead[0].firstname+" "+
                      data.userRead[0].lastname,
          )
        );
      }
      itemScrollController.scrollTo(
        index: countItem, 
        duration: Duration(milliseconds: 10),
        curve: Curves.easeInOutCubic
      );
  }

  showSuccess(){
    setState(() {
      AppLoader.showSuccess("บันทึกสำเร็จ");
    });
  }
  
  // Future<void> loadDataAppend() async {
  //   List<Widget> chatAppend = [];
  //   DateTime lastChatDate = DateTime.now();
  //   if(page <= _totalPage){
  //     try {
  //       final list = await ChatDetail.getData(widget.id, page); //
  //       setState(
  //         () {
  //           ChatDetail.data.clear();

  //           list.forEach((v) async {
  //             final chatDetailList = ChatDetail.fromJson(v);
  //             ChatDetail.data.add(chatDetailList); // loop เก็บข้อมูล
  //             //print(v);
  //           });
  //           print(ChatDetail.data.length);
  //           ChatDetail.data = ChatDetail.data.reversed.toList(); // order by desc
            
  //           for (int i = 0; i < ChatDetail.data.length; i++) {
  //             DateTime currentChatDate =
  //                 DateFormat('d/M/yyyy').parse(ChatDetail.data[i].createAt);
  //             int dateDiff = diffInDays(currentChatDate, lastChatDate);
  //             if (dateDiff.abs() > 0) {
  //               listTemp.add(
  //                 Align(
  //                   alignment: Alignment(0, 0),
  //                   child: Container(
  //                     margin: const EdgeInsets.only(top: 5.0),
  //                     height: 30,
  //                     width: 120,
  //                     decoration: BoxDecoration(
  //                       color: Color(0xffC7D3D8),
  //                       borderRadius: BorderRadius.all(
  //                         Radius.circular(8.0),
  //                       ),
  //                     ),
  //                     child: Center(
  //                       child: Text(
  //                         ChatDetail.data[i].createAt + " น.",
  //                         style: TextStyle(fontSize: 11, color: Colors.white),
  //                       ),
  //                     ),
  //                   ),
  //                 ),
  //               );
  //               lastChatDate = currentChatDate;
  //             }

  //             if (ChatDetail.data[i].accountId == AppUrl.userID){
  //               listText.add(
  //                 SendedMessage(
  //                   msgId: ChatDetail.data[i].id,
  //                   time:  ChatDetail.data[i].time,
  //                   content: ChatDetail.data[i].content, 
  //                   filename: ChatDetail.data[i].fileName,
  //                   readCount: ChatDetail.data[i].readcnt,
  //                   msgType: ChatDetail.data[i].type.toString(),
  //                   url: ChatDetail.getFile(ChatDetail.data[i].id),
  //                   fullname: ChatDetail.data[i].userRead[0].firstname+" "+
  //                             ChatDetail.data[i].userRead[0].lastname,
  //                 )
  //               );
  //             }

  //             if (ChatDetail.data[i].accountId != AppUrl.userID){
  //               listText.add(
  //                 ReceivedMessage(
  //                   department: roomName,
  //                   time:  ChatDetail.data[i].time,
  //                   content: ChatDetail.data[i].content, 
  //                   filename: ChatDetail.data[i].fileName,
  //                   msgType: ChatDetail.data[i].type.toString(),
  //                   url: ChatDetail.getFile(ChatDetail.data[i].id),
  //                   fullname: ChatDetail.data[i].userRead[0].firstname+" "+
  //                             ChatDetail.data[i].userRead[0].lastname,
  //                 )
  //               );
  //             }
  //           }
  //           //streamController.add(chatAppend.toList());
  //           //listText.insertAll(0, chatAppend.reversed.toList());
  //           //listText.insertAll(0, chatAppend.toList());
  //           //streamController.add(chatAppend);
  //           //listText.insertAll(0, chatAppend.toList());
  //           //streamController.add(listText);

          
  //           //listText.add(listTemp);
  //           print(listText);
  //           for(var lists in listText){
  //             streamController.add(lists);
  //           }
  //           listText.clear();
  //           listTemp.clear();
  //           print(_totalPage);
  //           print("Size of data ------------>  "  + listText.length.toString());
  //         },
  //       );
  //     } catch (e) {
  //       print(e);
  //     }
  //   }
    
  // }

  Future<void> loadData() async {
    AppLoader.show();
    DateTime lastChatDate = DateTime.now();
    try {
      int dataCount = 1;
      int countDiffday = 0;
      chatList.clear();

      ChatDetail.data.clear();
      final list = await ChatDetail.getData(widget.id, page);

      if(list.isNotEmpty){
        setState(() {

          if(_totalPage == 0){
            _totalPage = list[0]['TotalPage'];
          }
          list.forEach((v) async {
            final chatDetailList = ChatDetail.fromJson(v);
            ChatDetail.data.add(chatDetailList); // loop เก็บข้อมูล
          });
          ChatDetail.data = ChatDetail.data.reversed.toList(); // order by desc
          //int lenData = ChatDetail.data.length < 10 ? ChatDetail.data.length : 10;

          
          for (int i = 0; i < ChatDetail.data.length; i++) {
            dataCount = i + 1;

            DateTime currentChatDate =
                DateFormat('d/M/yyyy').parse(ChatDetail.data[i].createAt);
            int dateDiff = diffInDays(currentChatDate, lastChatDate);
            if (dateDiff.abs() > 0) {
              Widget dataDiff = Align(
                  alignment: Alignment(0, 0),
                  child : Container(
                    margin: const EdgeInsets.only(top: 5.0),
                    height: 30,
                    width: 120,
                    decoration: BoxDecoration(
                      color: Color(0xffC7D3D8),
                      borderRadius: BorderRadius.all(
                        Radius.circular(8.0),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        ChatDetail.data[i].createAt,
                        style: TextStyle(fontSize: 11, color: Colors.white),
                      ),
                    ),
                    ),
                  );
              countDiffday = countDiffday + 1;
              lastChatDate = currentChatDate;
              streamController.add(dataDiff);
            }
            

            if (ChatDetail.data[i].accountId == AppUrl.userID){
              streamController.add(
                SendedMessage(
                  msgId: ChatDetail.data[i].id,
                  time:  ChatDetail.data[i].time,
                  content: ChatDetail.data[i].content, 
                  filename: ChatDetail.data[i].fileName,
                  readCount: ChatDetail.data[i].readcnt,
                  msgType: ChatDetail.data[i].type.toString(),
                  url: ChatDetail.getFile(ChatDetail.data[i].id),
                  fullname: ChatDetail.data[i].userRead[0].firstname+" "+
                            ChatDetail.data[i].userRead[0].lastname,
                )
              );
            }

            if (ChatDetail.data[i].accountId != AppUrl.userID){
              streamController.add(
                ReceivedMessage(
                  // department: roomName,
                  time:  ChatDetail.data[i].time,
                  content: ChatDetail.data[i].content, 
                  filename: ChatDetail.data[i].fileName,
                  msgType: ChatDetail.data[i].type.toString(),
                  url: ChatDetail.getFile(ChatDetail.data[i].id),
                  fullname: ChatDetail.data[i].userRead[0].firstname+" "+
                            ChatDetail.data[i].userRead[0].lastname,
                  department: ChatDetail.data[i].userRead[0].customerName,
                )
              );
            }
          }

          sum = dataCount + countDiffday;
          WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToBottom(sum));
          AppLoader.hide();
          },
        );
      }else{
        setState(() {
          AppLoader.hide();
        });
        return;
      }
    } catch (e) {
      setState(() {
        AppLoader.hide();
      });
      print(e);
    }
  }

  Widget makeElement(int index) {
    if(index >= listText.length){
      return null;
    }
    
    //Good way 
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children : [
        listText[index]
      ],
    );
  }

  Widget list(BuildContext context) => ScrollablePositionedList.builder(
    itemCount: countItem,
    itemScrollController: itemScrollController,
    itemPositionsListener: itemPositionsListener,
    itemBuilder: (context, index) => makeElement(index),
  );

  @override
  Widget build(BuildContext context) {
    Header.routes = Chathome();
    double _width = MediaQuery.of(context).size.width;
    if(MediaQuery.of(context).viewInsets.bottom > 0){
      itemScrollController.scrollTo(
        index: countItem, 
        duration: Duration(milliseconds: 10),
        curve: Curves.easeInOutCubic
      );
    }
    return Material(
      color: AppColors.bgColor,
      child: WillPopScope(
        onWillPop: () async {
          Get.offAll(Header.routes);
          return false;
        },
        child: Stack (
          children: <Widget>[
            Header.header2ListPage(context),
            Row(
              children: <Widget>[
                Container(
                  width: _width,
                  height: mediaQuery(context, 'h', 600),
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(top: mediaQuery(context, 'h', 360)),
                  child: Column(
                    children: <Widget>[
                      GestureDetector(
                        onTap: (){
                          print(countItem.toString());
                          itemScrollController.jumpTo(index: countItem);
                        },
                        child: Text(
                          roomName,
                          style: TextStyle(
                            fontSize:
                                mediaQuery(context, 'w', 50),
                            color: AppColors.color_gold,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Container(
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 460),
              ),
              padding: EdgeInsets.only(bottom: 2),
              child: Column(
                children: <Widget>[
                  Expanded(
                    child: GestureDetector(
                      onTap: (){
                        FocusScope.of(context).unfocus();
                      },
                        child: Container(
                          padding: EdgeInsets.only(
                            top: mediaQuery(context, 'h', 20),
                            //bottom: 100,
                          ),
                          //GOOD way
                          // child: ListView.builder(
                          //   controller: _scrollController,
                          //   shrinkWrap: true,
                          //   itemBuilder: (BuildContext context, index) => makeElement(index)
                          // ),
                          //Test real <---------
                          // child: ListView.builder(
                          //   itemCount: countItem,
                          //   controller: _scrollController,
                          //   shrinkWrap: true,
                          //   itemBuilder: (BuildContext context, index) => makeElement(index)
                          // ),
                          //test scroll position
                          child : list(context),
                        ),
                      ),
                  ),
                  Container(
                    padding: EdgeInsets.only(
                      bottom: MediaQuery.of(context).viewInsets.bottom,
                    ),
                    child: Header.mainMenu2(
                      context,
                      _text,
                      _dataBase64Img,
                      _selectImage,
                      _dataBase64File,
                      _selectDoc,
                      _filename,
                      () async {
                        if (_dataBase64Img.text.isNotEmpty) {
                          await ChatDetailSend.sendText(
                            text: _dataBase64Img.text,
                            filename: _filename.text,
                            fileType: _selectImage.text,
                            type: 2,
                            room: roomName,
                            chatRoomType: roomType,
                          );
                          _selectImage.clear();
                          _dataBase64Img.clear();
                        }
                      },
                      () async {
                        if (_dataBase64File.text.isNotEmpty) {
                          await ChatDetailSend.sendText(
                            text: _dataBase64File.text,
                            filename: _filename.text,
                            fileType: _selectDoc.text,
                            type: 3,
                            room: roomName,
                            chatRoomType: roomType,
                          );
                          _selectDoc.clear();
                          _dataBase64File.clear();
                        }
                      },
                      () async {
                        if (_text.text.isNotEmpty) {
                          await ChatDetailSend.sendText(
                            text: _text.text,
                            filename: "",
                            fileType: "",
                            type: 1,
                            room: roomName,
                            chatRoomType: roomType,
                          );
                          _text.clear();
                          //FocusScope.of(context).requestFocus(FocusNode());
                        }
                      },
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<String> _findLocalPath() async {
    final directory = Platform.isAndroid
        ? await ExtStorage.getExternalStoragePublicDirectory(ExtStorage.DIRECTORY_DOWNLOADS)
        : await getApplicationDocumentsDirectory();
    return directory;
  }

  createDownload(String url) async {
    var status = await Permission.storage.request();
      print("build 1 Create Downlaoaddd");
      if(status.isGranted){
        Dio dio = Dio();
        var myPath = await _findLocalPath();
        var getRes = await dio.get(url);
        print(getRes.headers);
        String checkFile = getRes.headers['content-length'][0];
        String contentType = getRes.headers['content-type'][0];
        String fileName = getRes.headers['content-disposition'][0].split("filename=")[1];
        bool select = await alertConfirm(context, "แจ้งเตือน" , "คุณต้องการดาวน์โหลด $fileName หรือไม่?  ");
        if(select){
          print("Download..  "+ url);
          print(fileName);
          if(checkFile != "0" && contentType != ""){
            String fullpath = myPath+"/"+fileName;
            var response = await dio.download(url, fullpath);
            if(response.statusCode == 200){
              AppLoader.showSuccess("บันทึกสำเร็จ");
            }else{
              AppLoader.showSuccess("บันทึกไม่สำเร็จ");
            }
          }
        }
      }else{
        print("Permission Deneid");
      }
  }
}
