import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:dio/dio.dart';
import 'package:ext_storage/ext_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rounded_date_picker/rounded_picker.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/convert.dart';
import 'package:mwf_app/service/header.dart';
import 'package:mwf_app/service/navigator.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/shadow.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:mwf_app/set2/visiting_plan_list.dart';
import 'package:mwf_app/set4/header_delegate.dart';
import 'package:mwf_app/set4/related_documents.dart';
import 'package:mwf_app/set4/visiting_plan.dart';
import 'package:flutter/services.dart';
import 'package:mwf_app/model/visit_plan.dart';
import 'package:mwf_app/service/alert.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:buddhist_datetime_dateformat/buddhist_datetime_dateformat.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class ProbData {
  TextEditingController problemType = TextEditingController();
  ProbData(this.problemType);
}

List<ProbData> dataProb = [];
List<ListProblme> listProblme = [];
List<ListDocumentFile> listDocumentFile = [];

class ServiceVisitUser extends StatefulWidget {
  // final format = DateFormat("dd-MM-yyyy");
  final visitIdEdit;

  ServiceVisitUser(this.visitIdEdit,
      {Key key, this.file, this.list, this.detail, this.prob})
      : super(key: key);
  Map file;
  Map list;
  Map detail;
  Map prob;

  @override
  _ServiceVisitUserState createState() => _ServiceVisitUserState(
        this.visitIdEdit,
      );
}

  TextEditingController problemType = TextEditingController();

class _ServiceVisitUserState extends State<ServiceVisitUser> {
  TextEditingController startDate = TextEditingController();
  TextEditingController startTime = TextEditingController(); // วันที่เยี่ยมเยือน
  TextEditingController detail = TextEditingController(); //รายละเอียด
  TextEditingController process = TextEditingController(); // การดำเนินการ


  TextEditingController visitTeamId = TextEditingController();
  TextEditingController customerName = TextEditingController();
  TextEditingController customerCode = TextEditingController();
  TextEditingController description = TextEditingController();
  TextEditingController proposeTypename = TextEditingController();
  TextEditingController visitDate = TextEditingController();

  String visitIdEdit;

  _ServiceVisitUserState(
    this.visitIdEdit,
  );

  bool isLoading = false;
  bool loading = false;
  String solutionStatus; // สถานะการแก้ปัญหา
  String strStartDate = "";
  int _radioValue;

  @override
  void initState() {
    super.initState();
    Intl.defaultLocale = 'th';
    print("service_visit_user");
    print(visitIdEdit);
    print(dataProb);

    if (visitIdEdit != null && widget.file == null) {
      print("First time");
      getDataEdit(context);
    }
    if (widget.file != null || widget.detail != null) {
      print("sec time");
      getDataEdit(context);
      setWidget();
    }
  }

  setWidget() {
    setState(() {
      if(widget.file['files'] != null && widget.file['files'].isNotEmpty){
        print("in :: " + widget.file['files'].toString());
        var items = widget.file['files'][0];
        print("Lenth : " + widget.file['files'].length.toString());
        String strUploadFileVisitId;
        String strUserFileName;
        String strFileDescription;
        int strFileSize;
        String strFileContent;
        String strFileUrl;

        print("------- set value part ----------- ");
        strUploadFileVisitId = items.uploadFileVisitId;
        strUserFileName = items.userFileName;
        strFileDescription = items.fileDescription;
        strFileSize = items.fileSize;
        strFileContent = items.fileContent;
      }
    });
  }

  var dropdownValue;

  @override
  Widget build(BuildContext context) {
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    Header.routes = VisitingPlanList();
    double _width = MediaQuery.of(context).size.width;

    return Scaffold(
        body: WillPopScope(
      onWillPop: () async {
        Get.offAll(Header.routes);
        return false;
      },
      child: Stack(
        children: <Widget>[
          Header.mainMenu(context),
          Container(
            margin: EdgeInsets.only(
              top: mediaQuery(context, 'h', 1000),
              bottom: mediaQuery(context, 'h', 200),
            ),
            child: loading
                ? Center(
                    child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.teal),
                  ))
                : CustomScrollView(
                    slivers: <Widget>[
                      SliverToBoxAdapter(
                        child: Column(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.center,
                              margin: EdgeInsets.only(
                                bottom: mediaQuery(context, 'h', 60),
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Text(
                                    AppStrings.service_visit_result,
                                    style: TextStyle(
                                      color: Color(0xFFB58E38),
                                      fontSize: mediaQuery(context, 'h', 60),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Container(
                              alignment: Alignment.center,
                              margin: EdgeInsets.only(
                                bottom: mediaQuery(context, 'h', 60),
                              ),
                              child: Column(
                                children: <Widget>[
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: <Widget>[
                                      Expanded(
                                        flex: 3,
                                        child: Container(
                                          padding: EdgeInsets.only(
                                              left:
                                                  mediaQuery(context, 'w', 60),
                                              bottom:
                                                  mediaQuery(context, 'h', 20)),
                                          //color: Colors.green,
                                          child: Text(
                                            'วันที่เข้าเยี่ยมเยือน : ',
                                            style: TextStyle(
                                              fontSize:
                                                  mediaQuery(context, "w", 30),
                                            ),
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        flex: 3,
                                        child: Container(
                                          padding: EdgeInsets.only(
                                              left:
                                                  mediaQuery(context, 'w', 45),
                                              bottom:
                                                  mediaQuery(context, 'h', 20)),
                                          //color: Colors.black26,
                                          child: Text(
                                            'เวลา : ',
                                            style: TextStyle(
                                              fontSize:
                                                  mediaQuery(context, "w", 30),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  _buildTextFieldTwoColumn(
                                      context, startDate, startTime),
                                  Padding(
                                    padding: EdgeInsets.only(
                                        top: mediaQuery(context, 'h', 50),
                                        right: mediaQuery(context, 'h', 100)),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: <Widget>[
                                        GestureDetector(
                                          onTap: () {
                                            print('Click Add Problem type');
                                            Navigator.of(context)
                                                .pushReplacement(
                                              MaterialPageRoute(
                                                settings: const RouteSettings(
                                                    name: '/visitingPlandProblem'),
                                                builder: (context) =>
                                                    VisitingPlan(
                                                  visitIdEdit,
                                                  list: {
                                                    'lists': listDocumentFile
                                                  },
                                                  detail: {
                                                    'visitDate': startDate.text,
                                                    'visitTime': startTime.text,
                                                    'setdetail': detail.text,
                                                    'setprocess': process.text,
                                                    'solution': solutionStatus
                                                  },
                                                ),
                                              ),
                                            );
                                          },
                                          child: Row(
                                            children: <Widget>[
                                              Icon(
                                                Icons.add_circle_outline,
                                                size: mediaQuery(
                                                    context, 'h', 100),
                                                color: AppColors.color,
                                              ),
                                              SizedBox(
                                                width: mediaQuery(
                                                    context, 'w', 14),
                                              ),
                                              Text(
                                                "เพิ่มประเภทปัญหา",
                                                style: TextStyle(
                                                  color: AppColors.color,
                                                  fontSize: mediaQuery(
                                                      context, 'h', 40),
                                                ),
                                              ),
                                            ],
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                  _buildSizeBox(context),
                                  _buildTextMenu(context,
                                      'ประเภทปัญหา/ความต้องการของลูกค้า'),
                                  _buildSizeBox(context),
                                  //======================================
                                  //
                                  //======================================

                                  if (dataProb != null)
                                    Column(
                                      children: List.generate(dataProb.length,
                                          (index) {
                                        return _buildTextFieldList(
                                          context,
                                          index,
                                          dataProb[index]
                                              .problemType
                                              .text
                                              .split('|')[0],
                                        );
                                      }),
                                    ),

                                  //======================================
                                  _buildSizeBox(context),
                                  _buildSizeBox(context),
                                  _buildTextMenu(context,
                                      'รายละเอียด/ความต้องการของลูกค้า'),
                                  _buildSizeBox(context),
                                  _buildTextFormField(context, detail),
                                  _buildSizeBox(context),
                                  _buildTextMenu(context, 'การดำเนินการ'),
                                  _buildSizeBox(context),
                                  _buildTextFormField(context, process),
                                  _buildSizeBox(context),
                                  _buildTextMenu(context, 'สถานะการแก้ปัญหา'),
                                  _buildSizeBox(context),
                                  Padding(
                                    padding: EdgeInsets.only(
                                        right: mediaQuery(context, 'w', 20)),
                                    child: Row(
                                      children: <Widget>[
                                        _buildRadio(
                                            context, 'อยู่ระหว่างดำเนินการ', 0),
                                        SizedBox(
                                          width: mediaQuery(context, 'w', 100),
                                        ),
                                        _buildRadio(
                                            context, 'ดำเนินการแล้ว', 1),
                                      ],
                                    ),
                                  ),
                                  _buildSizeBox(context),
                                  Padding(
                                    padding: EdgeInsets.only(
                                        right: mediaQuery(context, 'w', 20),
                                        left: mediaQuery(context, 'w', 50)),
                                    child: Row(
                                      children: <Widget>[
                                        Text(
                                          "เอกสารที่เกี่ยวข้อง",
                                          style: TextStyle(
                                            color: AppColors.color,
                                            fontSize:
                                                mediaQuery(context, 'h', 40),
                                          ),
                                        ),
                                        Spacer(),
                                        GestureDetector(
                                          onTap: () {
                                            print('click Add');
                                            Navigator.of(context)
                                                .pushReplacement(
                                              MaterialPageRoute(
                                                settings: const RouteSettings(
                                                    name: '/relateDocument'),
                                                builder: (context) =>
                                                    RelatedDocuments(
                                                  visitIdEdit,
                                                  list: {
                                                    'lists': listDocumentFile
                                                  },
                                                  detail: {
                                                    'visitDate': startDate.text,
                                                    'visitTime': startTime.text,
                                                    'setdetail': detail.text,
                                                    'setprocess': process.text,
                                                    'solution': solutionStatus
                                                  },
                                                  prob: {'prob' : dataProb},
                                                ),
                                              ),
                                            );
                                          },
                                          child: Row(
                                            children: <Widget>[
                                              Icon(
                                                Icons.file_upload,
                                                size: mediaQuery(
                                                    context, 'h', 100),
                                                color: AppColors.color,
                                              ),
                                              SizedBox(
                                                width: mediaQuery(
                                                    context, 'w', 14),
                                              ),
                                              Text(
                                                "เพิ่ม",
                                                style: TextStyle(
                                                  color: AppColors.color,
                                                  fontSize: mediaQuery(
                                                      context, 'h', 40),
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  _buildSizeBox(context),
                                  Container(
                                    width: _width,
                                    height: mediaQuery(context, 'h', 350),
                                    margin: EdgeInsets.only(
                                      left: mediaQuery(context, 'w', 60),
                                      right: mediaQuery(context, 'w', 60),
                                    ),
                                    child: SingleChildScrollView(
                                      child: Column(
                                        children: <Widget>[
                                          Column(
                                            children: List.generate(
                                                listDocumentFile.length,(index) {
                                              return _buildContent(
                                                context,
                                                index,
                                                (index + 1).toString(),
                                                listDocumentFile[index]
                                                    .userFileName,
                                                listDocumentFile[index]
                                                    .fileDescription,
                                                listDocumentFile[index]
                                                    .fileUrl,
                                              );
                                            }),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                    children: <Widget>[
                                      _buildButton(context, "ยกเลิก",
                                          Colors.white, AppColors.color),
                                      _buildButton(context, "ส่ง",
                                          AppColors.color, Colors.white),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
          ),
          Header.headerListPage(context),
        ],
      ),
    ));
  }

  timePicker() async {
    TimeOfDay newTime = await showTimePicker(
      context: context,
      initialTime: startTime.text != ""
          ? TimeOfDay(
              hour: CheckTime.getHour(startTime),
              minute: CheckTime.getMin(startTime))
          : TimeOfDay.now(),
      builder: (context, child) {
        return Container(
          child: Column(children: <Widget>[
            MediaQuery(
                data: MediaQuery.of(context)
                    .copyWith(alwaysUse24HourFormat: true),
                child: child),
            Theme(
              data: Theme.of(context).copyWith(
                primaryColor: AppColors.color,
                accentColor: AppColors.color_gold,
                colorScheme: ColorScheme.light(
                  primary: AppColors.color,
                ),
                buttonTheme: ButtonThemeData(
                  textTheme: ButtonTextTheme.primary,
                ),
              ),
              child: Container(
                height: 0,
                width: 0,
                child: child,
              ),
            ),
          ]),
        );
      },
    );
    if (newTime != null) {
      String hour = newTime.hour.toString();
      String min = newTime.minute.toString();
      var time = AppConvert.fillZeroTime(newTime, hour, min);
      setState(() {
        startTime.text = time;
      });
      print(time);
      return time;
    }
  }

  datePicker() async {
    DateTime newDate = await showRoundedDatePicker(
      context: context,
      initialDate:
          strStartDate != "" ? DateTime.parse(strStartDate) : DateTime.now(),
      firstDate: DateTime(DateTime.now().year - 10),
      lastDate: DateTime(DateTime.now().year + 10),
      locale: Locale('th', 'TH'),
      era: EraMode.BUDDHIST_YEAR,
      theme: ThemeData(primarySwatch: Colors.deepPurple),
      height: 280,
    );
    return newDate;
  }

  Widget _buildHeader() {
    return SliverPersistentHeader(
      floating: true,
      pinned: true,
      delegate: HeaderDelegate(
        flexibleSpace: mediaQuery(context, 'h', 700),
        stackPaddingTop: mediaQuery(context, 'h', 150),
        titlePaddingTop: mediaQuery(context, 'h', 3),
        title: Container(
          alignment: Alignment.center,
          child: Column(
            children: <Widget>[
              Text(
                AppStrings.service_service,
                style: TextStyle(
                    fontSize: mediaQuery(context, "h", 70),
                    color: AppColors.color),
              ),
              Text(
                AppStrings.serviceCompanyName,
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: mediaQuery(context, "h", 36),
                    color: AppColors.color_serviceCompany),
              ),
            ],
          ),
        ),
        subTitle: Column(
          children: <Widget>[
            Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Container(
                      width: mediaQuery(context, "h", 300),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            AppStrings.serviceElectricityUserNumberName,
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: mediaQuery(context, "w", 30),
                                height: 2,
                                color: AppColors.color_serviceCompany),
                          ),
                          Text(
                            AppStrings.service_ElectricityUserAddressName,
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: mediaQuery(context, "w", 30),
                                height: 2,
                                color: AppColors.color_serviceCompany),
                          ),
                          Text(
                            AppStrings.service_ElectricityUserTSIC,
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: mediaQuery(context, "w", 30),
                                height: 2,
                                color: AppColors.color_serviceCompany),
                          ),
                          Text(
                            AppStrings.service_ElectricityName,
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: mediaQuery(context, "w", 30),
                                height: 2,
                                color: AppColors.color_serviceCompany),
                          ),
                        ],
                      ),
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          AppStrings.service_ElectricityUserNumber,
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: mediaQuery(context, "w", 50),
                              height: 1,
                              color: AppColors.color_serviceCompanyDetail),
                        ),
                        Text(
                          AppStrings.serviceElectricityUserAddress,
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: mediaQuery(context, "w", 30),
                              height: 2,
                              color: AppColors.color_serviceCompanyDetail),
                        ),
                        Flexible(
                          child: Text(
                            AppStrings.serviceElectricityUserTSICDetail,
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: mediaQuery(context, 'h', 40),
                                color: AppColors.color_serviceCompanyDetail),
                          ),
                        ),
                        Flexible(
                          child: Text(
                            AppStrings.serviceElectricityNameDetail,
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: mediaQuery(context, "w", 30),
                                height: 2,
                                color: AppColors.color_serviceCompanyDetail),
                          ),
                        ),
                      ],
                    ),
                  ],
                )
              ],
            ),
          ],
        ),
      ),
    );
  }

  _buildTextMenu(context, text) {
    return Padding(
      padding: EdgeInsets.only(left: mediaQuery(context, "w", 50)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Text(
            text + " :",
            style: TextStyle(
                fontSize: mediaQuery(context, 'h', 40), color: AppColors.Black),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

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

  _buildTextFormField(context, controller) {
    return Container(
      padding: EdgeInsets.only(
        left: mediaQuery(context, 'w', 40),
        right: mediaQuery(context, 'w', 40),
      ),
      color: Colors.white,
      child: TextFormField(
        controller: controller,
        keyboardType: TextInputType.text,
        maxLines: 2,
        decoration: InputDecoration(
          border: OutlineInputBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(10.0),
            ),
          ),
          labelStyle: TextStyle(color: Colors.white),
        ),
        textAlign: TextAlign.start,
        style: TextStyle(
          color: Colors.black,
          fontSize: 10.0,
        ),
      ),
    );
  }

  _buildRadio(context, text, int value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        SizedBox(
          height: mediaQuery(context, 'h', 80),
          child: Radio(
            groupValue: _radioValue,
            hoverColor: AppColors.color,
            value: value,
            activeColor: AppColors.color,
            onChanged: (val) {
              setState(() {
                _radioValue = val;
              });
              if (_radioValue == 0) {
                setState(() {
                  solutionStatus = "อยู่ระหว่างการดำเนินการ";
                });
              } else if (_radioValue == 1) {
                setState(() {
                  solutionStatus = "ดำเนินการแล้ว";
                });
              }
              print(solutionStatus);
            },
          ),
        ),
        Text(
          text,
          style: TextStyle(
            fontSize: mediaQuery(context, 'h', 40),
            color: AppColors.Black,
          ),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  _buildTextFieldList(context, index, val) {
    TextEditingController _val = TextEditingController();
    _val.text = val;
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 110),
          width: mediaQuery(context, 'w', 1005),
          child: Stack(
            children: <Widget>[
              TextField(
                enabled: false,
                controller: _val,
                decoration: InputDecoration(
                    //hintText: 'Enter a search term',
//              prefixIcon: Icon(Icons.search),
                    border: OutlineInputBorder(
                      borderRadius: const BorderRadius.all(
                        const Radius.circular(50.0),
                      ),
                    ),
                    filled: true,
                    hintStyle: TextStyle(color: Colors.grey[800]),
                    counterText: "",
                    contentPadding: EdgeInsets.fromLTRB(13.0, 0.0, 20.0, 10.0),
                    fillColor: Colors.white70),
              ),
              GestureDetector(
                onTap: () {
                  print(val);
                  setState(() {
                    dataProb.removeAt(index);
                  });
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(
                        top: mediaQuery(context, 'h', 10),
                        right: mediaQuery(context, 'w', 20),
                      ),
                      child: Icon(
                        Icons.delete,
                        color: AppColors.color_gold,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  _buildTextFieldTwoColumn(context, TextEditingController controller1,
      TextEditingController controller2) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 490),
          child: GestureDetector(
            onTap: () async {
              var newDate = await datePicker();
              if (newDate != null) {
                var dtArray = newDate.toString().split(" ");
                print("dtArray : " + dtArray.toString());
                setState(() {
                  var formatter = DateFormat.yMd();
                  var showDate =
                      formatter.formatInBuddhistCalendarThai(newDate);
                  print("showDate : " + showDate.toString());
                  startDate.text = showDate;
                  strStartDate = dtArray[0];
                  print(showDate);
                  print(startDate.text);
                  print(strStartDate);
                });
              }
            },
            child: Container(
              height: mediaQuery(context, 'h', 105),
              width: mediaQuery(context, 'w', 490),
              padding: EdgeInsets.only(
                left: mediaQuery(context, 'h', 20),
                right: mediaQuery(context, 'h', 20),
              ),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(
                  Radius.circular(
                    mediaQuery(
                      context,
                      'h',
                      150,
                    ),
                  ),
                ),
                border: Border.all(
                  color: Colors.grey[500],
                ),
                color: Colors.white,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(startDate.text),
                  Icon(
                    Icons.calendar_today,
                    color: Colors.grey,
                    size: mediaQuery(
                      context,
                      'h',
                      80,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 490),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(
              Radius.circular(
                mediaQuery(
                  context,
                  'h',
                  150,
                ),
              ),
            ),
            border: Border.all(
              color: Colors.grey[500],
            ),
            color: Colors.white,
          ),
          child: Stack(
            children: <Widget>[
              TextField(
                controller: startTime,
                enabled: false,
                decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderRadius: const BorderRadius.all(
                        const Radius.circular(50.0),
                      ),
                    ),
                    filled: true,
                    hintStyle: TextStyle(color: Colors.grey[800]),
                    counterText: "",
                    contentPadding: EdgeInsets.fromLTRB(15.0, 0.0, 20.0, 10.0),
                    fillColor: Colors.white70),
              ),
              GestureDetector(
                onTap: () async {
                  await timePicker();
                },
                child: Container(
                  margin: EdgeInsets.only(
                    top: mediaQuery(context, 'h', 10),
                    left: mediaQuery(context, 'w', 400),
                  ),
                  child: Icon(
                    Icons.expand_more,
                    color: Colors.grey,
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

//==================================================
//                VisitResult Update
//==================================================
  _visitResultUpdate() async {
    bool chk = await checkForm([startDate.text, startTime.text]);

    if (chk == false) {
      isLoading = false;
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    } else {
      var resultProb = <Map>[];
      var resultDoc = <Map>[];

//==================================================
//                List Problme
//==================================================
      for (var item in dataProb) {
        Map mapListProblem = {
          "CategoryProblem": item.problemType.text.split("|")[0],
          "CategoryProblemId": item.problemType.text.split("|")[1],
        };
        resultProb.add(mapListProblem);
      }
//==================================================
//                Document File
//==================================================
      var mapListDocumentFile;
      for (var item in listDocumentFile) {
        //if(item.uploadFileVisitId == ""){
        mapListDocumentFile = {
          "UploadFileVisitId": item.uploadFileVisitId == ""
              ? visitIdVal.visitId
              : item.uploadFileVisitId,
          "UserFileName": item.userFileName,
          "FileDescription": item.fileDescription,
          "FileSize": item.fileSize,
          "FileContent": item.fileContent,
        };
        resultDoc.add(mapListDocumentFile);
        //}
      }
      if (resultDoc.isEmpty) {
        print("doc empty ");
      }
//==================================================
      var _data = jsonEncode({
        "visitId": visitIdVal.visitId,
        "visitDate": strStartDate + " " + startTime.text,
        "detailProblem": detail.text,
        "statusSolvingProblem": solutionStatus,
        "processDetail": process.text,

        //==================================================

        "CategoryProblemInfo": resultProb,

        //==================================================

        "DocumentFileInfo": resultDoc,

        //==================================================

        "authenKey": AppUrl.AuthenKey
      });
      setState(() {
        isLoading = false;
      });
      print(_data);
      var response = await VisitPlanCreate.visitResultUpdate(context, _data);
      print(response);
    }
  }

  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;
  }

//====================================================================================================
//                                    Get Data Edit (เยี่ยมเยียน Bind data)
//====================================================================================================
  getDataEdit(context) async {
    isLoading = true;
    final list = await VisitPlanCreate.getDataEdit(visitIdEdit);


    detail.clear();
    process.clear();
    if (widget.file == null) {
      listDocumentFile.clear();
    }
    if(widget.prob == null){
      dataProb.clear();
      print("prob empty");
    }else{
      print("is prob");
    }

    try {
      setState(() {
        final dataList = VisitPlanCreate.fromJson(list);
        VisitPlanCreate.data.add(dataList); // loop เก็บข้อมูล
      });

      if (widget.detail == null) {
        print("in getedit");
        startDate.text =
            (int.parse(VisitPlanCreate.data[0].visitDate.substring(6, 10)) <
                    2400
                ? ""
                : (VisitPlanCreate.data[0].visitDate.toString().split(" ")[0]));
        strStartDate = startDate.text == ""
            ? ""
            : AppConvert.dateThaiToEng(startDate.text);

        startTime.text =
            int.parse(VisitPlanCreate.data[0].visitDate.substring(6, 10)) < 2400
                ? ""
                : VisitPlanCreate.data[0].visitDate.toString().split(" ")[1];

        solutionStatus = VisitPlanCreate.data[0].statusSolvingProblem == null
            ? ""
            : VisitPlanCreate.data[0].statusSolvingProblem;
        if (solutionStatus == "อยู่ระหว่างการดำเนินการ") {
          setState(() {
            _radioValue = 0;
          });
        } else if (solutionStatus == "ดำเนินการแล้ว") {
          setState(() {
            _radioValue = 1;
          });
        }

        detail.text = VisitPlanCreate.data[0].detailProblem;
        process.text = VisitPlanCreate.data[0].processDetail;
      } else {
        var itemDetail = widget.detail['details'];
        print("widget detail");
        print(itemDetail);
        startDate.text = itemDetail['visitDate'].toString() == ""
            ? ""
            : itemDetail['visitDate'].toString();

        print(startDate.text);
        strStartDate = startDate.text == ""
            ? ""
            : AppConvert.dateThaiToEng(startDate.text + " 00");
        print(strStartDate);

        detail.text = itemDetail['setdetail'].toString() == ""
            ? ""
            : itemDetail['setdetail'].toString();
        process.text = itemDetail['setprocess'].toString() == ""
            ? ""
            : itemDetail['setprocess'].toString();
        print("detail : " + detail.text);
        print("process : " + process.text);

        startTime.text =
            itemDetail['visitTime'] == "" ? "" : itemDetail['visitTime'];

        solutionStatus =
            itemDetail['solution'] == null ? "" : itemDetail['solution'];
        if (solutionStatus == "อยู่ระหว่างการดำเนินการ") {
          setState(() {
            _radioValue = 0;
          });
        } else if (solutionStatus == "ดำเนินการแล้ว") {
          setState(() {
            _radioValue = 1;
          });
        }
      }

      var problemInfo = VisitPlanCreate.data[0].categoryProblemInfo == null
          ? ""
          : VisitPlanCreate.data[0].categoryProblemInfo;
      
      for (var item in problemInfo) {
        String problemTypeset;
        TextEditingController xx = TextEditingController();

        problemTypeset =
            item['CategoryProblem'] + "|" + item['CategoryProblemId'];

        xx.text = problemTypeset;
        var _list = ProbData(xx);
        dataProb.add(_list);
      }
      var _listDocumentFile = VisitPlanCreate.data[0].visitDocumentInfo == null
          ? []
          : VisitPlanCreate.data[0].visitDocumentInfo;
      print("=========== -- ===============");
      print(_listDocumentFile);
      print("=========== -- ===============");
      if (_listDocumentFile != [] && widget.file == null) {
        print("=========== list not null ===============");
        for (var item in _listDocumentFile) {
          String strUploadFileVisitId;
          String strUserFileName;
          String strFileDescription;
          int strFileSize;
          String strFileContent;
          String strFileUrl;

          strUploadFileVisitId = item['UploadFileVisitId'];
          strUserFileName = item['UserFileName'];
          strFileDescription = item['FileDescription'];
          strFileSize = item['FileSize'];
          strFileContent = item['FileContent'] != null ? item['FileContent'] : "";
          strFileUrl = item['FileUrl'];

          listDocumentFile.add(
            ListDocumentFile(
              strUploadFileVisitId, 
              strUserFileName, 
              strFileDescription, 
              strFileSize, 
              strFileContent,
              strFileUrl
            )
          );
        }
      }
      setState(() {
        isLoading = false;
      });
    } catch (e) {
      //AppLoader.showError('เพิ่มข้อมูลไม่สำเร็จ  ' + ("getData_Edit Error"));
      setState(() {
        isLoading = false;
      });
      print("getData_Edit Error (service_visit_user)");
      throw e;
    }
  }

//====================================================================================================
//
//====================================================================================================

  _buildButton(context, text, bgColor, fontColor) {
    return ButtonTheme(
      minWidth: mediaQuery(context, "w", 477),
      height: mediaQuery(context, "h", 120),
      child: FlatButton(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(
            mediaQuery(context, "w", 50),
          ),
          side: BorderSide(color: AppColors.color),
        ),
        color: bgColor,
        textColor: Colors.red,
        padding: EdgeInsets.all(
          mediaQuery(context, "w", 10),
        ),
        onPressed: () async {
          if (text == "ส่ง") {
            setState(() {
              isLoading = true;
            });
            await _visitResultUpdate();
          } else {
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(
                builder: (context) => VisitingPlanList(),
              ),
            );
          }
        },
        child: Text(
          text,
          style: TextStyle(
            fontSize: 14.0,
            color: fontColor,
          ),
        ),
      ),
    );
  }

  _buildContent(
    context,
    index,
    number,
    namefile,
    detail,
    url,
  ) {
    return Container(
      width: mediaQuery(context, 'w', 1005),
      padding: EdgeInsets.all(
        mediaQuery(context, 'h', 50),
      ),
      margin: EdgeInsets.only(
        bottom: mediaQuery(context, 'h', 40),
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(
          Radius.circular(
            mediaQuery(context, 'h', 20),
          ),
        ),
        boxShadow: [
          appShadow(),
        ],
        color: Colors.white,
      ),
      child: Row(
        children: <Widget>[
          GestureDetector(
            onTap: () async {
              print("URL : " + url);
              print("File name : " + namefile);
              try{
                await createDownload(context, url, namefile);
              }catch(e){
                print("Error : " + e.toString());
              }
              print("load");
            },
            child: Container(
              width: mediaQuery(context, 'w', 780),
              child: Wrap(
                spacing: 5.0,
                runSpacing: 5.0,
                direction: Axis.vertical,
                children: <Widget>[
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'ลำดับ : ',
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 42),
                            ),
                          ),
                          Text(
                            number,
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 40),
                            ),
                          ),
                        ],
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'ชื่อไฟล์ : ',
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 42),
                            ),
                          ),
                          Text(
                            namefile == "" ? '.' : namefile,
                            style: TextStyle(
                              decoration: TextDecoration.underline,
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 40),
                            ),
                          ),
                        ],
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'คำอธิบาย : ',
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 42),
                            ),
                          ),
                          Text(
                            detail,
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 40),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          Flexible(
              child: GestureDetector(
            onTap: () {
              setState(() {
                listDocumentFile.removeAt(index);
              });
            },
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.only(left: mediaQuery(context, 'w', 70)),
              child: Center(
                child: Icon(
                  FontAwesomeIcons.trashAlt,
                  size: mediaQuery(context, 'h', 60),
                  color: AppColors.color_gold,
                ),
              ),
            ),
          ))
        ],
      ),
    );
  }
}
