import 'package:amos_flutter_ui/card/index.dart';
import 'package:amos_iot_login_tpl/amos_iot_login_tpl.dart';
import 'package:amos_iot_login_tpl/message/conf.dart';
import 'package:amos_iot_login_tpl/message/message_list.dart';
import 'package:amos_iot_login_tpl/message/message_list_item.dart';
import 'package:amos_iot_login_tpl/utils/EventBusUtil.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jcs_airport/entity/message.dart';
import 'package:jcs_airport/services/api.dart';
import 'package:jcs_airport/view/workBench/maintenance/maintenanceTask/task_detail.dart';
import './RichText.dart';
import 'WaitingTask.dart';
import 'dart:async';

///@Description     非领导首页 待办任务、消息通知卡片
///@author          helinlin
///@create          2021-11-17 13:46
class HomeMessageCard extends StatefulWidget {
  final MessageType type;
  final ValueChanged editMessageCount;

  const HomeMessageCard(this.type, {Key key, this.editMessageCount})
      : super(key: key);

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

class _HomeMessageCardState extends State<HomeMessageCard> {

  final List<Message> _messageList = <Message>[];


  @override
  void initState() {
    super.initState();
    // getMessage();
    // API.msgList({
    //   'current': 0,
    //   'size': 10,
    //   'terminal': 'APP',
    //   'category': widget.type == MessageType.Task ? 0 : 1
    // }).then((value) {
    //   if (value['records'] != null) {
    //     setState(() {
    //       value['records'].forEach((item) {
    //         _messageList.add(Message.fromJson(item));
    //       });
    //     });
    //     if (widget.type == MessageType.Message) {
    //       widget.editMessageCount(value['total']);
    //     }
    //   }
    // });
  }

  @override
  Widget build(BuildContext context) {
    return CommonCard(
      child: Padding(
        padding: const EdgeInsets.only(right: 8, left: 8, top: 8),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                    child: Text(
                  widget.type == MessageType.Message ? '消息通知' : '待办任务',
                  style: const TextStyle(fontSize: 15),
                )),
                InkWell(
                  onTap: () {
                    widget.type == MessageType.Message
                        ? EventBusUtil.getInstance().fire(EventFn(2))
                        : Get.to(const WaitingTask()).then((value){
                      API.msgList({
                        'current': 0,
                        'size': 10,
                        'terminal': 'APP',
                        'category': widget.type == MessageType.Task ? 0 : 1
                      }).then((value) {
                        if (value['records'] != null) {
                          setState(() {
                            value['records'].forEach((item) {
                              _messageList.add(Message.fromJson(item));
                            });
                          });
                          if (widget.type == MessageType.Message) {
                            widget.editMessageCount(value['total']);
                          }
                        }
                      });
                    });
                  },
                  child: Opacity(
                      opacity: 0.6,
                      child: Row(
                        children: const [
                          Text(
                            '更多',
                            style: TextStyle(fontSize: 13),
                          ),
                          Icon(
                            Icons.chevron_right,
                            size: 18,
                          )
                        ],
                      )),
                )
              ],
            ),
            const Divider(
              color: Colors.black,
              height: 15,
              thickness: 0.1,
            ),
            ListView.builder(
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                //只显示5条
                itemCount: _messageList.length > 3 ? 3 : _messageList.length,
                itemBuilder: (BuildContext context, int index) {
                  return InkWell(
                    onTap: () async {
                      Map<String, dynamic> data = _messageList[index].toJson();
                      var id = data['extras']['planTaskDetailId'];
                      var routePointId = data['extras']['routePointId'];
                      var msgType = data['msgType'];
                      if (msgType == 'maintenance') {
                        var result = await API.inquirePoint(id);
                        // print(result);
                        // print('result11');

                        Get.to(TaskDetail(id, routePointId, result));
                      }else {
                        ListViewItem.linkRoute(context, data);
                      }
                    },
                    child: Column(
                      children: [
                        Padding(
                          padding: const EdgeInsets.all(0.0),
                          child: Row(
                            children: [
                              Padding(
                                padding:
                                    const EdgeInsets.only(left: 10, right: 20),
                                child: Image.asset(
                                  imgMap[_messageList[index].msgType] ??
                                      'assets/images/car_default.png',
                                  width: 32,
                                ),
                              ),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      children: [
                                        Expanded(
                                            child:_messageList[index].body!=null ?RichText1(content:_messageList[index].body):const Text(''))
                                      ],
                                    ),
                                    const SizedBox(
                                      height: 4,
                                    ),
                                    Opacity(
                                        opacity: 0.6,
                                        child: Row(
                                          children: [
                                            Expanded(
                                                child: Text(
                                              _messageList[index].msgTypeName ??
                                                  '',
                                              style:
                                                  const TextStyle(fontSize: 13),
                                              overflow: TextOverflow.ellipsis,
                                            )),
                                            Text(
                                              _messageList[index].sendTime ??
                                                  '',
                                              style:
                                                  const TextStyle(fontSize: 13),
                                              overflow: TextOverflow.ellipsis,
                                            )
                                          ],
                                        )),
                                  ],
                                ),
                              )
                            ],
                          ),
                        ),
                        const Divider(
                          color: Colors.black,
                          thickness: 0.1,
                        )
                      ],
                    ),
                  );
                })
          ],
        ),
      ),
    );
  }

  ///获取消息
  void getMessage() {
    var timer = null;
    timer=Timer.periodic(
        const Duration(milliseconds: 30000),(timer) {
      API.msgList({
        'current': 0,
        'size': 10,
        'terminal': 'APP',
        'category': widget.type == MessageType.Task ? 0 : 1
      }).then((value) {
        if (value['records'] != null) {
          setState(() {
            value['records'].forEach((item) {
              _messageList.add(Message.fromJson(item));
            });
          });
          if (widget.type == MessageType.Message) {
            widget.editMessageCount(value['total']);
          }
        }
      }).catchError((Object obj) {
        timer.cancel();
      });;
    });
  }
}
