import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:lazy_load_scrollview/lazy_load_scrollview.dart';
import 'package:provider/provider.dart';
import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
import 'package:telnow_mobile_new/src/layouts/functions/history.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/layouts/web/history_detail.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';

class WebHistoryPage extends StatefulWidget {
  const WebHistoryPage({super.key});

  @override
  State<WebHistoryPage> createState() => _WebHistoryPageState();
}

class _WebHistoryPageState extends State<WebHistoryPage> with TickerProviderStateMixin {
  final HistoryFunction hisFunc = HistoryFunction();
  late AnimationController _animationController;

  var rating = [
    {'key': 1, 'image': "assets/image/icon/very_dissatisfied.png", 'label': 'disatisfied'.tr()},
    {'key': 2, 'image': "assets/image/icon/dissatisfied.png", 'label': 'lessSatisfied'.tr()},
    {'key': 3, 'image': "assets/image/icon/neutral.png", 'label': 'satisfied'.tr()},
    {'key': 4, 'image': "assets/image/icon/satisfied.png", 'label': 'verySatisfied'.tr()},
    {'key': 5, 'image': "assets/image/icon/very_satisfied.png", 'label': 'reallyPleased'.tr()},
  ];
  bool _timeLimit = false;

  @override
  void initState() {
    // print(U.newServerVersion(1716279633));
    Provider.of<HistoryModule>(context, listen: false).reset();
    _animationController = new AnimationController(vsync: this, duration: Duration(seconds: 1));
    _animationController.repeat(reverse: true);

    WidgetsBinding.instance.addPostFrameCallback((_) {
      hisFunc.getActiveForum(context);
    });
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Provider.of<UserModule>(context).resetData() ? RefreshPage(() {
      Provider.of<UserModule>(context, listen: false).setResetData(false);
      hisFunc.getActiveForum(context);
    }) : Scaffold(
      backgroundColor: backgroundColor,
      appBar: PreferredSize(preferredSize: Size.fromHeight(0), child: AppBar(elevation: 0, backgroundColor: primaryColor)),
      body: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('history'.tr(), style: TextStyle(color: textColor, fontSize: 17, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
                Provider.of<HistoryModule>(context).multiSelectMode() ? GestureDetector(
                  child: Container(
                    padding: EdgeInsets.fromLTRB(16, 9, 16, 9),
                    child: Row(
                      children: [
                        Text('delete'.tr(), style: TextStyle(color: primaryColor, fontSize: 14)),
                        SizedBox(width: 5),
                        U.iconsax('trash', color: primaryColor, size: 20)
                      ],
                    ),
                    decoration: BoxDecoration(color: primaryColor.withValues(alpha: 0.1), border: Border.all(color: primaryColor), borderRadius: BorderRadius.all(Radius.circular(50))),
                  ),
                  onTap: () => hisFunc.deleteData(context),
                ) : GestureDetector(
                  child: Text('buttonBack'.tr(), style: TextStyle(color: primaryColor, fontSize: 14)),
                  onTap: (){
                    var pid = U.getPidFromUrl(context.router.currentUrl);
                    context.router.removeLast();
                    context.navigateToPath("/app/$pid/menu");
                  },
                )
              ],
            ),
          ),
          divider(),
          Container(
            padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    GestureDetector(
                      child: Container(
                        padding: EdgeInsets.symmetric(vertical: 5, horizontal: 16),
                        child: Text('ongoing'.tr(), style: TextStyle(color: Provider.of<HistoryModule>(context).selectedFilter() == 1 ? textColor : textColor.withValues(alpha: 0.65), fontSize: 16)),
                        decoration: BoxDecoration(color: Colors.white, border: Border(bottom: BorderSide(color: Provider.of<HistoryModule>(context).selectedFilter() == 1 ? primaryColor : primaryColor.withValues(alpha: 0.3), width: Provider.of<HistoryModule>(context).selectedFilter() == 1 ? 2 : 1))),
                      ),
                      onTap: () {
                        if (!Provider.of<HistoryModule>(context, listen: false).isLoadHistory()) {
                          Provider.of<HistoryModule>(context, listen: false).setPressAttention(0);
                          Provider.of<HistoryModule>(context, listen: false).setSelectedFilter(1);
                          hisFunc.onRefresh(context);
                        }
                      },
                    ),
                    GestureDetector(
                      child: Container(
                        padding: EdgeInsets.symmetric(vertical: 5, horizontal: 16),
                        child: Text('done'.tr(), style: TextStyle(color: Provider.of<HistoryModule>(context).selectedFilter() == 0 ? textColor : textColor.withValues(alpha: 0.65), fontSize: 16)),
                        decoration: BoxDecoration(color: Colors.white, border: Border(bottom: BorderSide(color: Provider.of<HistoryModule>(context).selectedFilter() == 0 ? primaryColor : primaryColor.withValues(alpha: 0.3), width: Provider.of<HistoryModule>(context).selectedFilter() == 0 ? 2 : 1))),
                      ),
                      onTap: () {
                        if (!Provider.of<HistoryModule>(context, listen: false).isLoadHistory()) {
                          Provider.of<HistoryModule>(context, listen: false).setPressAttention(0);
                          Provider.of<HistoryModule>(context, listen: false).setSelectedFilter(0);
                          hisFunc.onRefresh(context);
                        }
                      },
                    ),
                  ],
                ),
                SizedBox(height: 20),
                Provider.of<HistoryModule>(context).selectedFilter() == 0 ? doneFilter() : ongoingFilter(),
              ],
            ),
          ),
          Expanded(
            child: Provider.of<UserModule>(context).user().isNotEmpty ? Container(
              width: double.infinity,
              padding: EdgeInsets.symmetric(horizontal: 100),
              child: LazyLoadScrollView(
                onEndOfPage: () => hisFunc.getMission(context),
                scrollOffset: 500,
                child: EasyRefresh(
                  header: MaterialHeader(clamping: true, color: primaryColor),
                  onRefresh: ()=>hisFunc.onRefresh(context),
                  child: Provider.of<HistoryModule>(context).selectedFilter() == 0 ? doneContainer() : ongoingContainer(),
                ),
              ),
            ) : Provider.of<UserModule>(context).resetData() ? Container() : _timeLimit ? showButton(context) : loadingTemplate(() {if(mounted) setState(()=>_timeLimit=true);},),
          )
        ],
      ),
    );
  }

  Widget ongoingFilter() {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: List.generate(hisFunc.ongoingList.length, (i) {
          return GestureDetector(
            child: Container(
              margin: EdgeInsets.only(right: 16),
              padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
              child: Text(hisFunc.ongoingList[i]['title'], style: TextStyle(color: Provider.of<HistoryModule>(context).checkPressAttention(hisFunc.ongoingList[i]['value']) ? Colors.white : textColor, fontSize: 16)),
              decoration: BoxDecoration(
                  color: Provider.of<HistoryModule>(context).checkPressAttention(hisFunc.ongoingList[i]['value']) ? primaryColor : Color(0xffF2F8F7),
                  border: Border.all(color: Provider.of<HistoryModule>(context).checkPressAttention(hisFunc.ongoingList[i]['value']) ? primaryColor : Color(0xffBEC1C1)),
                  borderRadius: BorderRadius.all(Radius.circular(50))),
            ),
            onTap: () {
              if (!Provider.of<HistoryModule>(context, listen: false).isLoadHistory()) {
                if (Provider.of<HistoryModule>(context, listen: false).checkPressAttention(hisFunc.ongoingList[i]['value'])) {
                  Provider.of<HistoryModule>(context, listen: false).setPressAttention(0);
                  hisFunc.onRefresh(context);
                } else {
                  Provider.of<HistoryModule>(context, listen: false).setPressAttention(hisFunc.ongoingList[i]['value']);
                  hisFunc.onRefresh(context);
                }
              }
            },
          );
        }),
      ),
    );
  }

  Widget ongoingContainer() {
    return SingleChildScrollView(
      child: Column(
        children: [
          U.newServerVersion(1709864293) && !U.getInternetStatus() ? Column(
            children: List.generate(Provider.of<HistoryModule>(context).dataPending().length, (i) {
              return GestureDetector(
                child: Container(
                  width: double.infinity,
                  padding: EdgeInsets.all(15),
                  margin: EdgeInsets.only(bottom: 15),
                  decoration: BoxDecoration(color: Colors.white, border: Border.all(color: textColor.withValues(alpha: 0.15)), borderRadius: BorderRadius.all(Radius.circular(12))),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(convertDate(Provider.of<HistoryModule>(context).dataPending()[i]['datetimeRequest'], context.locale.toString()), style: TextStyle(color: primaryColor, fontSize: 14)),
                          renderStatus('sending'.tr(), Color(0xff02C539).withValues(alpha: 0.2))
                        ],
                      ),
                      SizedBox(height: 10),
                      divider(),
                      SizedBox(height: 10),
                      Row(
                        children: [
                          imageTiles(imageUrl: Provider.of<HistoryModule>(context).dataPending()[i]['image'] ?? "null"),
                          SizedBox(width: 25),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(Provider.of<HistoryModule>(context).dataPending()[i]['title'], style: TextStyle(color: textColor, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
                                SizedBox(height: 10),
                                Text(Provider.of<HistoryModule>(context).dataPending()[i][U.langColumn(context, 'sub')], style: TextStyle(color: textColor), overflow: TextOverflow.ellipsis),
                                SizedBox(height: 5),
                                Text(Provider.of<HistoryModule>(context).dataPending()[i][U.langColumn(context, 'desc')], style: TextStyle(color: textColor), overflow: TextOverflow.ellipsis),
                                dashed(top: 10, bottom: 10),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text('location'.tr()+': '+Provider.of<HistoryModule>(context).dataPending()[i]['location'], style: TextStyle(color: textColor, fontSize: 14), overflow: TextOverflow.ellipsis),
                                    Row(
                                      children: [
                                        Container(
                                          width: 25, height: 25,
                                          decoration: BoxDecoration(image: DecorationImage(image: AssetImage('assets/image/general/Hourglass.png'), fit: BoxFit.cover)),
                                        ),
                                        SizedBox(width: 8),
                                        Text('pending_info_tiles'.tr(), style: TextStyle(color: textColor, fontSize: 14))
                                      ],
                                    )
                                  ],
                                )
                              ],
                            ),
                          )
                        ],
                      )
                    ],
                  ),
                ),
                onTap: () {
                  if(!U.getInternetStatus()){
                    // navigateTo(context, MobHistoryDetailPendingPage(data: Provider.of<HistoryModule>(context, listen: false).dataPending()[i])).then((val) {
                    //   val = val??false;
                    //   if(val) hisFunc.onRefresh(context);
                    // });
                  }
                  else{
                    hisFunc.onRefresh(context);
                  }
                },
              );
            }),
          ) : Container(),

          Column(
            children: List.generate(Provider.of<HistoryModule>(context).dataMisi().length, (i) {
              return GestureDetector(
                child: Container(
                  width: double.infinity,
                  padding: EdgeInsets.all(15),
                  margin: EdgeInsets.only(bottom: 15),
                  decoration: BoxDecoration(color: Colors.white, border: Border.all(color: textColor.withValues(alpha: 0.15)), borderRadius: BorderRadius.all(Radius.circular(12))),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Text(convertDate(Provider.of<HistoryModule>(context).dataMisi()[i]['datetimeRequest'], context.locale.toString()), style: TextStyle(color: primaryColor, fontSize: 14)),
                          SizedBox(width: 15),
                          Expanded(
                            child: Text('ticketNumber'.tr()+': '+Provider.of<HistoryModule>(context).dataMisi()[i]['ticketNo'], style: TextStyle(color: textColor, fontSize: 14), overflow: TextOverflow.ellipsis),
                          ),
                          Provider.of<HistoryModule>(context).dataMisi()[i]['currentState'] == 'DIMULAI' ? Container(
                            child: Row(
                              children: [
                                Container(
                                  width: 25, height: 25,
                                  decoration: BoxDecoration(
                                      border: Border.all(color: primaryColor), borderRadius: BorderRadius.all(Radius.circular(25)),
                                      image: DecorationImage(image: AssetImage('assets/image/general/Avatar.jpg'), fit: BoxFit.cover)
                                  ),
                                ),
                                SizedBox(width: 8),
                                Text(Provider.of<HistoryModule>(context).dataMisi()[i]['servantNameStart'] + 'isWorking'.tr(), style: TextStyle(color: textColor, fontSize: 14), overflow: TextOverflow.ellipsis)
                              ],
                            ),
                          ) : Container(),
                          Provider.of<HistoryModule>(context).dataMisi()[i]['_activeHoldRequest'] != null?renderStatus('hold'.tr(), Color(0xffD3D3D3)):Provider.of<HistoryModule>(context).dataMisi()[i]['currentState'] == 'DIMULAI'?renderStatus('onProgress'.tr(), Color(0xffCCA600).withValues(alpha: 0.2)):renderStatus('queued'.tr(), Color(0xff02C539).withValues(alpha: 0.2))
                        ],
                      ),
                      SizedBox(height: 10),
                      divider(),
                      SizedBox(height: 10),
                      Row(
                        children: [
                          imageTiles(imageUrl: Provider.of<HistoryModule>(context).dataMisi()[i]['_requestImage'] ?? "null", width: 150, height: 120),
                          SizedBox(width: 25),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(Provider.of<HistoryModule>(context).dataMisi()[i][U.langColumn(context, 'requestGroupDescription')], style: TextStyle(color: textColor, fontSize: 16), overflow: TextOverflow.ellipsis),
                                SizedBox(height: 10),
                                Text(Provider.of<HistoryModule>(context).dataMisi()[i][U.langColumn(context, 'requestSubject')], style: TextStyle(color: textColor, fontWeight: FontWeight.w600), overflow: TextOverflow.ellipsis),
                                SizedBox(height: 5),
                                Text(Provider.of<HistoryModule>(context).dataMisi()[i][U.langColumn(context, '_subjectDescription')]??'', style: TextStyle(color: textColor), overflow: TextOverflow.ellipsis),
                                dashed(top: 10, bottom: 10),
                                renderRequested(Provider.of<HistoryModule>(context).dataMisi()[i]),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text('location'.tr()+': '+Provider.of<HistoryModule>(context).dataMisi()[i]['ipphoneExtLocation'], style: TextStyle(color: textColor, fontSize: 14), overflow: TextOverflow.ellipsis),
                                    Provider.of<HistoryModule>(context).dataMisi()[i]['_activeHoldRequest'] != null ? Container(
                                      child: Row(
                                        children: [
                                          Container(
                                            width: 25, height: 25,
                                            decoration: BoxDecoration(image: DecorationImage(image: AssetImage('assets/image/general/Watch.png'), fit: BoxFit.cover)),
                                          ),
                                          SizedBox(width: 8),
                                          Text(Provider.of<HistoryModule>(context).dataMisi()[i]['_activeHoldRequest']['description'], style: TextStyle(color: textColor, fontSize: 14))
                                        ],
                                      ),
                                    ) : !Provider.of<HistoryModule>(context).dataMisi()[i]['autoResponse'] && Provider.of<HistoryModule>(context).dataMisi()[i]['_hasForum'] && Provider.of<HistoryModule>(context).dataMisi()[i]['_forumMsg'] != null ? Container(
                                      width: double.infinity,
                                      margin: EdgeInsets.only(top: 16),
                                      child: Row(
                                        children: [
                                          FadeTransition(opacity: _animationController, child: U.iconsax('messages-3', color: primaryColor)),
                                          SizedBox(width: 8),
                                          Text('“${Provider.of<HistoryModule>(context).dataMisi()[i]['_forumMsg']}”', style: TextStyle(color: textColor.withValues(alpha: 0.75), fontSize: 14, fontStyle: FontStyle.italic))
                                        ],
                                      ),
                                    ) : Container(),
                                  ],
                                ),
                              ],
                            ),
                          )
                        ],
                      ),
                    ],
                  ),
                ),
                onTap: () => navigateTo(context, WebHistoryDetailPage(index: i)).then((val) {
                  val = val??false;
                  if(val) Provider.of<HistoryModule>(context, listen: false).cancelMisi(i);
                }),
              );
            }),
          ),
          !Provider.of<HistoryModule>(context).stopLoadHistory() || (Provider.of<HistoryModule>(context).isLoadHistory() && Provider.of<HistoryModule>(context).page() > 0)
              ? Container(margin: EdgeInsets.only(top: Provider.of<HistoryModule>(context).page() > 0 ? 0 : 50), child: loadingTemplate(() {},))
              : Provider.of<HistoryModule>(context).dataMisi().isEmpty && Provider.of<HistoryModule>(context).dataPending().isEmpty
              ? NoDataPage()
              : Container(),
        ],
      ),
    );
  }

  Widget doneFilter() {
    return Row(
      children: List.generate(hisFunc.doneList.length, (i) {
        return GestureDetector(
          child: Container(
            margin: EdgeInsets.only(right: 16),
            padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
            decoration: BoxDecoration(
                color: Provider.of<HistoryModule>(context).checkPressAttention(hisFunc.doneList[i]['value']) ? primaryColor : Color(0xffF2F8F7),
                border: Border.all(color: Provider.of<HistoryModule>(context).checkPressAttention(hisFunc.doneList[i]['value']) ? primaryColor : Color(0xffBEC1C1)),
                borderRadius: BorderRadius.all(Radius.circular(50))),
            child: Text(hisFunc.doneList[i]['title'], style: TextStyle(color: Provider.of<HistoryModule>(context).checkPressAttention(hisFunc.doneList[i]['value']) ? Colors.white : textColor, fontSize: 16)),
          ),
          onTap: () {
            if (!Provider.of<HistoryModule>(context, listen: false).isLoadHistory()) {
              if (Provider.of<HistoryModule>(context, listen: false).checkPressAttention(hisFunc.doneList[i]['value'])) {
                Provider.of<HistoryModule>(context, listen: false).setPressAttention(0);
                hisFunc.onRefresh(context);
              } else {
                Provider.of<HistoryModule>(context, listen: false).setPressAttention(hisFunc.doneList[i]['value']);
                hisFunc.onRefresh(context);
              }
            }
          },
        );
      }),
    );
  }

  Widget doneContainer() {
    return SingleChildScrollView(
      child: Column(
        children: [
          Column(
              children: List.generate(Provider.of<HistoryModule>(context).dataMisi().length, (i) {
                return GestureDetector(
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.all(15),
                    margin: EdgeInsets.only(bottom: 15),
                    decoration: BoxDecoration(color: Colors.white, border: Border.all(color: textColor.withValues(alpha: 0.15)), borderRadius: BorderRadius.all(Radius.circular(12))),
                    child: Column(
                      children: [
                        Row(
                          children: [
                            Text(convertDate(Provider.of<HistoryModule>(context).dataMisi()[i]['datetimeRequest'], context.locale.toString()), style: TextStyle(color: primaryColor, fontSize: 14)),
                            SizedBox(width: 15),
                            Expanded(
                              child: Text('ticketNumber'.tr()+': '+Provider.of<HistoryModule>(context).dataMisi()[i]['ticketNo'], style: TextStyle(color: textColor, fontSize: 14), overflow: TextOverflow.ellipsis),
                            ),
                            Provider.of<HistoryModule>(context).dataMisi()[i]['currentState'] == 'DISELESAIKAN' || Provider.of<HistoryModule>(context).dataMisi()[i]['currentState'] == 'TUNTAS' ? renderStatus('stateFinish'.tr(), primaryColor.withValues(alpha: 0.4)) : renderStatus('stateCancel'.tr(), Color(0xffD81010).withValues(alpha: 0.4))
                          ],
                        ),
                        SizedBox(height: 10),
                        divider(),
                        SizedBox(height: 10),
                        Row(
                          children: [
                            imageTiles(imageUrl: Provider.of<HistoryModule>(context).dataMisi()[i]['_requestImage'] ?? "null", width: 150, height: 120),
                            SizedBox(width: 25),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(Provider.of<HistoryModule>(context).dataMisi()[i][U.langColumn(context, 'requestGroupDescription')], style: TextStyle(color: textColor, fontSize: 16), overflow: TextOverflow.ellipsis),
                                  SizedBox(height: 10),
                                  Text(Provider.of<HistoryModule>(context).dataMisi()[i][U.langColumn(context, 'requestSubject')], style: TextStyle(color: textColor, fontWeight: FontWeight.w600), overflow: TextOverflow.ellipsis),
                                  SizedBox(height: 5),
                                  Text(Provider.of<HistoryModule>(context).dataMisi()[i][U.langColumn(context, '_subjectDescription')]??'', style: TextStyle(color: textColor), overflow: TextOverflow.ellipsis),
                                  dashed(top: 10, bottom: 10),
                                  renderRequested(Provider.of<HistoryModule>(context).dataMisi()[i]),
                                  Text('location'.tr()+': '+Provider.of<HistoryModule>(context).dataMisi()[i]['ipphoneExtLocation'], style: TextStyle(color: textColor, fontSize: 14), overflow: TextOverflow.ellipsis),
                                ],
                              ),
                            )
                          ],
                        ),
                        SizedBox(height: 10),
                        divider(),
                        SizedBox(height: 10),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            !Provider.of<HistoryModule>(context).dataMisi()[i]['autoResponse'] && Provider.of<HistoryModule>(context).dataMisi()[i]['servantIdentityStart'] != '#system' && (Provider.of<HistoryModule>(context).dataMisi()[i]['currentState'] == 'TUNTAS' || Provider.of<HistoryModule>(context).dataMisi()[i]['currentState'] == 'DISELESAIKAN') ? Container(
                              child: hisFunc.askForRate(Provider.of<HistoryModule>(context, listen: true).dataMisi()[i]) ? GestureDetector(
                                child: Container(
                                  padding: EdgeInsets.symmetric(vertical: 4, horizontal: 16),
                                  child: Text('rateReq'.tr(), style: TextStyle(color: secondaryColor, fontSize: 14), overflow: TextOverflow.ellipsis),
                                  decoration: BoxDecoration(color: Colors.white, border: Border.all(color: secondaryColor), borderRadius: BorderRadius.all(Radius.circular(50))),
                                ),
                                onTap: () {
                                  U.newServerVersion(1716279633) ? rateMissionNew(context, Provider.of<HistoryModule>(context, listen: false).dataMisi()[i], i) : rateMission(context, Provider.of<HistoryModule>(context, listen: false).dataMisi()[i], i);
                                },
                              ) : !hisFunc.isAutoResponse(Provider.of<HistoryModule>(context).dataMisi()[i]) ? Row(
                                children: [
                                  Image(image: AssetImage(rating[Provider.of<HistoryModule>(context).dataMisi()[i]['satisfactionRate'] - 1]['image'].toString()), width: 25),
                                  SizedBox(width: 5),
                                  Text(rating[Provider.of<HistoryModule>(context).dataMisi()[i]['satisfactionRate'] - 1]['label'].toString(), style: TextStyle(color: textColor, fontSize: 14), overflow: TextOverflow.ellipsis),
                                ],
                              ) : Container(),
                            ) : message(Provider.of<HistoryModule>(context).dataMisi()[i]['_hasForum'], Provider.of<HistoryModule>(context).dataMisi()[i]['_forumMsg'] ?? "null"),
                            GestureDetector(
                              child: Container(
                                padding: EdgeInsets.symmetric(vertical: 4, horizontal: 16),
                                child: Text('reqAgain'.tr(), style: TextStyle(color: primaryColor, fontSize: 14)),
                                decoration: BoxDecoration(color: Colors.white, border: Border.all(color: primaryColor), borderRadius: BorderRadius.all(Radius.circular(50))),
                              ),
                              onTap: () => hisFunc.requestAgainAction(context, i),
                            )
                          ],
                        ),
                      ],
                    ),
                  ),
                  onTap: () {
                    if (Provider.of<HistoryModule>(context, listen: false).multiSelectMode()) {
                      hisFunc.selectedController(context, i);
                    } else {
                      navigateTo(context, WebHistoryDetailPage(index: i));
                    }
                  },
                  onLongPress: () => hisFunc.selectedController(context, i),
                );
              })
          ),
          !Provider.of<HistoryModule>(context).stopLoadHistory() || (Provider.of<HistoryModule>(context).isLoadHistory() && Provider.of<HistoryModule>(context).page() > 0)
              ? Container(margin: EdgeInsets.only(top: Provider.of<HistoryModule>(context).page() > 0 ? 0 : 50), child: loadingTemplate(() {},))
              : Provider.of<HistoryModule>(context).dataMisi().length == 0 ? NoDataPage() : Container(),
        ],
      ),
    );
  }

  Widget renderRequested(list){
    if(list['receptionistId'] != null){
      var user = Provider.of<UserModule>(context, listen: false).user();
      if(user['roomAttendant'] && user['userId'] != list['informantUserId'] && user['userId'] == list['receptionistId']){
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('${'requestedFor'.tr()}: ${list['informantName']??'-'}' ,style: TextStyle(color: textColor, fontSize: 13), overflow: TextOverflow.ellipsis),
            SizedBox(height: 5),
          ],
        );
      }

      if(user['userId'] == list['informantUserId'] && user['userId'] != list['receptionistId']){
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('${'requestedBy'.tr()}: ${list['receptionistName']??''}' ,style: TextStyle(color: textColor, fontSize: 13), overflow: TextOverflow.ellipsis),
            SizedBox(height: 5),
          ],
        );
      }
    }

    return Container();
  }

  Widget message(bool _hasForum, String _forumMsg, {double top = 0}) {
    return _hasForum ? Container(
      margin: EdgeInsets.only(top: top),
      child: Row(
        children: [
          FadeTransition(opacity: _animationController, child: U.iconsax('messages-3', color: primaryColor)),
          SizedBox(width: 8),
          Text('“$_forumMsg”', style: TextStyle(color: textColor.withValues(alpha: 0.75), fontSize: 14, fontStyle: FontStyle.italic), overflow: TextOverflow.ellipsis),
        ],
      ),
    ) : Container();
  }

  renderStatus(text, color){
    return Container(
      padding: EdgeInsets.symmetric(vertical: 3, horizontal: 10),
      margin: EdgeInsets.only(left: 10),
      child: Text(text, style: TextStyle(fontSize: 12, color: textColor)),
      decoration: BoxDecoration(
        color: color, borderRadius: BorderRadius.all(Radius.circular(3))
      ),
    );
  }

  rateMission(BuildContext context, list, index) {
    showDialog(
      context: context,
        builder: (contexts) {
          int tempRating = 0;
          String description = '';
          return AlertDialog(
            backgroundColor: Colors.transparent,
            contentPadding: EdgeInsets.all(0),
            content: StatefulBuilder(
              builder: (contextt, setStates) {
                return Container(
                  decoration: BoxDecoration(color: secondaryColor, borderRadius: BorderRadius.all(Radius.circular(25))),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(list[U.langColumn(context, 'requestSubject')], style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w600)),
                            SizedBox(height: 4),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text('ticketNumber'.tr()+': '+list['ticketNo'], style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w300)),
                                Text(convertDate(list['datetimeRequest'], context.locale.toString()), style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w300)),
                              ],
                            ),
                          ],
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.fromLTRB(30, 15, 30, 15),
                        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(25))),
                        child: Column(
                          children: [
                            Text('satisfactionAsk'.tr(), style: TextStyle(fontSize: 16)),
                            SizedBox(height: 12),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: List.generate(rating.length, (i) {
                                return Expanded(
                                  child: GestureDetector(
                                    child: Image(
                                      image: AssetImage(rating[i]['image'].toString()),
                                      color: Colors.white.withValues(alpha: tempRating == rating[i]['key'] ? 1 : 0.3),
                                      colorBlendMode: BlendMode.modulate,
                                    ),
                                    // child: Icon(rating[i]['icon'] as IconData, color: tempRating == rating[i]['key']?rating[i]['color'] as Color:Colors.grey),
                                    onTap: () {
                                      setStates(() {
                                        tempRating = rating[i]['key'] as int;
                                        description = rating[i]['label'] as String;
                                      });
                                    },
                                  ),
                                );
                              }),
                            ),
                            SizedBox(height: 6),
                            Text(description, style: TextStyle(color: textColor, fontSize: 14, fontWeight: FontWeight.w300), textAlign: TextAlign.center),
                            SizedBox(height: 20),
                            Opacity(
                              opacity: tempRating > 0 ? 1 : 0,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Expanded(child: buttonTemplate(text: 'textCancel'.tr(), backgroundColor: Colors.black12, borderColor: Colors.black12, textColor: textColor, height: 40, action: (){
                                    navigateBack(contexts);
                                  })),
                                  SizedBox(width: 20),
                                  Expanded(child: buttonTemplate(text: 'save_rating'.tr(), backgroundColor: primaryColor, borderColor: primaryColor, height: 40, action: ()async{
                                    if (tempRating > 0) {
                                      var data = {"ticketNo": list['ticketNo'], "rateSatisfy": tempRating};

                                      var res = await ApiAuthProvider() .postData('/api/requestHistories/rateSatisfy', null, data, contexts);
                                      if (res != null) {
                                        Provider.of<HistoryModule>(context, listen: false).setSatisfaction(index, tempRating);
                                        navigateBack(contexts);
                                      }
                                    }
                                  }))
                                ],
                              ),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                );
              },
            ),
          );
        }
    );
  }

  rateMissionNew(BuildContext context, list, index) {
    String locale = context.locale.toString();

    showDialog(
        context: context,
        builder: (contexts) {
          int tempRating = 0;
          String description = '';
          String ratingAspect = '';
          TextEditingController controllerOptOther = new TextEditingController();
          List aspectList = list['_ratingAspect'+locale[0].toUpperCase()+locale[1]] != null && list['_ratingAspect'+locale[0].toUpperCase()+locale[1]].trim() != '' ? list['_ratingAspect'+locale[0].toUpperCase()+locale[1]].split(';') : [];
          if(aspectList.isNotEmpty){
            aspectList.add('OTHER_OPTION');
          }
          else{
            ratingAspect = 'OTHER_OPTION';
          }

          return AlertDialog(
            backgroundColor: Colors.transparent,
            contentPadding: EdgeInsets.all(0),
            content: StatefulBuilder(
              builder: (contextt, setStates) {
                return Container(
                  decoration: BoxDecoration(color: secondaryColor, borderRadius: BorderRadius.all(Radius.circular(25))),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(list[U.langColumn(context, 'requestSubject')], style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w600)),
                            SizedBox(height: 4),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text('ticketNumber'.tr()+': '+list['ticketNo'], style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w300)),
                                Text(convertDate(list['datetimeRequest'], context.locale.toString()), style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w300)),
                              ],
                            ),
                          ],
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.fromLTRB(30, 15, 30, 15),
                        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(25))),
                        child: Column(
                          children: [
                            Text('satisfactionAsk'.tr(), style: TextStyle(fontSize: 16)),
                            SizedBox(height: 12),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: List.generate(rating.length, (i) {
                                return Expanded(
                                  child: GestureDetector(
                                    child: Image(
                                      image: AssetImage(rating[i]['image'].toString()),
                                      color: Colors.white.withValues(alpha: tempRating == rating[i]['key'] ? 1 : 0.3),
                                      colorBlendMode: BlendMode.modulate,
                                    ),
                                    onTap: () {
                                      setStates(() {
                                        tempRating = rating[i]['key'] as int;
                                        description = rating[i]['label'] as String;
                                      });
                                    },
                                  ),
                                );
                              }),
                            ),
                            SizedBox(height: 6),
                            Text(description, style: TextStyle(color: textColor, fontSize: 14, fontWeight: FontWeight.w300), textAlign: TextAlign.center),
                            tempRating != 0 ? SizedBox(height: 20) : Container(),
                            tempRating != 0 ? separator() : Container(),
                            tempRating != 0 ? SizedBox(height: 20) : Container(),
                            tempRating != 0 ? Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text('whatMakesYou'.tr()+' '+description+'?', style: TextStyle(fontSize: 16)),
                                SizedBox(height: 12),
                                Wrap(
                                  runSpacing: 10, spacing: 10,
                                  children: List.generate(aspectList.length, (i){
                                    return GestureDetector(
                                      child: Container(
                                        padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                                        child: Text(aspectList[i]=='OTHER_OPTION'?'letMeWrite'.tr():aspectList[i], style: TextStyle(color: textColor)),
                                        decoration: BoxDecoration(
                                            color: aspectList[i] == ratingAspect ? primaryColor.withValues(alpha: 0.3) : Colors.white,
                                            border: Border.all(color: aspectList[i] == ratingAspect ? primaryColor : textColor),
                                            borderRadius: BorderRadius.all(Radius.circular(50))
                                        ),
                                      ),
                                      onTap: (){
                                        setStates(() {
                                          ratingAspect = ratingAspect == aspectList[i]?'':aspectList[i];
                                        });
                                      },
                                    );
                                  }),
                                ),
                                aspectList.isNotEmpty ? SizedBox(height: 10) : Container(),
                                ratingAspect == 'OTHER_OPTION' ? TextFormField(
                                  maxLines: 1, maxLength: 50,
                                  autofocus: true,
                                  controller: controllerOptOther,
                                  style: TextStyle(fontSize: 14, color: Colors.black),
                                  decoration: InputDecoration(
                                    counterText: '',
                                    counterStyle: TextStyle(fontSize: 0),
                                    hintText: 'writeHere'.tr(),
                                    hintStyle: TextStyle(color: textColor.withValues(alpha: 0.5), fontSize: 14),
                                    filled: true, fillColor: Colors.white,
                                    isDense: true,
                                    contentPadding: EdgeInsets.all(13),
                                    prefixIcon: Padding(padding: EdgeInsets.only(left: 13, right: 13), child: U.iconsax('edit-2', color: textColor, size: 22)),
                                    enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Color(0xff262626).withValues(alpha: 0.5))),
                                    focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: primaryColor)),
                                  ),
                                ) : Container(),
                              ],
                            ) : Container(),
                            tempRating != 0 ? SizedBox(height: 20) : Container(),
                            Opacity(
                              opacity: tempRating > 0 ? 1 : 0,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Expanded(child: buttonTemplate(text: 'textCancel'.tr(), backgroundColor: Colors.black12, borderColor: Colors.black12, textColor: textColor, height: 40, action: (){
                                    navigateBack(contexts);
                                  })),
                                  SizedBox(width: 20),
                                  Expanded(child: buttonTemplate(text: 'save_rating'.tr(), backgroundColor: primaryColor, borderColor: primaryColor, height: 40, action: ()async{
                                    if (tempRating > 0) {
                                      var data = {"ticketNo": list['ticketNo'], "rateSatisfy": tempRating};
                                      if(ratingAspect != 'OTHER_OPTION'){
                                        data['aspect'] = ratingAspect;
                                      }
                                      else if(ratingAspect == 'OTHER_OPTION' && controllerOptOther.text.isNotEmpty){
                                        data['aspect'] = controllerOptOther.text;
                                      }

                                      var res = await ApiAuthProvider() .postData('/api/requestHistories/rateSatisfy', null, data, contexts);
                                      if (res != null) {
                                        Provider.of<HistoryModule>(context, listen: false).setSatisfaction(index, tempRating);
                                        navigateBack(contexts);
                                      }
                                    }
                                  }))
                                ],
                              ),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                );
              },
            ),
          );
        }
    );
  }
}
