import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:ext_storage/ext_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mime/mime.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/loader.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/style.dart';
import 'package:mwf_app/model/voice.dart';
import 'package:mwf_app/set7/chat_full_photo.dart';
import 'package:mwf_app/set7/file_util.dart';
import 'package:nextflow_thai_personal_id/nextflow_thai_personal_id.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class CustomerVoiceView extends StatefulWidget {
  final voiceIndex;
  final String complainerID;
  CustomerVoiceView(this.voiceIndex, this.complainerID);

  @override
  _CustomerVoiceViewState createState() =>
      _CustomerVoiceViewState(this.voiceIndex, this.complainerID);
}

class _CustomerVoiceViewState extends State<CustomerVoiceView> {
  var voiceIndex;
  var complainerID;
  Voice voiceData = Voice();
  dynamic attachmentFile;
  dynamic mimeType;
  dynamic fileUrl;

  _CustomerVoiceViewState(this.voiceIndex, this.complainerID);

  TextEditingController name = TextEditingController(); // ชื่ผู้ให้ข้อมูล
  TextEditingController idCard = TextEditingController(); //เลขบัตรประชาชน
  TextEditingController phone = TextEditingController(); // เบอร์โทรศัพท์
  TextEditingController email = TextEditingController(); // email
  TextEditingController contactLocation =
      TextEditingController(); // สถานที่ติดต่อกลับ
  TextEditingController province = TextEditingController(); // จังหวัด
  TextEditingController electricity = TextEditingController(); // การไฟฟ้า
  TextEditingController locale = TextEditingController(); // สถานที่เกิดเหตุ
  TextEditingController electricityUserNumber =
      TextEditingController(); // หมายเลขผู้ใช้ไฟฟ้า
  TextEditingController subcategory = TextEditingController(); // ประเภทย่อย
  TextEditingController topic = TextEditingController(); // หัวข้อ
  TextEditingController details = TextEditingController(); // รายละเอียด
  TextEditingController fileName = TextEditingController(); // เอกสารแนบ
  TextEditingController status = TextEditingController(); // สถานะ
  TextEditingController typeVoice = TextEditingController();
  TextEditingController complaintType = TextEditingController();
  TextEditingController subComplaintType = TextEditingController();
  TextEditingController peaCodeName = TextEditingController();
  bool isIdCardValid = true;
  bool isLoading = false;
  ThaiIdValidator validator = ThaiIdValidator();

  @override
  void initState() {
    print('CustomerVoiceView is initState!');
    super.initState();
    loadData();
  }

  Future<void> loadData() async {
    print('CustomerVoiceView : loadData');
    setState(() {
      isLoading = true;
    });
    AppLoader.show();
    try {
      final voice = await Voice.getVoiceView(
          this.complainerID); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
      print(voice);
      if (mounted) {
        setState(() {
          typeVoice.text = voice['tagName'];
          name.text = voice['complainerName'];
          status.text = voice['ComplaintStatus'];
          idCard.text = voice['citizenNumber'];
          phone.text = voice['telephoneNumber'];
          email.text = voice['email'];
          contactLocation.text = voice['contactAddress'];
          province.text = voice['contactAddress'];
          locale.text = voice['accidentLocation'];
          electricityUserNumber.text = voice['caNumber'];
          details.text = voice['detail'];

          complaintType.text = voice['complaintTypeName'];
          subComplaintType.text = voice['complaintSubtypeName'];
          peaCodeName.text = voice['peaName'];
          //File
          final files = voice['files'];
          if (files != null && files.length > 0) {
            fileName.text = files[0]['FileName'];
            attachmentFile = files[0]['FileContent'];
            fileUrl = files[0]['FileUrl'];
            mimeType = files[0]['MimeType'];
          }
        });
        setState(() {
          isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      print(e);
    }
    AppLoader.hide();
  }

  @override
  Widget build(BuildContext context) {
    double _width = MediaQuery.of(context).size.width;
    return Material(
      color: AppColors.bgColor,
      child: Stack(
        children: <Widget>[
          Header.header1(context),
          Header.mainMenu(context),
          Container(
            margin: EdgeInsets.only(
              top: mediaQuery(context, 'h', 950),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  "เสียงของลูกค้า",
                  style: AppStyle.headTextStyle(context),
                )
              ],
            ),
          ),
          Container(
            width: _width,
            height: mediaQuery(context, 'h', 1150),
            margin: EdgeInsets.only(
              top: mediaQuery(context, 'h', 1050),
              left: mediaQuery(context, 'w', 60),
              right: mediaQuery(context, 'w', 60),
            ),
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  _buildTextMenu(context, "ประเภทเสียงของลูกค้า"),
                  _buildSizeBox(context),
                  _buildRow(context, typeVoice),
                  _buildSizeBox(context),
                  _buildTextMenu(context, "ชื่อผู้ให้ข้อมูล"),
                  _buildSizeBox(context),
                  _buildRow(context, name),
                  _buildSizeBox(context),
                  _buildTextMenu(context, "เลขที่บัตรประชาชน"),
                  _buildSizeBox(context),
                  _buildRowIdCard(context, idCard),
                  _buildSizeBox(context),
                  _buildTextMenu(context, "เบอร์โทรศัพท์"),
                  _buildSizeBox(context),
                  _buildRowTelNumber(context, phone),
                  _buildSizeBox(context),
                  _buildTextMenu(context, "อีเมล"),
                  _buildSizeBox(context),
                  _buildRow(context, email),
                  _buildSizeBox(context),
                  _buildTextMenu(context, "สถานที่ติดต่อกลับ"),
                  _buildSizeBox(context),
                  _buildTextArea(context, contactLocation),
                  _buildSizeBox(context),
                  Row(
                    children: <Widget>[
                      Text(
                        "กรุณาระบุการไฟฟ้าที่ท่านต้องการให้ข้อเสนอแนะ / ข้อคิดเห็น",
                        style: TextStyle(
                          color: AppColors.color,
                          fontSize: mediaQuery(context, "w", 30),
                        ),
                      )
                    ],
                  ),
                  _buildSizeBox(context),
                  _buildTextMenu(context, "จังหวัด"),
                  _buildSizeBox(context),
                  _buildRow(context, province),
                  _buildSizeBox(context),
                  _buildTextMenu(context, "การไฟฟ้า (กรุณาเลือกจังหวัดก่อน)"),
                  _buildSizeBox(context),
                  _buildRow(context, peaCodeName),
                  _buildSizeBox(context),
                  _buildTextMenu(context, "สถานที่เกิดเหตุ"),
                  _buildSizeBox(context),
                  _buildTextArea(context, locale),
                  _buildSizeBox(context),
                  _buildTextMenu(context, "หมายเลขผู้ใช้ไฟฟ้า"),
                  _buildSizeBox(context),
                  _buildRow(context, electricityUserNumber),
                  _buildSizeBox(context),
                  _buildTextMenu(context, "ประเภทย่อย"),
                  _buildSizeBox(context),
                  _buildRow(context, complaintType),
                  _buildSizeBox(context),
                  _buildTextMenu(context, "หัวข้อ"),
                  _buildSizeBox(context),
                  _buildRow(context, subComplaintType),
                  _buildSizeBox(context),
                  _buildTextMenu(context, "รายละเอียด"),
                  _buildSizeBox(context),
                  _buildTextArea(context, details),
                  _buildSizeBox(context),
                  Visibility(
                    visible: fileUrl != null,
                    child: Row(
                      children: [
                        Column(
                          children: [
                            _buildTextMenu(context, "เอกสารแนบ"),
                            _buildSizeBox(context),
                            _buildViewDocument(
                                context, fileName, fileUrl, mimeType),
                            _buildSizeBox(context),
                          ],
                        )
                      ],
                    ),
                  ),
                  _buildTextMenu(context, "สถานะ"),
                  _buildSizeBox(context),
                  _buildRow(context, status),
                  _buildSizeBox(context),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  _buildRowIdCard(context, TextEditingController controller) {
    isZero() {
      if (controller.text.length > 0 && isIdCardValid == false) {
        return mediaQuery(context, 'h', 196);
      } else if (controller.text.length == 0 && isIdCardValid == false) {
        setState(() {
          isIdCardValid = true;
        });
        return mediaQuery(context, 'h', 110);
      } else {
        return mediaQuery(context, 'h', 110);
      }
    }

    return Container(
      height: isZero(),
      width: mediaQuery(context, 'w', 1005),
      child: TextField(
        keyboardType: TextInputType.number,
        controller: controller,
        onChanged: (value) {
          var res = validator.validate(value);
          if (res != null) {
            setState(() {
              isIdCardValid = false;
            });
          } else {
            setState(() {
              isIdCardValid = true;
            });
          }
        },
        enabled: true,
        maxLength: 13,
        decoration: InputDecoration(
          errorText:
              isIdCardValid ? null : "กรุณาตรวจสอบ เลขบัตรประจำตัว อีกครั้ง",
          border: OutlineInputBorder(
            borderRadius: const BorderRadius.all(
              const Radius.circular(50.0),
            ),
          ),
          filled: true,
          counterText: "",
          contentPadding: EdgeInsets.fromLTRB(10.0, 0.0, 20.0, 10.0),
          hintStyle: TextStyle(color: Colors.grey[800]),
          fillColor: Colors.white70,
        ),
      ),
    );
  }

  _buildRowTelNumber(context, TextEditingController controller) {
    return Container(
      height: mediaQuery(context, 'h', 110),
      width: mediaQuery(context, 'w', 1005),
      child: TextField(
        keyboardType: TextInputType.number,
        controller: controller,
        enabled: true,
        decoration: InputDecoration(
          border: OutlineInputBorder(
            borderRadius: const BorderRadius.all(
              const Radius.circular(50.0),
            ),
          ),
          filled: true,
          counterText: "",
          contentPadding: EdgeInsets.fromLTRB(10.0, 0.0, 20.0, 10.0),
          hintStyle: TextStyle(color: Colors.grey[800]),
          fillColor: Colors.white70,
        ),
      ),
    );
  }

  _buildTextArea(context, TextEditingController controller) {
    return Container(
      color: Colors.white,
      child: TextField(
        controller: controller,
        enabled: false,
        maxLines: 5,
        decoration: InputDecoration(
          fillColor: Colors.white70,
          border: OutlineInputBorder(
            borderRadius: const BorderRadius.all(
              const Radius.circular(10.0),
            ),
          ),
          hintText: "",
          labelText: '',
        ),
      ),
    );
  }

  _buildSizeBox(context) {
    return SizedBox(
      height: mediaQuery(context, "h", 15),
    );
  }

  _buildTextMenu(context, text) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Text(
          text,
          style: TextStyle(
              fontSize: mediaQuery(context, 'h', 38), color: AppColors.Black),
          textAlign: TextAlign.center,
        ),
        Text(
          "*",
          style: TextStyle(
              fontSize: mediaQuery(context, 'h', 38), color: Colors.red),
          textAlign: TextAlign.center,
        ),
        Text(
          " :",
          style: TextStyle(
              fontSize: mediaQuery(context, 'h', 38), color: AppColors.Black),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  _buildRow(context, TextEditingController controller) {
    return Container(
      height: mediaQuery(context, 'h', 110),
      width: mediaQuery(context, 'w', 1005),
      child: TextField(
        style: TextStyle(
          color: Colors.grey,
        ),
        controller: controller,
        enabled: false,
        decoration: InputDecoration(
          border: OutlineInputBorder(
            borderRadius: const BorderRadius.all(
              const Radius.circular(50.0),
            ),
          ),
          filled: true,
          counterText: "",
          contentPadding: EdgeInsets.fromLTRB(10.0, 0.0, 20.0, 10.0),
          hintStyle: TextStyle(color: Colors.grey),
          fillColor: Colors.white70,
        ),
      ),
    );
  }

  _buildViewDocument(context, TextEditingController controller,
      dynamic url, dynamic mimeType) {
    // print(url);
    // print(controller.text);
    // print(mimeType);
    return Container(
        height: mediaQuery(context, 'h', 110),
        width: mediaQuery(context, 'w', 1005),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              height: mediaQuery(context, 'h', 110),
              width: mediaQuery(context, 'w', 600),
              child: TextField(
                style: TextStyle(
                  color: Colors.grey,
                ),
                controller: controller,
                enabled: false,
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: const BorderRadius.all(
                      const Radius.circular(50.0),
                    ),
                  ),
                  filled: true,
                  counterText: "",
                  contentPadding: EdgeInsets.fromLTRB(10.0, 0.0, 20.0, 10.0),
                  hintStyle: TextStyle(color: Colors.grey),
                  fillColor: Colors.white70,
                ),
              ),
            ),
            ButtonTheme(
              minWidth: mediaQuery(context, "w", 360),
              height: mediaQuery(context, "h", 120),
              child: FlatButton(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(
                    mediaQuery(context, "w", 50),
                  ),
                  side: BorderSide(color: AppColors.color),
                ),
                color: AppColors.color_gold,
                textColor: Colors.white,
                padding: EdgeInsets.all(
                  mediaQuery(context, "w", 10),
                ),
                onPressed: () {
                  print("View");
                  // _viewAttachmentFile(context, attachmentFile);
                  _buildContentMessage(
                      context, _getMsgType(mimeType), url, controller);
                },
                child: Text(
                  "View",
                  style: TextStyle(
                    fontSize: mediaQuery(context, "h", 50),
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ));
  }

  _getMsgType(dynamic mimeType) {
    print(mimeType);
    if(mimeType == "image/jpeg" || mimeType == "image/jpg") {
      return 2;
    } else {
      return 3;
    }
  }

  _buildContentMessage(BuildContext context, msgType, String url, filename) async {
    int type = _getMsgType(msgType); 
    if (type == 2) {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => ChatFullPhoto(
            imageBase64: null,
            linkUrl: url,
            fileName: filename.text
          ),
        ),
      );
    } else if (type == 3) {
      await createDownload(context, url, filename.text);
    }
  }

  createDownload(context, String url, String filename) async {
    var status = await Permission.storage.request();
      print("build 1 Create Downlaoaddd");
      if(status.isGranted){
        try{
          Dio dio = Dio();
          var myPath = await _findLocalPath();
          final getRes = await dio.get(url);
          String fullpath = "";
          if(getRes.statusCode == 200){
            String checkFile = getRes.headers['content-length'][0];
            String contentType = getRes.headers['content-type'][0];
            String typefile = "."+getRes.headers['content-type'][0].split("/")[1].trim();
            bool check = File(myPath+"/"+filename).existsSync();
            String fileName = 
              filename == "" ? 
                DateTime.now().toString().substring(0,10)+"_"+Random.secure().nextInt(1000).toString()+typefile : 
                filename;
            bool select = await alertConfirm(context, "แจ้งเตือน" , "คุณต้องการดาวน์โหลด $fileName หรือไม่?  ");

            if(select){
              print("Download..  "+ url);
              print(fileName);
              if(checkFile != "0" && contentType != ""){
                String name;
                if(check){
              name = filename.toString().split(".")[0]+"("+Random.secure().nextInt(1000).toString()+")."+filename.toString(). split  (".")[1];
                  fullpath = myPath+"/"+name;
                }else{
                  name = fileName;
                  fullpath = myPath+"/"+name;
                }
                var response = await dio.download(url, fullpath);
                if(response.statusCode == 200){
                  AppLoader.showSuccess("บันทึกสำเร็จ");
                  await Future.delayed(Duration(seconds: 3));
                  bool result = await alertConfirm(context, "แจ้งเตือน","ต้องการเปิดไฟล์ $name หรือไม่");
                  if(result){
                    OpenFile.open(fullpath);
                  }
                }else{
                  AppLoader.showError("บันทึกไม่สำเร็จ");
                }
              }
            }
          }else{
            AppLoader.showError("ไม่สามารถดาวน์โหลดได้");
          }
        }catch(e) {
          AppLoader.showError("ไม่สามารถดาวน์โหลดได้");
          print(e);
          throw e;
        }
      }else{
        print("Permission Deneid");
      }
  }

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