import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:liftmanager/internal/maintenance/maintenance_router.dart';
import 'package:liftmanager/internal/maintenance/model/maintenance_detail_item.dart';
import 'package:liftmanager/internal/maintenance/model/maintenance_list_entity.dart';
import 'package:liftmanager/internal/maintenance/model/maintenance_options_item.dart';
import 'package:liftmanager/internal/maintenance/provider/maintenance_detail_page_provider.dart';
import 'package:liftmanager/internal/maintenance/widgets/maintenance_options.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/click_item.dart';
import 'package:liftmanager/widgets/selected_image.dart';
import 'package:liftmanager/widgets/star_item.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart' as p;

class MaintenanceDetailPage extends StatefulWidget {
  MaintenanceDetailPage(this.item);

  final MaintenanceListItem item;

  @override
  State<StatefulWidget> createState() {
    return MaintenanceDetailPageState();
  }
}

class MaintenanceDetailPageState extends State<MaintenanceDetailPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  List<Map> tabs = [
    {"id": 0, "name": "机房"},
    {"id": 1, "name": "轿顶"},
    {"id": 2, "name": "轿厢"},
    {"id": 3, "name": "层门"},
    {"id": 4, "name": "底坑井道"},
//    {"id": 5, "name": "评价"}
  ];
  MaintenanceDetailPageProvider provider = MaintenanceDetailPageProvider();

  TabController _tabController;
  PageController _pageController = PageController(initialPage: 0);
  TextEditingController _controller = TextEditingController();
  TextEditingController _controller2 = TextEditingController();
  MaintenanceDetailEntity item = MaintenanceDetailEntity();
  List<File> images = [];

  var mainSignImgByte;
  var mainSignImgByte2;
  Image mainSignImg = Image.asset(
    "assets/images/img_sign.png",
    width: 80,
    height: 80,
  );
  Image secondSign = Image.asset(
    "assets/images/img_sign.png",
    width: 80,
    height: 80,
  );

  @override
  void initState() {
    super.initState();
    tabs = [
      {"id": 0, "name": widget.item.category > 3 ? "第一页" : "机房"},
      {"id": 1, "name": widget.item.category > 3 ? "第二页" : "轿顶"},
      {"id": 2, "name": widget.item.category > 3 ? "第三页" : "轿厢"},
      {"id": 3, "name": widget.item.category > 3 ? "第四页" : "层门"},
      {"id": 4, "name": widget.item.category > 3 ? "第五页" : "底坑井道"}
    ];
    if (widget.item.hasEvaluate == "1") {
      tabs.add({"id": 5, "name": "评价"});
    }
    _tabController = new TabController(vsync: this, length: tabs.length);
    _getDetail();
  }

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

  _onPageChange(int index) {
    _tabController.animateTo(index);
    provider.setIndex(index);
  }

  Future _getDetail() async {
    ApiService(context: context).maintenanceRecordDetail(widget.item.recordId,
        onSuccess: (data) {
      item = data;
      _getOptions();
      setState(() {});
    }, onError: (code, msg) {
      showToast(msg);
    });
  }

  Future _getOptions() async {
    ApiService(context: context)
        .maintenanceOptions(widget.item.maintenanceType, item.category,
            onSuccess: (List<MaintenanceOptionsItem> datas) {
      initOptions(datas);
      setState(() {});
    }, onError: (code, msg) {
      showToast(msg);
    });
  }

  ///初始化维保项
  void initOptions(List<MaintenanceOptionsItem> datas) {
    Map<String, int> map = item.getMaintenanceOptionArr();
    Map<int, List<MaintenanceOptionsItem>> _optionsMap = {
      1: [],
      2: [],
      3: [],
      4: [],
      5: []
    };
    if (widget.item.category < 4) {
      for (var i = 0; i < datas.length; ++i) {
        var item = datas[i];
        item.status = map[item.id] ?? 0;
        if ([1, 2, 3, 4, 5].contains(item.sort)) {
          if (datas[item.sort] == null) _optionsMap[item.sort] = [];
          _optionsMap[item.sort].add(item);
          provider.setOptions(_optionsMap);
        }
      }
    } else {
      for (var i = 0; i < datas.length; ++i) {
        var item = datas[i];
        item.status = map[item.id] ?? 0;
        int length = datas.length ~/ 5 + 1;
        if (i < length) {
          _optionsMap[1].add(item);
          provider.setOptions(_optionsMap);
        } else if (i < length * 2) {
          _optionsMap[2].add(item);
          provider.setOptions(_optionsMap);
        } else if (i < length * 3) {
          _optionsMap[3].add(item);
          provider.setOptions(_optionsMap);
        } else if (i < length * 4) {
          _optionsMap[4].add(item);
          provider.setOptions(_optionsMap);
        } else if (i < length * 5) {
          _optionsMap[5].add(item);
          provider.setOptions(_optionsMap);
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return p.ChangeNotifierProvider<MaintenanceDetailPageProvider>(
        create: (_) => provider,
        child: Scaffold(
          appBar: MyAppBar(
            centerTitle: "日常保养",
//            actions: <Widget>[
//              FlatButton(
//                child: Text("保存", key: const Key('actionName')),
//                textColor: Colours.dark_text,
//                highlightColor: Colors.transparent,
//                onPressed: () {},
//              )
//            ],
          ),
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Row(
                children: <Widget>[
                  Expanded(
                      flex: 1,
                      child: Container(
                        // 隐藏点击效果
                        color: ThemeUtils.getTabsBg(context),
                        child: TabBar(
                            onTap: (index) {
                              if (!mounted) {
                                return;
                              }
                              _pageController.jumpToPage(index);
                            },
                            isScrollable: true,
                            controller: _tabController,
                            labelStyle: TextStyles.textBold18,
                            indicatorSize: TabBarIndicatorSize.label,
//                labelPadding: const EdgeInsets.only(left: 16.0),
                            unselectedLabelColor: Colours.text_gray,
                            labelColor: Theme.of(context).primaryColor,
                            indicatorPadding:
                                const EdgeInsets.only(left: 5.0, right: 5.0),
                            tabs: tabs.map((map) {
                              return _TabView("${map["name"]}", "", map["id"]);
                            }).toList()),
                      )),
                ],
              ),
              Gaps.line,
              Expanded(
                child: PageView.builder(
                  key: const Key('pageView'),
                  itemCount: tabs.length,
                  onPageChanged: _onPageChange,
                  controller: _pageController,
                  itemBuilder: (BuildContext context, int index) {
                    if (index == 5) {
                      _controller2.text = item.evaluation.advice;
                      return Container(
                          color: ThemeUtils.getBackgroundColor(context),
                          child: ListView(
//                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                StarItem(
                                  title: "服务态度",
                                  starRating:
                                      item.evaluation.serviceLevel.toDouble(),
                                ),
                                StarItem(
                                  title: "急修满意度",
                                  starRating:
                                      item.evaluation.starLevel.toDouble(),
                                ),
                                Gaps.vGap8,
                                ClickItem(title: "客户评价"),
                                Container(
                                  color: ThemeUtils.getTabsBg(context),
                                  child: Padding(
                                    padding: const EdgeInsets.only(
                                        top: 5,
                                        left: 15.0,
                                        right: 15.0,
                                        bottom: 8.0),
                                    child: TextField(
                                        enabled: false,
                                        maxLength: 100,
                                        maxLines: 8,
                                        autofocus: false,
                                        controller: _controller2,
                                        decoration: InputDecoration(
                                            hintText: "填写现场情况描述",
                                            border: InputBorder.none,
                                            hintStyle: TextStyles.textGray14)),
                                  ),
                                ),
                                SizedBox(
                                  height: 8,
                                ),
                                ClickItem(title: "客户手写签名", content: ""),
                                Container(
                                  height: 200,
                                  color: ThemeUtils.getTabsBg(context),
                                  alignment: Alignment.center,
                                  child: Stack(
                                    alignment: Alignment.center,
                                    children: <Widget>[
                                      Positioned(
                                        child: Text(
                                          "手写签名",
                                          style: TextStyle(
                                              fontSize: 12,
                                              color: Colours.text_gray_c),
                                        ),
                                      ),
                                      Image.network(
                                        "${item.evaluation.imgUrl}",
                                        width: 150,
                                        height: 150,
                                        fit: BoxFit.fill,
                                      ),
                                    ],
                                  ),
                                ),
                              ]));
                    } else if (index == 4) {
                      _controller.text = item.maintenanceAdvice;
                      return ListView(
                        children: <Widget>[
                          Container(
                              color: ThemeUtils.getBackgroundColor(context),
                              child: MaintenanceOptions(
                                index: index,
                                items: provider.optionsMap[index + 1],
                                type: widget.item.maintenanceType,
                                liftType: widget.item.liftType,
                              )),
                          Container(
                              color: ThemeUtils.getBackgroundColor(context),
                              child: uploadView()),

                          //                      child: MaintenanceOptions(index: index,items:_optionsMap[index+1],type: widget.type, liftType: widget.liftType,));
                        ],
                      );
                    } else {
                      return Container(
                          color: ThemeUtils.getBackgroundColor(context),
                          child: MaintenanceOptions(
                            index: index,
                            items: provider.optionsMap[index + 1],
                            type: widget.item.maintenanceType,
                            liftType: widget.item.liftType,
                          ));
                    }
                  },
                ),
              )
            ],
          ),
        ));
  }

  ///第五页底部
  Widget uploadView() {
    bool isDark = ThemeUtils.isDark(context);
    return Container(
      padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          ClickItem(
            title: "计划日期",
            content: "${item.planDate}",
          ),
          ClickItem(
            title: "停梯时间",
            content: "${item.stopDate}",
          ),
          ClickItem(
            title: "恢复时间",
            content: "${item.recoveryDate}",
          ),


          ClickItem(
            title: "保养建议",
            hintText: "",
          ),
          Container(
            color: isDark ? Colours.dark_bg_gray : Colors.white,
            child: Padding(
              padding: const EdgeInsets.only(
                  top: 5, left: 15.0, right: 15.0, bottom: 8.0),
              child: TextField(
                  maxLength: 30,
                  maxLines: 3,

//                  autofocus: false,
                  enabled: false,
                  controller: _controller,
//                    keyboardType: widget.keyboardType,
                  //style: TextStyles.textDark14,
                  decoration: InputDecoration(
                      hintText: "${item.maintenanceAdvice}",
                      border: InputBorder.none,
                      hintStyle: TextStyles.textGray14)),
            ),
          ),
          ClickItem(
            title: "保养图片",
            hintText: "",
          ),
          Container(
              color: isDark ? Colours.dark_bg_gray : Colors.white,
              child: GridView.builder(
                shrinkWrap: true,
                padding: const EdgeInsets.fromLTRB(8.0, 12, 8.0, 12.0),
                physics: NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3, childAspectRatio: 1.18),
                itemCount: item.status == "2"
                    ? item.mtRecordImgs.length
                    : (images.length >= 9 ? 9 : images.length + 1),
                itemBuilder: (_, index) {
                  return Stack(
                    children: <Widget>[
                      Center(
                        child: item.status == "2"
                            ? GestureDetector(
                                onTap: () {
                                  NavigatorUtils.push(
                                      context,
                                      "${MaintenanceRouter.viewImage}?edit=0&img=" +
                                          Uri.encodeComponent(
                                              item.mtRecordImgs[index].imgUrl));
                                },
                                child: Image.network(
                                  "${item.mtRecordImgs[index].imgUrl}",
                                  width: 80,
                                  height: 80,
                                  fit: BoxFit.fill,
                                ))
                            : SelectedImage(
                                image: index < images.length
                                    ? images[index]
                                    : null,
                                onTap: () {}),
                      )
                    ],
                  );
                },
              )),
          SizedBox(
            height: 8,
          ),
          ClickItem(
            title: "负责人签名",
            hintText: "",
          ),
          Container(
              padding: EdgeInsets.all(15),
              color: isDark ? Colours.dark_bg_gray : Colors.white,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  GestureDetector(
                      onTap: () {},
                      child: Container(
                        color: Colors.white,
                        alignment: Alignment.center,
                        child: Stack(
                          alignment: Alignment.center,
                          children: <Widget>[
                            Positioned(
                                child: Text(
                              "主要维保人员",
                              style: TextStyle(
                                  fontSize: 12, color: Colours.text_gray_c),
                            )),
                            Image.network(
                              "${item.signatureImg1}",
                              width: 150,
                              height: 150,
                              fit: BoxFit.fill,
                            ),
                          ],
                        ),
                      )),
                  SizedBox(
                    width: 15,
                  ),
                  Offstage(
                      offstage: item.signatureImg2?.length == 0,
                      child: GestureDetector(
                          onTap: () {},
                          child: Container(
                            color: Colors.white,
                            alignment: Alignment.center,
                            child: Stack(
                              alignment: Alignment.center,
                              children: <Widget>[
                                Positioned(
                                    child: Text(
                                  "次要维保人员",
                                  style: TextStyle(
                                      fontSize: 12, color: Colours.text_gray_c),
                                )),
                                Image.network(
                                  "${item.signatureImg2}",
                                  width: 150,
                                  height: 150,
                                  fit: BoxFit.fill,
                                ),
                              ],
                            ),
                          )))
                ],
              ))
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class _TabView extends StatelessWidget {
  const _TabView(this.tabName, this.tabSub, this.index);

  final String tabName;
  final String tabSub;
  final int index;

  @override
  Widget build(BuildContext context) {
    return p.Consumer<MaintenanceDetailPageProvider>(
      builder: (_, provider, child) {
        return Tab(
            child: SizedBox(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                tabName,
                style: TextStyle(fontSize: 15),
              ),
              Offstage(
                  offstage: provider.index != index,
                  child: Padding(
                    padding: const EdgeInsets.only(top: 1.0),
                    child: Text(tabSub,
                        style: TextStyle(fontSize: Dimens.font_sp12)),
                  )),
            ],
          ),
        ));
      },
    );
  }
}
