import 'dart:async';

import 'package:flutter/material.dart';
import 'package:odf/tools/home/home_model.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../../bean/company_bean.dart';
import '../../bean/update_bean.dart';
import '../../common/func.dart';
import '../../dialog/update_dialog.dart';
import '../machine/region_page.dart';

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late StreamSubscription subscription;
  final HomeModel _viewmodel = HomeModel();

  bool isLoad = false;

  List<CompanyBean> companyList = [];

  late UpdateBean updateBean;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    subscription = _viewmodel.streamController.stream.listen((event) {
      String code = event['code'];
      if (code.isNotEmpty) {
        switch (code) {
          case "getCompany":
            isLoad = true;
            companyList = event['data'];
            break;

          case "checkAppVersion":
            updateBean = event['data'];

            if (updateBean.needUpdate != null && updateBean.needUpdate!) {
              FunctionUtil.popDialog2(
                context,
                UpdateDialog(
                  downloadUrl: "${updateBean.downloadUrl}",
                ),
              );
            }

            break;
        }
      }
      setState(() {});
    });

    _viewmodel.getCompany();
    _viewmodel.odfPortsUnitType();
    _viewmodel.odfPortsBusinessType();
    getUpdate();
  }

  ///检查更新
  getUpdate() async {
    final info = await PackageInfo.fromPlatform();
    String version = info.version;

    print("版本:version==$version");
    _viewmodel.checkAppVersion(version);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    subscription.cancel();
    super.dispose();
  }

  // 下拉刷新数据
  Future<void> _refreshData() async {
    _viewmodel.getCompany();
  }

  @override
  Widget build(BuildContext context) {
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    final size = MediaQuery.of(context).size;
    final t10 = size.width / 36;
    final s20 = size.width / 18;
    final h35 = size.width / 10.285714285714;
    final l16 = size.width / 22.5;
    final w18 = size.width / 20;
    final l11 = size.width / 32.727272727272;
    final s14 = size.width / 25.714285714285;

    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
            image: DecorationImage(
          image: AssetImage('assets/images/home_bg.png'),
          fit: BoxFit.cover,
        )),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              margin: EdgeInsets.only(top: statusBarHeight + t10, left: l16, right: l16),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  ///刷新
                  GestureDetector(
                    onTap: () {
                      _refreshData();
                    },
                    child: Image(
                      width: w18,
                      image: const AssetImage('assets/images/ic_refresh.png'),
                    ),
                  ),

                  GestureDetector(
                    onTap: () {},
                    child: Container(
                      alignment: Alignment.center,
                      child: Text(
                        '公司列表',
                        style: TextStyle(fontSize: s20, fontWeight: FontWeight.w600),
                      ),
                    ),
                  ),

                  ///设置
                  GestureDetector(
                    onTap: () {
                      Navigator.pushNamed(context, '/SetPage');
                    },
                    child: Image(
                      width: w18,
                      image: const AssetImage('assets/images/ic_set.png'),
                    ),
                  ),
                ],
              ),
            ),

            ///搜索
            GestureDetector(
              onTap: () {
                Navigator.pushNamed(context, "/SearchPage");
              },
              child: Container(
                height: h35,
                margin: EdgeInsets.only(top: t10, left: l11, right: l11),
                decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border.all(width: 0.5, color: Colors.black12),
                  borderRadius: BorderRadius.all(Radius.circular(l16)),
                ),
                child: Row(
                  children: [
                    Container(
                      margin: EdgeInsets.only(left: t10),
                      child: Image(
                        width: l16,
                        image: const AssetImage('assets/images/ic_search.png'),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: s20),
                      child: Text(
                        "请输入要搜索的备注内容",
                        style: TextStyle(color: const Color(0xFF999999), fontSize: s14),
                      ),
                    )
                  ],
                ),
              ),
            ),
            isLoad
                ? Expanded(
                    child: Container(
                      margin: EdgeInsets.only(top: s20, left: t10, right: t10),
                      child: RefreshIndicator(
                        color: const Color(0xFF1A73EC),
                        onRefresh: _refreshData,
                        child: ListView.builder(
                            itemCount: companyList.length,
                            padding: const EdgeInsets.all(0),
                            itemBuilder: (BuildContext context, int index) {
                              return _item(companyList[index], t10, s20);
                            }),
                      ),
                    ),
                  )
                : Container()
          ],
        ),
      ),
    );
  }

  _item(CompanyBean data, t10, t20) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => ReginPage(
              deptId: '${data.deptId}',
            ),
          ),
        );
      },
      child: Container(
        margin: EdgeInsets.only(bottom: t10),
        child: Card(
          color: Colors.white,
          child: Container(
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.only(left: t20, top: t20, bottom: t20),
            child: Text("${data.deptName}"),
          ),
        ),
      ),
    );
  }
}
