import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:mwf_app/model/Permission_model.dart';
import 'package:mwf_app/service/alert.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/loader.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/service/url.dart';
import 'package:mwf_app/model/ResearchQuestion_model.dart';
import 'package:mwf_app/model/Research_model.dart';
import 'package:mwf_app/set6/answer_question.dart';
import 'package:mwf_app/set6/answer_question_result_web_view.dart';
import 'package:mwf_app/set6/answer_question_web_view.dart';
import 'package:url_launcher/url_launcher.dart';

class ServiceQuestionUser extends StatefulWidget {

  ServiceQuestionUser();

  @override
  _ServiceQuestionUserState createState() => _ServiceQuestionUserState();
}

class _ServiceQuestionUserState extends State<ServiceQuestionUser> {
  _ServiceQuestionUserState();

  String isView = '';
  String isAdd = '';
  String isUpdate = '';
  String isDelete = '';
  String isAll = '';
  bool isLoading = false;
  @override
  void initState() {
    super.initState();
    setPermission();
    print('Service_Question_User.dart');
    print('Permission for this menu ...');
    
    print("eployee id : " + AppUrl.EmployeeID);
    print("customer id : " + AppUrl.CustomerID);
    loadData(); // ดึงข้อมูล
  }

  setPermission() async {
    var data = await Permission.getResource("menuQuestionUserData");
    isAdd = data.add;
    isUpdate = data.edit;
    isDelete = data.delete;
    isAll = data.all;
    print("isView -->" + isView);
    print("isAdd -->" + isAdd);
    print("isUpdate -->" + isUpdate);
    print("isDelete -->" + isDelete);
    print("isAll -->" + isAll);
  }

  loadData() async {
    setState(() {
      isLoading = true;
    });
    try {
      final list =
          await ResearchQuestion.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
      setState(() {
        list.forEach((v) {
          final RQList = ResearchQuestion.fromJson(v);
          ResearchQuestion.data.add(RQList); // loop เก็บข้อมูล
        });
      });
      await new Future.delayed(const Duration(milliseconds: 2000));
      setState(() {
        isLoading = false;
      });
    } 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: Stack(
        children: <Widget>[
          Header.header1(context),
          Header.mainMenu(context),
          Container(
            width: _width,
            //color: Colors.black26,
            margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 950),
                left: mediaQuery(context, 'w', 60),
                right: mediaQuery(context, 'w', 60),
                bottom: mediaQuery(context, 'h', 30)),
            child: Column(
              children: <Widget>[
                Container(
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(
                    bottom: mediaQuery(context, 'h', 60),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
//                      Container(
//                        width: mediaQuery(context, 'w', 200),
//                      ),
                      Text(
                        AppStrings.service_question_user,
                        style: TextStyle(
                          color: Color(0xFFB58E38),
                          fontSize: mediaQuery(context, 'h', 70),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          Container(
            width: _width,
            height: mediaQuery(context, 'h', 1150),
            margin: EdgeInsets.only(
              top: mediaQuery(context, 'h', 1100),
              left: mediaQuery(context, 'w', 60),
              right: mediaQuery(context, 'w', 60),
            ),
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  Column(
                    children:
                        List.generate(ResearchQuestion.data.length, (index) {
                      return _buildContent(
                        context,
                        (index + 1).toString(),
                        ResearchQuestion.data[index].rQId,
                        ResearchQuestion.data[index].rQcode,
                        ResearchQuestion.data[index].rQName,
                        ResearchQuestion.data[index].rQStatusName,
                        ResearchQuestion.data[index].startDate,
                        ResearchQuestion.data[index].endDate,
                        index,
                      );
                    }),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  _onTabCardItem(index) async {
    print('_onTabCardItem');

    String rqid = ResearchQuestion.data[index].rQId;

    if (rqid == null) {
      alertForm(context, "Error", "ไม่มี rQId");
      return;
    }
    String rqcode = ResearchQuestion.data[index].rQcode;
    if (rqcode == null) {
      alertForm(context, "Error", "ไม่มี rqcode");
      return;
    }
    String rqname = ResearchQuestion.data[index].rQName;
    if (rqname == null) {
      alertForm(context, "Error", "ไม่มี rqname");
      return;
    }

    // webView version
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => AnswerQuestionWebView(rqid, rqcode, rqname)),
    );
    if(result != null){
      if (result) {
        AppLoader.showSuccess("บันทึกสำเร็จ");
      }
    }
  }

  _buildContent(context, number, rQId, numbermodel, question, status, datestart,
      dateend, index) {
    return GestureDetector(
      onTap: () {
        _onTabCardItem(index);
      },
      child: Container(
        width: mediaQuery(context, 'w', 1005),
//      height: mediaQuery(context, 'h', 380),
        padding: EdgeInsets.all(
          mediaQuery(context, 'h', 50),
        ),
        margin: EdgeInsets.only(
          bottom: mediaQuery(context, 'h', 40),
        ),
        decoration: BoxDecoration(
          borderRadius: new BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 20),
            ),
          ),
          boxShadow: [
            appShadow(),
          ],
          color: Colors.white,
        ),
        child: Row(
          children: <Widget>[
            Container(
              width: mediaQuery(context, 'w', 800),
              child: 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 == null ? "" : 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(
                        numbermodel == null ? "" : numbermodel,
                        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', 40),
                        ),
                      ),
                      Flexible(
                        child: Text(
                          question == null
                              ? ""
                              : status != "ไม่เผยแพร่"
                                  ? question
                                  : "[ร่าง] " + question,
                          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(
                        datestart == null
                            ? ""
                            : datestart.toString().substring(0, 16) + " น.",
                        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(
                        dateend != null
                            ? dateend.toString().substring(0, 16) + " น."
                            : '-',
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 40),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      InkWell(
                          child: Text(
                            'ดูผลสำรวจ',
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 52),
                              decoration: TextDecoration.underline,
                            ),
                          ),
                          onTap: () => _launchURL(rQId)),
                    ],
                  ),
                ],
              ),
            ),
            Flexible(
              child: isUpdate == 1.toString() ||
                      isUpdate == '' ||
                      isAll == 1.toString()
                  ? GestureDetector(
                      onTap: () {
                        status != "ไม่เผยแพร่"
                            ? _onTabCardItem(index)
                            : alertForm(context, "แจ้งเตือน",
                                "ไม่สามารถบันทึกข้อมูลได้ เนื่องจากแบบสอบถามยังไม่ได้เผยแพร่");
                      },
                      child: Container(
                        alignment: Alignment.center,
                        padding: EdgeInsets.only(
                          left: mediaQuery(context, 'w', 40),
                        ),
                        child: Center(
                          child: Icon(
                            Icons.question_answer,
                            size: mediaQuery(context, 'h', 100),
                            color: AppColors.color,
                          ),
                        ),
                      ),
                    )
                  : Container(width: mediaQuery(context, 'w', 40)),
            ),
          ],
        ),
      ),
    );
  }

  _launchURL(String rqId) async {
    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => AnswerQuestionResultWebView(rqId)),
    );
  }
}
