import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:get/get.dart';
import 'package:mwf_app/service/notification_count.dart';
import 'package:mwf_app/service/alert.dart';
import 'package:mwf_app/service/assets.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/model/package.dart';
import 'package:mwf_app/screen/bottom_menu.dart';
import 'package:mwf_app/set4/list_additional.dart';

//Package_model
class DetailAdditional extends StatefulWidget {
  final image;
  final name;
  final detail;
  final pId;

  DetailAdditional(this.image, this.name, this.detail, this.pId);

  @override
  _DetailAdditionalState createState() =>
      _DetailAdditionalState(this.image, this.name, this.detail, this.pId);
}

var statusProcess;

class _DetailAdditionalState extends State<DetailAdditional> {
  String image;
  String name;
  String detail;
  String pId;

  bool isLoading;

  _DetailAdditionalState(this.image, this.name, this.detail, this.pId);

  TextEditingController _comment = TextEditingController(); //ความต้องการลูกค้า
  var operationStatus = ''; // สถานะการดำเนินการ
  List<KeyValueModel> packageStatusList = [
    KeyValueModel(key: "เลือก", value: ""),
  ];

  @override
  void initState() {
    super.initState();
    print('DetailAdditional : screen');
    loadPackageStatusList();
  }

  loadPackageStatusList() async {
    setState(() {
      isLoading = true;
    });
    try {
      final getPackageStatusList = await Package
          .getDataPackageStatusList(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
      for (var i = 0; i < getPackageStatusList.length; i++) {
        setState(() {
          packageStatusList.add(
            KeyValueModel(
                key: getPackageStatusList[i]['StatusType']
                    .toString(), // key คือค่าที่แสดง
                value: getPackageStatusList[i]['Id'].toString()),
          );
        });
      }
      await Future.delayed(const Duration(seconds: 1));
      setState(() {
        isLoading = false;
      });
      return "xx";
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      print(e);
    }
  }

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

    return Material(
      color: AppColors.bgColor,
      child: WillPopScope(
        onWillPop: () async {
          Get.offAll(ListAdditional());
          return false;
        },
        child: Stack(
          children: <Widget>[
            _footer(_width),
            _body(_width, _height),
            //_imageHeader(),
            _topHeaderTab(_width),
            // _partHTML(_width),
          ],
        ),
      ),
    );
  }

  Widget _topHeaderTab(_width) {
    return Stack(
      children: <Widget>[
        Container(
          width: _width,
          height: mediaQuery(context, 'h', 450),
          child: Image.asset(
            AppAssets.bg_service,
            fit: BoxFit.cover,
          ),
        ),
        GestureDetector(
          onTap: () {
            print('Navigator.pop');
            Get.off(ListAdditional());
            // Navigator.pop(context);
          },
          child: Container(
            color: Colors.transparent,
            margin: EdgeInsets.only(
              left: mediaQuery(context, 'w', 0),
              top: mediaQuery(context, 'h', 140),
            ),
            padding: EdgeInsets.all(
              mediaQuery(context, 'h', 20),
            ),
            child: Icon(
              Icons.arrow_back_ios,
              color: Colors.white,
              size: mediaQuery(context, 'h', 90),
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.only(
            right: mediaQuery(context, 'w', 240),
          ),
          width: _width,
          padding: EdgeInsets.fromLTRB(mediaQuery(context, "w", 100),
              mediaQuery(context, "h", 171), 0, 0),
          child: Text(
            AppStrings.profileFullName + " : " + AppStrings.profilePosition,
            textAlign: TextAlign.right,
            style: TextStyle(
              color: AppColors.color_profile,
              fontWeight: FontWeight.bold,
              fontSize: mediaQuery(context, "w", 30),
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.only(
            right: mediaQuery(context, 'w', 240),
          ),
          width: _width,
          padding: EdgeInsets.fromLTRB(mediaQuery(context, "w", 100),
              mediaQuery(context, "h", 231), 0, 0),
          child: Text(
            AppStrings.profilePositionName,
            textAlign: TextAlign.right,
            style: TextStyle(
              color: AppColors.color_profile,
              fontSize: mediaQuery(context, "w", 30),
            ),
          ),
        ),
        Container(
          width: mediaQuery(context, 'h', 177),
          height: mediaQuery(context, 'h', 155),
          margin: EdgeInsets.only(
            top: mediaQuery(context, 'h', 130),
            left: mediaQuery(context, 'w', 940),
            right: mediaQuery(context, 'w', 30),
          ),
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            border: Border.all(
              color: Colors.white,
              width: 2,
            ),
            image: DecorationImage(
              fit: BoxFit.fill,
              image: AssetImage(AppAssets.imageProfile),
            ),
          ),
        ),
      ],
    );
  }

  Widget _imageHeader() {
    return Row(
      children: [
        image != null
            ? Container(
                width: mediaQuery(context, 'w', 1125),
                height: mediaQuery(context, 'h', 700),
                margin: EdgeInsets.only(
                  top: mediaQuery(context, 'h', 200),
                ),
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: NetworkImage(
                      image,
                    ),
                    fit: BoxFit.fitWidth,
                  ),
                ),
              )
            : Container(
                //รูปภาพ
                width: mediaQuery(context, 'w', 1125),
                height: mediaQuery(context, 'h', 700),
                margin: EdgeInsets.only(
                  top: mediaQuery(context, 'h', 200),
                ),
                child: Image.asset(
                  AppAssets.noimage,
                  fit: BoxFit.cover,
                ),
              ),
      ],
    );
  }

  Widget _footer(_width) {
    return Stack(
      children: [
        Container(
          width: _width,
          height: mediaQuery(context, 'h', 175),
          margin: EdgeInsets.only(
            top: mediaQuery(context, 'h', 2267.16),
          ),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.only(
              topRight: Radius.circular(
                mediaQuery(context, 'h', 100),
              ),
            ),
            color: Color(0xFF7F3F98),
          ),
          child: BottomMenu(),
        ),
        Container(
          //สีม่วง เล็ก ๆ ซ้าย
          width: _width,
          height: mediaQuery(context, 'h', 121.87),
          margin: EdgeInsets.only(
            top: mediaQuery(context, 'h', 2146),
          ),
          color: Color(0xFF7F3F98),
        ),
      ],
    );
  }

  Widget _partHTML(_width) {
    return Container(
      width: _width,
      padding: EdgeInsets.fromLTRB(
        mediaQuery(context, 'h', 60),
        mediaQuery(context, 'h', 20),
        mediaQuery(context, 'h', 60),
        mediaQuery(context, 'h', 60),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Flexible(
                child: Text(
                  name != null ? name : '',
                  style: TextStyle(
                    color: AppColors.color,
                    fontSize: mediaQuery(context, "h", 60),
                  ),
                ),
              ),
            ],
          ),
          HtmlWidget(
            detail,
            enableCaching: false,
            customWidgetBuilder: (element) {
              if (element.localName == 'img') {
                return Image.network(element.attributes['src']);
              }
              return null;
            },
          ),
        ],
      ),
    );
  }

  Widget _userComment(_width) {
    return Container(
      //ที่ซ่อนไว้
      width: _width,
      padding: EdgeInsets.fromLTRB(
        mediaQuery(context, 'w', 60),
        mediaQuery(context, 'h', 60),
        mediaQuery(context, 'w', 60),
        mediaQuery(context, 'h', 60),
      ),
      child: Column(
        children: <Widget>[
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                'ความต้องการลูกค้า :',
                style: TextStyle(
                  color: AppColors.color_text,
                  fontSize: mediaQuery(context, 'h', 40),
                ),
              ),
              SizedBox(
                height: mediaQuery(context, 'h', 20),
              ),
              Card(
                color: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(
                    mediaQuery(context, 'h', 50),
                  ),
                ),
                child: Padding(
                  padding: EdgeInsets.all(
                    mediaQuery(context, 'h', 40),
                  ),
                  child: TextField(
                    controller: _comment,
                    maxLines: 5,
                    style: TextStyle(
                      fontSize: mediaQuery(context, 'h', 36),
                      color: Color(0xFF707070),
                    ),
                    decoration: InputDecoration.collapsed(
                      hintText: "",
                    ),
                  ),
                ),
              ),
            ],
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                'สถานะการดำเนินการ :',
                style: TextStyle(
                  color: AppColors.color_text,
                  fontSize: mediaQuery(context, 'h', 40),
                ),
              ),
              SizedBox(
                height: mediaQuery(context, 'h', 20),
              ),
              _buildDropDownRow(context),
            ],
          ),
          SizedBox(
            height: mediaQuery(context, 'h', 20),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              _buildButton(context, "ยกเลิก", Colors.white, AppColors.color),
              _buildButton(context, "บันทึก", AppColors.color, Colors.white),
            ],
          ),
        ],
      ),
    );
  }

  Widget _body(_width, _height) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(
            mediaQuery(context, 'h', 120),
          ),
          bottomLeft: Radius.circular(
            mediaQuery(context, 'h', 120),
          ),
        ),
        color: Color(0xFFf2f5f7),
      ),
      height: mediaQuery(context, 'h', 2277),
      child: SingleChildScrollView(
        padding: EdgeInsets.only(
            bottom: _height / 4.1, top: mediaQuery(context, 'h', 340)),
        child: Column(
          children: [
            _partHTML(_width),
            _userComment(_width),
          ],
        ),
      ),
    );
  }

  _buildDropDownRow(context) {
    return Container(
      height: mediaQuery(context, 'h', 130),
      width: mediaQuery(context, 'w', 1005),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          border: Border.all(
            color: Color(0xFF999C9D),
            width: 0.5,
          ),
          color: Colors.white),
      child: Container(
        margin: EdgeInsets.only(
          left: mediaQuery(context, 'w', 25),
        ),
        child: DropdownButtonHideUnderline(
          child: DropdownButton<String>(
            iconSize: 0,
            icon: Icon(Icons.keyboard_arrow_down),
            underline: SizedBox(),
            items: packageStatusList
                .map(
                  (data) => DropdownMenuItem<String>(
                    child: Container(
                      child: Text(
                        data.key,
                        style: TextStyle(
                          fontSize: mediaQuery(context, "h", 50),
                        ),
                        textScaleFactor: 0.7,
                      ),
                    ),
                    value: data.value,
                  ),
                )
                .toList(),
            isExpanded: true,
            onChanged: (String value) {
              setState(() {
                operationStatus = value.toString();
              });
            },
            value: operationStatus,
          ),
        ),
      ),
    );
  }

  _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: () {
          if (text == "บันทึก") {
            save();
          } else {
            Navigator.pop(context, ListAdditional);
          }
        },
        child: Text(
          text,
          style: TextStyle(
            fontSize: 14.0,
            color: fontColor,
          ),
        ),
      ),
    );
  }

  save() async {
    List chk = [_comment.text, operationStatus];
    pId = chk[1];
    var resChk = await checkForm(chk);

    if (resChk == false) {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    } else {
      setState(() {
        isLoading = true;
      });
      
      String employeeId = NotificationCount.getPrefString('EmployeeID');

      Map<String, dynamic> data = {
        "P_Id": AppUrl.P_Id,
        "CA": AppStrings.serviceElectricityUserNumberName,
        "PR_StatusType": operationStatus, // สถานะการดำเนินการ
        "CreateBy": AppUrl.userName,
        "CreateDate": DateTime.now().toString().substring(0,16),
        "PR_Descreption": _comment.text.trim(), //ความต้องการลูกค้า
        "EmployeeID": employeeId,
        "P_Name" : name,
        "authenKey" : AppUrl.AuthenKey,
      };
      print(data);
      await Package.packageRequestCreate(context, data);
      setState(() {
        isLoading = false;
      });
    }
  }
} //class

class KeyValueModel {
  String key;
  String value;

  KeyValueModel({this.key, this.value});
}
