import 'dart:convert';
import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mime_type/mime_type.dart';
import 'package:path/path.dart' as path;
import 'package:peasmartcare/blocs/feedback_list/feedback_list_bloc.dart';
import 'package:peasmartcare/blocs/feedback_province/feedback_province_bloc.dart';
import 'package:peasmartcare/blocs/feedback_save/feedback_save_bloc.dart';
import 'package:peasmartcare/blocs/feedback_suggestion_type/feedback_suggestion_type_bloc.dart';
import 'package:peasmartcare/blocs/feedback_type/feedback_type_bloc.dart';
import 'package:peasmartcare/components/body_layout.dart';
import 'package:peasmartcare/components/customer_info.dart';
import 'package:peasmartcare/components/header_content.dart';
import 'package:peasmartcare/components/pea_app_bar.dart';
import 'package:peasmartcare/components/profile_avatar.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/constraints/image_asset.dart';
import 'package:peasmartcare/models/feedback_branch_model.dart';
import 'package:peasmartcare/models/feedback_province_model.dart';
import 'package:peasmartcare/models/feedback_subject_suggestion_type_model.dart';
import 'package:peasmartcare/models/feedback_suggestion_type_model.dart';
import 'package:peasmartcare/models/feedback_type_model.dart';
import 'package:peasmartcare/models/file_model.dart';
import 'package:peasmartcare/pages/auth/logout.dart';
import 'package:peasmartcare/utils/app_util.dart';
import 'package:peasmartcare/utils/share_data_util.dart';
import 'package:peasmartcare/widgets/loading.dart';
import 'package:peasmartcare/widgets/sweetalert/sweetalert.dart';

class FeedbackForm extends StatefulWidget {
  @override
  _FeedbackFormState createState() => _FeedbackFormState();
}

class _FeedbackFormState extends State<FeedbackForm> {
  final _formUserInfoKey = GlobalKey<FormState>();
  final _formPEALocationKey = GlobalKey<FormState>();
  TextStyle textStyle = TextStyle(color: Color(AppData.primaryColor), fontSize: 18);
  TextStyle errortyle = TextStyle(color: Colors.orange[900], fontSize: 18, height: 1);

  TextEditingController _name = TextEditingController();
  TextEditingController _idCard = TextEditingController();
  TextEditingController _email = TextEditingController();
  TextEditingController _contactLocation = TextEditingController();
  TextEditingController _crimeScene = TextEditingController();
  TextEditingController _caNumber = TextEditingController();
  TextEditingController _detail = TextEditingController();
  String _feedbackTypeValue;
  String _feedbackSuggestionTypeValue;
  String _feedbackSubjectSuggestionTypeValue;
  String _feedbackProvinceValue;
  String _feedbackProvinceName;
  String _feedbackBranchValue;
  String _feedbackBranchName;
  String _filename;
  FileModel _fileData;

  @override
  void initState() {
    context.read<FeedbackTypeBloc>().add(FeedbackTypeGetList());
    context.read<FeedbackProvinceBloc>().add(FeedbackProvinceGetProvinceList());

    _caNumber.text = ShareDataUtil.getCaNumber();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Size deviceSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: PEAAppBar(
        title: "เสียงของลูกค้า",
        actions: <Widget>[
          ProfileAvatar(),
        ],
      ),
      body: BodyLayout(
        header: CustomerInfo(),
        child: Column(
          children: <Widget>[
            Stack(
              children: <Widget>[
                HeaderContent(
                  title: "เสียงของลูกค้า",
                  icon: ImageAsset.complaintImg,
                ),
                _body(),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _body() {
    return Positioned(
      child: Padding(
        padding: const EdgeInsets.only(top: 50),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _formUserInfo(),
            Stack(
              children: <Widget>[
                HeaderContent(
                  title: "กรุณาระบุการไฟฟ้าที่ท่านต้องการให้ข้อเสนอแนะ/ข้อคิดเห็น",
                  icon: ImageAsset.complaintImg,
                  maxLines: 2,
                ),
                Positioned(
                  child: _formPEALocation(),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _formUserInfo() {
    return Form(
      key: _formUserInfoKey,
      child: Center(
        child: Container(
          constraints: BoxConstraints(maxWidth: 500),
          child: Column(
            children: <Widget>[
              SizedBox(
                height: 40,
              ),
              BlocListener<FeedbackTypeBloc, FeedbackTypeState>(
                listener: (context, state) {
                  if (state is FeedbackTypeErrorUnauthorized) {
                    Navigator.of(context).popUntil((route) => route.isFirst);
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(builder: (context) => LogoutPage()),
                    );
                  }
                },
                child: BlocBuilder<FeedbackTypeBloc, FeedbackTypeState>(
                  builder: (context, state) {
                    if (state is FeedbackTypeLoaded) {
                      List<FeedbackTypeModel> _feedbackTypeList = state.result;
                      return Container(
                        height: 85,
                        padding: EdgeInsets.only(left: 30, right: 30),
                        child: DropdownButtonFormField<dynamic>(
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return "กรุณาเลือกประเภทเสียงของลูกค้า";
                            }
                            return null;
                          },
                          decoration: InputDecoration(
                            hintText: "ประเภทเสียงของลูกค้า",
                            hintStyle: textStyle,
                            labelText: "ประเภทเสียงของลูกค้า",
                            labelStyle: textStyle,
                            errorStyle: errortyle,
                            floatingLabelBehavior: FloatingLabelBehavior.auto,
                            filled: true,
                            fillColor: Color(AppData.whiteColor),
                            contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                            border: OutlineInputBorder(
                              borderRadius: const BorderRadius.all(
                                const Radius.circular(30),
                              ),
                            ),
                          ),
                          value: _feedbackTypeValue,
                          isExpanded: true,
                          onChanged: (val) {
                            setState(() {
                              _feedbackTypeValue = val;
                              _feedbackSuggestionTypeValue = null;
                              _feedbackSubjectSuggestionTypeValue = null;
                            });

                            context.read<FeedbackSuggestionTypeBloc>().add(
                                  FeedbackSuggestionTypeGetSuggestionTypeList(feedbackTypeId: val),
                                );
                          },
                          items: _feedbackTypeList.map<DropdownMenuItem<dynamic>>(
                            (value) {
                              return DropdownMenuItem<dynamic>(
                                value: value.id,
                                child: Text(
                                  value.name,
                                  style: textStyle,
                                ),
                              );
                            },
                          ).toList(),
                        ),
                      );
                    }

                    return Container(
                      height: 85,
                      padding: EdgeInsets.only(left: 30, right: 30),
                      child: DropdownButtonFormField<dynamic>(
                        decoration: InputDecoration(
                          labelText: "ประเภทเสียงของลูกค้า",
                          labelStyle: textStyle,
                          filled: true,
                          fillColor: Color(AppData.whiteColor),
                          contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                          border: OutlineInputBorder(
                            borderRadius: const BorderRadius.all(
                              const Radius.circular(30),
                            ),
                          ),
                        ),
                        isExpanded: true,
                        onChanged: (val) {},
                        items: [].map<DropdownMenuItem<dynamic>>(
                          (value) {
                            return DropdownMenuItem<dynamic>(
                              value: value.id,
                              child: Text(
                                value.name,
                                style: textStyle,
                              ),
                            );
                          },
                        ).toList(),
                      ),
                    );
                  },
                ),
              ),
              Container(
                height: 85,
                padding: EdgeInsets.only(left: 30, right: 30),
                child: TextFormField(
                  validator: (value) {
                    if (value.isEmpty) {
                      return "กรุณากรอกผู้ให้ข้อเสนอแนะ/ข้อคิดเห็น";
                    }
                    return null;
                  },
                  controller: _name,
                  maxLines: 1,
                  style: textStyle,
                  decoration: InputDecoration(
                    hintText: "ผู้ให้ข้อเสนอแนะ/ข้อคิดเห็น",
                    hintStyle: textStyle,
                    labelText: "ผู้ให้ข้อเสนอแนะ/ข้อคิดเห็น",
                    labelStyle: textStyle,
                    errorStyle: errortyle,
                    floatingLabelBehavior: FloatingLabelBehavior.auto,
                    filled: true,
                    fillColor: Color(AppData.whiteColor),
                    contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                    border: OutlineInputBorder(
                      borderRadius: const BorderRadius.all(
                        const Radius.circular(30),
                      ),
                    ),
                  ),
                ),
              ),
              Container(
                height: 85,
                padding: EdgeInsets.only(left: 30, right: 30),
                child: TextFormField(
                  validator: (value) {
                    if (value.isEmpty) {
                      return "กรุณากรอกบัตรประชาชน";
                    } else if (value.isNotEmpty && !AppUtil.isIDCard(value)) {
                      return "บัตรประชาชนไม่ถูกต้อง";
                    }
                    return null;
                  },
                  controller: _idCard,
                  maxLines: 1,
                  style: textStyle,
                  keyboardType: TextInputType.number,
                  inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter.digitsOnly],
                  decoration: InputDecoration(
                    hintText: "บัตรประชาชน",
                    hintStyle: textStyle,
                    labelText: "บัตรประชาชน",
                    labelStyle: textStyle,
                    errorStyle: errortyle,
                    floatingLabelBehavior: FloatingLabelBehavior.auto,
                    filled: true,
                    fillColor: Color(AppData.whiteColor),
                    contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                    border: OutlineInputBorder(
                      borderRadius: const BorderRadius.all(
                        const Radius.circular(30),
                      ),
                    ),
                  ),
                ),
              ),
              Container(
                height: 85,
                padding: EdgeInsets.only(left: 30, right: 30),
                child: TextFormField(
                  validator: (value) {
                    // if (value.isEmpty) {
                    //   return "กรุณากรอกอีเมล";
                    // } else
                    if (value.isNotEmpty && !AppUtil.isEmail(value)) {
                      return "รูปแบบอีเมลไม่ถูกต้อง";
                    }
                    return null;
                  },
                  controller: _email,
                  maxLines: 1,
                  style: textStyle,
                  decoration: InputDecoration(
                    hintText: "อีเมล",
                    hintStyle: textStyle,
                    labelText: "อีเมล",
                    labelStyle: textStyle,
                    errorStyle: errortyle,
                    floatingLabelBehavior: FloatingLabelBehavior.auto,
                    filled: true,
                    fillColor: Color(AppData.whiteColor),
                    contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                    border: OutlineInputBorder(
                      borderRadius: const BorderRadius.all(
                        const Radius.circular(30),
                      ),
                    ),
                  ),
                ),
              ),
              Container(
                height: 195,
                padding: EdgeInsets.only(left: 30, right: 30),
                child: TextFormField(
                  validator: (value) {
                    if (value.isEmpty) {
                      return "กรุณากรอกสถานที่ติดต่อกลับ";
                    }

                    return null;
                  },
                  controller: _contactLocation,
                  maxLines: 5,
                  style: textStyle,
                  decoration: InputDecoration(
                    hintText: "สถานที่ติดต่อกลับ",
                    hintStyle: textStyle,
                    labelText: "สถานที่ติดต่อกลับ",
                    labelStyle: textStyle,
                    errorStyle: errortyle,
                    floatingLabelBehavior: FloatingLabelBehavior.auto,
                    filled: true,
                    fillColor: Color(AppData.whiteColor),
                    contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                    border: OutlineInputBorder(
                      borderRadius: const BorderRadius.all(
                        const Radius.circular(30),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _formPEALocation() {
    return Form(
      key: _formPEALocationKey,
      child: Center(
        child: Container(
          constraints: BoxConstraints(maxWidth: 500),
          child: Column(
            children: <Widget>[
              SizedBox(
                height: 110,
              ),
              BlocListener<FeedbackProvinceBloc, FeedbackProvinceState>(
                listener: (context, state) {
                  if (state is FeedbackProvinceErrorUnauthorized) {
                    Navigator.of(context).popUntil((route) => route.isFirst);
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(builder: (context) => LogoutPage()),
                    );
                  }
                },
                child: BlocBuilder<FeedbackProvinceBloc, FeedbackProvinceState>(
                  builder: (context, state) {
                    if (state is FeedbackProvinceLoaded) {
                      List<FeedbackProvinceModel> _feedbackProvinceList = state.resultProvince;
                      return Container(
                        height: 85,
                        padding: EdgeInsets.only(left: 30, right: 30),
                        child: DropdownButtonFormField<dynamic>(
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return "กรุณาเลือกจังหวัด";
                            }
                            return null;
                          },
                          decoration: InputDecoration(
                            hintText: "จังหวัด",
                            hintStyle: textStyle,
                            labelText: "จังหวัด",
                            labelStyle: textStyle,
                            errorStyle: errortyle,
                            floatingLabelBehavior: FloatingLabelBehavior.auto,
                            filled: true,
                            fillColor: Color(AppData.whiteColor),
                            contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                            border: OutlineInputBorder(
                              borderRadius: const BorderRadius.all(
                                const Radius.circular(30),
                              ),
                            ),
                          ),
                          value: _feedbackProvinceValue,
                          isExpanded: true,
                          onChanged: (val) {
                            FeedbackProvinceModel province = _feedbackProvinceList.singleWhere((item) => item.id == val);

                            setState(() {
                              _feedbackProvinceValue = val;
                              _feedbackProvinceName = province.province;
                              _feedbackBranchValue = null;
                            });

                            context.read<FeedbackProvinceBloc>().add(
                                  FeedbackProvinceGetBranchList(provinceId: val),
                                );
                          },
                          items: _feedbackProvinceList.map<DropdownMenuItem<dynamic>>(
                            (value) {
                              return DropdownMenuItem<dynamic>(
                                value: value.id,
                                child: Text(
                                  value.province,
                                  style: textStyle,
                                ),
                              );
                            },
                          ).toList(),
                        ),
                      );
                    }

                    return Container(
                      height: 85,
                      padding: EdgeInsets.only(left: 30, right: 30),
                      child: DropdownButtonFormField<dynamic>(
                        decoration: InputDecoration(
                          labelText: "จังหวัด",
                          labelStyle: textStyle,
                          filled: true,
                          fillColor: Color(AppData.whiteColor),
                          contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                          border: OutlineInputBorder(
                            borderRadius: const BorderRadius.all(
                              const Radius.circular(30),
                            ),
                          ),
                        ),
                        isExpanded: true,
                        onChanged: (val) {},
                        items: [].map<DropdownMenuItem<dynamic>>(
                          (value) {
                            return DropdownMenuItem<dynamic>(
                              value: value.id,
                              child: Text(
                                value.name,
                                style: textStyle,
                              ),
                            );
                          },
                        ).toList(),
                      ),
                    );
                  },
                ),
              ),
              BlocListener<FeedbackProvinceBloc, FeedbackProvinceState>(
                listener: (context, state) {
                  if (state is FeedbackProvinceErrorUnauthorized) {
                    Navigator.of(context).popUntil((route) => route.isFirst);
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(builder: (context) => LogoutPage()),
                    );
                  }
                },
                child: BlocBuilder<FeedbackProvinceBloc, FeedbackProvinceState>(
                  builder: (context, state) {
                    if (state is FeedbackProvinceLoaded) {
                      List<FeedbackBranchModel> _feedbackBranchList = state.resultBranch;
                      return Container(
                        height: 85,
                        padding: EdgeInsets.only(left: 30, right: 30),
                        child: DropdownButtonFormField<dynamic>(
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return "กรุณาเลือกการไฟฟ้า";
                            }
                            return null;
                          },
                          decoration: InputDecoration(
                            hintText: "การไฟฟ้า",
                            hintStyle: textStyle,
                            labelText: "การไฟฟ้า",
                            labelStyle: textStyle,
                            errorStyle: errortyle,
                            floatingLabelBehavior: FloatingLabelBehavior.auto,
                            filled: true,
                            fillColor: Color(AppData.whiteColor),
                            contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                            border: OutlineInputBorder(
                              borderRadius: const BorderRadius.all(
                                const Radius.circular(30),
                              ),
                            ),
                          ),
                          value: _feedbackBranchValue,
                          isExpanded: true,
                          onChanged: (val) {
                            FeedbackBranchModel branch = _feedbackBranchList.singleWhere((item) => item.id == val);

                            setState(() {
                              _feedbackBranchValue = val;
                              _feedbackBranchName = branch.name;
                            });
                          },
                          items: _feedbackBranchList.map<DropdownMenuItem<dynamic>>(
                            (value) {
                              return DropdownMenuItem<dynamic>(
                                value: value.id,
                                child: Text(
                                  value.name,
                                  style: textStyle,
                                ),
                              );
                            },
                          ).toList(),
                        ),
                      );
                    }

                    return Container(
                      height: 85,
                      padding: EdgeInsets.only(left: 30, right: 30),
                      child: DropdownButtonFormField<dynamic>(
                        decoration: InputDecoration(
                          labelText: "การไฟฟ้า",
                          labelStyle: textStyle,
                          filled: true,
                          fillColor: Color(AppData.whiteColor),
                          contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                          border: OutlineInputBorder(
                            borderRadius: const BorderRadius.all(
                              const Radius.circular(30),
                            ),
                          ),
                        ),
                        isExpanded: true,
                        onChanged: (val) {},
                        items: [].map<DropdownMenuItem<dynamic>>(
                          (value) {
                            return DropdownMenuItem<dynamic>(
                              value: value.id,
                              child: Text(
                                value.name,
                                style: textStyle,
                              ),
                            );
                          },
                        ).toList(),
                      ),
                    );
                  },
                ),
              ),
              Container(
                height: 195,
                padding: EdgeInsets.only(left: 30, right: 30),
                child: TextFormField(
                  validator: (value) {
                    // if (value.isEmpty) {
                    //   return "กรุณากรอกสถานที่เกิดเหตุ";
                    // }
                    return null;
                  },
                  controller: _crimeScene,
                  maxLines: 5,
                  style: textStyle,
                  decoration: InputDecoration(
                    hintText: "สถานที่เกิดเหตุ",
                    hintStyle: textStyle,
                    labelText: "สถานที่เกิดเหตุ",
                    labelStyle: textStyle,
                    errorStyle: errortyle,
                    floatingLabelBehavior: FloatingLabelBehavior.auto,
                    filled: true,
                    fillColor: Color(AppData.whiteColor),
                    contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                    border: OutlineInputBorder(
                      borderRadius: const BorderRadius.all(
                        const Radius.circular(30),
                      ),
                    ),
                  ),
                ),
              ),
              // Container(
              //   height: 100,
              //   width: double.infinity,
              //   padding: EdgeInsets.only(left: 25, right: 25),
              //   child: Card(
              //     shape: RoundedRectangleBorder(
              //       borderRadius: BorderRadius.circular(30),
              //     ),
              //     color: Color(AppData.whiteColor),
              //     child: Padding(
              //       padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
              //       child: Column(
              //         mainAxisAlignment: MainAxisAlignment.center,
              //         crossAxisAlignment: CrossAxisAlignment.start,
              //         children: <Widget>[
              //           Text("บัตรประชาชน", style: textLabelStyle),
              //           SizedBox(height: 5),
              //           Text(_idCard, style: textStyle),
              //         ],
              //       ),
              //     ),
              //   ),
              // ),
              Container(
                height: 85,
                padding: EdgeInsets.only(left: 30, right: 30),
                child: TextFormField(
                  validator: (value) {
                    if (value.isEmpty) {
                      return "กรุณากรอกหมายเลขผู้ใช้ไฟฟ้า";
                    }
                    return null;
                  },
                  controller: _caNumber,
                  maxLines: 1,
                  style: textStyle,
                  enabled: false,
                  keyboardType: TextInputType.number,
                  inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter.digitsOnly],
                  decoration: InputDecoration(
                    hintText: "หมายเลขผู้ใช้ไฟฟ้า",
                    hintStyle: textStyle,
                    labelText: "หมายเลขผู้ใช้ไฟฟ้า",
                    labelStyle: textStyle,
                    errorStyle: errortyle,
                    floatingLabelBehavior: FloatingLabelBehavior.auto,
                    filled: true,
                    fillColor: Color(AppData.whiteColor),
                    contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                    border: OutlineInputBorder(
                      borderRadius: const BorderRadius.all(
                        const Radius.circular(30),
                      ),
                    ),
                  ),
                ),
              ),
              BlocListener<FeedbackSuggestionTypeBloc, FeedbackSuggestionTypeState>(
                listener: (context, state) {
                  if (state is FeedbackSuggestionTypeErrorUnauthorized) {
                    Navigator.of(context).popUntil((route) => route.isFirst);
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(builder: (context) => LogoutPage()),
                    );
                  }
                },
                child: BlocBuilder<FeedbackSuggestionTypeBloc, FeedbackSuggestionTypeState>(
                  builder: (context, state) {
                    if (state is FeedbackSuggestionTypeLoaded) {
                      List<FeedbackSuggestionTypeModel> _feedbackSuggestionTypeList = state.resultSuggestionType;
                      return Container(
                        height: 85,
                        padding: EdgeInsets.only(left: 30, right: 30),
                        child: DropdownButtonFormField<dynamic>(
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return "กรุณาเลือกประเภทข้อเสนอแนะ/ข้อคิดเห็น";
                            }
                            return null;
                          },
                          decoration: InputDecoration(
                            hintText: "ประเภทข้อเสนอแนะ/ข้อคิดเห็น",
                            hintStyle: textStyle,
                            labelText: "ประเภทข้อเสนอแนะ/ข้อคิดเห็น",
                            labelStyle: textStyle,
                            errorStyle: errortyle,
                            floatingLabelBehavior: FloatingLabelBehavior.auto,
                            filled: true,
                            fillColor: Color(AppData.whiteColor),
                            contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                            border: OutlineInputBorder(
                              borderRadius: const BorderRadius.all(
                                const Radius.circular(30),
                              ),
                            ),
                          ),
                          value: _feedbackSuggestionTypeValue,
                          isExpanded: true,
                          onChanged: (val) {
                            setState(() {
                              _feedbackSuggestionTypeValue = val;
                              _feedbackSubjectSuggestionTypeValue = null;
                            });

                            context.read<FeedbackSuggestionTypeBloc>().add(
                                  FeedbackSuggestionTypeGetSubjectSuggestionTypeList(suggestionTypeId: val),
                                );
                          },
                          items: _feedbackSuggestionTypeList.map<DropdownMenuItem<dynamic>>(
                            (value) {
                              return DropdownMenuItem<dynamic>(
                                value: value.id,
                                child: Text(
                                  value.name,
                                  style: textStyle,
                                ),
                              );
                            },
                          ).toList(),
                        ),
                      );
                    }

                    return Container(
                      height: 85,
                      padding: EdgeInsets.only(left: 30, right: 30),
                      child: DropdownButtonFormField<dynamic>(
                        decoration: InputDecoration(
                          labelText: "ประเภทข้อเสนอแนะ/ข้อคิดเห็น",
                          labelStyle: textStyle,
                          filled: true,
                          fillColor: Color(AppData.whiteColor),
                          contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                          border: OutlineInputBorder(
                            borderRadius: const BorderRadius.all(
                              const Radius.circular(30),
                            ),
                          ),
                        ),
                        isExpanded: true,
                        onChanged: (val) {},
                        items: [].map<DropdownMenuItem<dynamic>>(
                          (value) {
                            return DropdownMenuItem<dynamic>(
                              value: value.id,
                              child: Text(
                                value.name,
                                style: textStyle,
                              ),
                            );
                          },
                        ).toList(),
                      ),
                    );
                  },
                ),
              ),
              BlocListener<FeedbackSuggestionTypeBloc, FeedbackSuggestionTypeState>(
                listener: (context, state) {
                  if (state is FeedbackSuggestionTypeErrorUnauthorized) {
                    Navigator.of(context).popUntil((route) => route.isFirst);
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(builder: (context) => LogoutPage()),
                    );
                  }
                },
                child: BlocBuilder<FeedbackSuggestionTypeBloc, FeedbackSuggestionTypeState>(
                  builder: (context, state) {
                    if (state is FeedbackSuggestionTypeLoaded) {
                      List<FeedbackSubjectSuggestionTypeModel> _feedbackSubjectSuggestionTypeList = state.resultSubjectSuggestionType;
                      return Container(
                        height: 85,
                        padding: EdgeInsets.only(left: 30, right: 30),
                        child: DropdownButtonFormField<dynamic>(
                          validator: (value) {
                            // if (value == null || value.isEmpty) {
                            //   return "กรุณาเลือกหัวข้อ";
                            // }
                            return null;
                          },
                          decoration: InputDecoration(
                            hintText: "หัวข้อ",
                            hintStyle: textStyle,
                            labelText: "หัวข้อ",
                            labelStyle: textStyle,
                            errorStyle: errortyle,
                            floatingLabelBehavior: FloatingLabelBehavior.auto,
                            filled: true,
                            fillColor: Color(AppData.whiteColor),
                            contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                            border: OutlineInputBorder(
                              borderRadius: const BorderRadius.all(
                                const Radius.circular(30),
                              ),
                            ),
                          ),
                          value: _feedbackSubjectSuggestionTypeValue,
                          isExpanded: true,
                          onChanged: (val) {
                            setState(() {
                              _feedbackSubjectSuggestionTypeValue = val;
                            });
                          },
                          items: _feedbackSubjectSuggestionTypeList.map<DropdownMenuItem<dynamic>>(
                            (value) {
                              return DropdownMenuItem<dynamic>(
                                value: value.id,
                                child: Text(
                                  value.name,
                                  style: textStyle,
                                ),
                              );
                            },
                          ).toList(),
                        ),
                      );
                    }

                    return Container(
                      height: 85,
                      padding: EdgeInsets.only(left: 30, right: 30),
                      child: DropdownButtonFormField<dynamic>(
                        decoration: InputDecoration(
                          labelText: "หัวข้อ",
                          labelStyle: textStyle,
                          filled: true,
                          fillColor: Color(AppData.whiteColor),
                          contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                          border: OutlineInputBorder(
                            borderRadius: const BorderRadius.all(
                              const Radius.circular(30),
                            ),
                          ),
                        ),
                        isExpanded: true,
                        onChanged: (val) {},
                        items: [].map<DropdownMenuItem<dynamic>>(
                          (value) {
                            return DropdownMenuItem<dynamic>(
                              value: value.id,
                              child: Text(
                                value.name,
                                style: textStyle,
                              ),
                            );
                          },
                        ).toList(),
                      ),
                    );
                  },
                ),
              ),
              Container(
                height: 195,
                padding: EdgeInsets.only(left: 30, right: 30),
                child: TextFormField(
                  validator: (value) {
                    // if (value.isEmpty) {
                    //   return "กรุณากรอกรายละเอียด";
                    // }
                    return null;
                  },
                  controller: _detail,
                  maxLines: 5,
                  style: textStyle,
                  decoration: InputDecoration(
                    hintText: "รายละเอียด",
                    hintStyle: textStyle,
                    labelText: "รายละเอียด",
                    labelStyle: textStyle,
                    errorStyle: errortyle,
                    floatingLabelBehavior: FloatingLabelBehavior.auto,
                    filled: true,
                    fillColor: Color(AppData.whiteColor),
                    contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                    border: OutlineInputBorder(
                      borderRadius: const BorderRadius.all(
                        const Radius.circular(30),
                      ),
                    ),
                  ),
                ),
              ),
              Container(
                padding: EdgeInsets.only(left: 30, right: 30),
                child: RaisedButton.icon(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(7),
                  ),
                  icon: Icon(
                    Icons.attach_file,
                    color: Colors.white,
                  ),
                  label: Text(
                    "เอกสารแนบ",
                    style: TextStyle(
                      fontWeight: FontWeight.w800,
                      color: Colors.white,
                      fontSize: 18,
                    ),
                  ),
                  color: Color(AppData.greyColor),
                  onPressed: () {
                    _openFileExplorer();
                  },
                ),
              ),
              SizedBox(height: 20),
              Container(
                child: _filename != null
                    ? Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          InkWell(
                            child: Icon(Icons.close),
                            onTap: () {
                              SweetAlert.show(
                                context,
                                title: "ต้องการลบไฟล์ใช่หรือไม่",
                                style: SweetAlertStyle.confirm,
                                showCancelButton: true,
                                onPress: (bool isConfirm) {
                                  if (isConfirm) {
                                    setState(() {
                                      _filename = null;
                                      _fileData = null;
                                    });
                                    Navigator.pop(context);
                                    return false;
                                  }
                                },
                              );
                            },
                          ),
                          SizedBox(width: 10),
                          Text(
                            _filename,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ],
                      )
                    : Text(""),
              ),
              BlocListener<FeedbackSaveBloc, FeedbackSaveState>(
                listener: (context, state) {
                  if (state is FeedbackSaveLoaded) {
                    if (state.result != null && state.result) {
                      SweetAlert.show(
                        context,
                        subtitle: "บันทึกเรื่องร้องเรียนสำเร็จ",
                        style: SweetAlertStyle.success,
                        showCancelButton: false,
                        onPress: (bool isConfirm) {
                          context.read<FeedbackListBloc>().add(FeedbackListGetList());
                          Navigator.pop(context);
                          Navigator.pop(context);

                          return false;
                        },
                      );
                    } else {
                      SweetAlert.show(
                        context,
                        subtitle: "บันทึกเรื่องร้องเรียนไม่สำเร็จ",
                        style: SweetAlertStyle.error,
                      );
                    }
                  } else if (state is FeedbackSaveError) {
                    SweetAlert.show(
                      context,
                      subtitle: "บันทึกเรื่องร้องเรียนไม่สำเร็จ",
                      style: SweetAlertStyle.error,
                    );
                  } else if (state is FeedbackSaveErrorUnauthorized) {
                    Navigator.of(context).popUntil((route) => route.isFirst);
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(builder: (context) => LogoutPage()),
                    );
                  }
                },
                child: BlocBuilder<FeedbackSaveBloc, FeedbackSaveState>(builder: (context, state) {
                  if (state is FeedbackSaveLoading) {
                    return Loading(height: 50);
                  }
                  return Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.fromLTRB(0, 30, 0, 15),
                        child: RaisedButton(
                          padding: EdgeInsets.only(top: 12, left: 30, right: 30, bottom: 12),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(7),
                          ),
                          child: Text(
                            "บันทึก",
                            style: TextStyle(
                              fontWeight: FontWeight.w800,
                              color: Colors.white,
                              fontSize: 18,
                            ),
                          ),
                          color: Color(AppData.yellowColor),
                          onPressed: () {
                            bool _userInfoValidate = _formUserInfoKey.currentState.validate();
                            bool _peaLocationValidate = _formPEALocationKey.currentState.validate();
                            if (_userInfoValidate && _peaLocationValidate) {
                              context.read<FeedbackSaveBloc>().add(
                                    FeedbackSaveOnSubmit(
                                      feedbackTypeId: _feedbackTypeValue,
                                      name: _name.text,
                                      idCard: _idCard.text,
                                      email: _email.text,
                                      provinceId: _feedbackProvinceValue,
                                      branchId: _feedbackBranchValue,
                                      branchName: _feedbackBranchName,
                                      contactLocation: _contactLocation.text,
                                      crimeScene: _crimeScene.text,
                                      caNumber: _caNumber.text,
                                      suggestionTypeId: _feedbackSuggestionTypeValue,
                                      subjectSuggestionTypeId: _feedbackSubjectSuggestionTypeValue,
                                      detail: _detail.text,
                                      fileData: _fileData,
                                    ),
                                  );
                            }
                          },
                        ),
                      ),
                      SizedBox(
                        width: 20,
                      ),
                      Container(
                        padding: EdgeInsets.fromLTRB(0, 30, 0, 15),
                        child: RaisedButton(
                          padding: EdgeInsets.only(top: 12, left: 30, right: 30, bottom: 12),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(7),
                          ),
                          child: Text(
                            "ยกเลิก",
                            style: TextStyle(
                              fontWeight: FontWeight.w800,
                              color: Colors.white,
                              fontSize: 18,
                            ),
                          ),
                          color: Color(AppData.greyColor),
                          onPressed: () {
                            Navigator.pop(context);
                          },
                        ),
                      ),
                    ],
                  );
                }),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _openFileExplorer() async {
    FilePickerResult fileResult = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx', 'mp3'],
    );

    if (fileResult != null) {
      PlatformFile platformFile = fileResult.files.first;
      // double sizeInMb = platformFile.bytes.lengthInBytes / (1024 * 1024);

      // print(file.name);
      // print(file.bytes);
      // print(file.size);
      // print(file.extension);
      // print(file.path);

      File file = File(platformFile.path);

      List<int> fileBytes = file.readAsBytesSync();

      double sizeInMb = file.lengthSync() / (1024 * 1024);

      if (sizeInMb > 10) {
        SweetAlert.show(
          context,
          subtitle: "กรุณาเลือกไฟล์ที่ที่มีขนาดไม่เกิน 10 MB.",
          style: SweetAlertStyle.error,
        );
      } else {
        String base64File = base64Encode(fileBytes);
        setState(() {
          _filename = path.basename(file.path);
        });

        _fileData = FileModel();
        _fileData.extensionData = path.extension(_filename);
        _fileData.fileName = _filename;
        _fileData.fileContentBase64 = base64File;
        _fileData.mimeType = mime(_filename);
      }
    }
  }
}
