import 'package:deus_app/common/event/RefreshMaintEdit.dart';
import 'package:deus_app/common/style/TitleBar.dart';
import 'package:deus_app/common/style/gsy_style.dart';
import 'package:deus_app/common/utils/ConstantString.dart';
import 'package:deus_app/common/utils/DioUtil.dart';
import 'package:deus_app/common/utils/ToastUtils.dart';
import 'package:deus_app/generated/json/maint_items_list_response_entity_helper.dart';
import 'package:deus_app/main.dart';
import 'package:deus_app/model/maint_items_list_response_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MaintJobSelect extends StatefulWidget {

  var id;

  @override
  State createState() {
    return _MaintlJobSelect(id);
  }
  MaintJobSelect({super.key, required this.id});
}

class _MaintlJobSelect extends State<MaintJobSelect> {

  var id;

  _MaintlJobSelect(this.id);

  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  int index = 1;

  List<MaintItemsListResponseDataList> patrolItemModelVOS = [];

  MaintItemsListResponseEntity jobEdit = MaintItemsListResponseEntity();

  @override
  void initState() {
    super.initState();
    patrolItemModel();
  }

  patrolItemModel() async {
    var result = await DioUtil().request('maintItems/app-list',
        method: DioMethod.post, data: {'index': index, 'size': 20});
    _refreshController.loadComplete();
    _refreshController.refreshCompleted();
    if (0 == result['code']) {
      setState(() {
        jobEdit = maintItemsListResponseEntityFromJson(
            MaintItemsListResponseEntity(), result);
        patrolItemModelVOS.clear();
        patrolItemModelVOS.addAll(jobEdit.data.xList);
      });
    } else {
      if (index > 1) {
        index--;
      }
      showToast(result['msg']);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: TitleBar().backAppbar("选择巡检项目"),
        backgroundColor: const Color(0xfff2f2f2),
        body: Stack(
          children: [
            Container(
                    child: SmartRefresher(
              enablePullDown: true,
              enablePullUp: true,
              header: WaterDropHeader(),
              footer: CustomFooter(
                builder: (BuildContext context, LoadStatus? mode) {
                  Widget body;
                  if (mode == LoadStatus.idle) {
                    body = Text("上拉加载");
                  } else if (mode == LoadStatus.loading) {
                    body = CupertinoActivityIndicator();
                  } else if (mode == LoadStatus.failed) {
                    body = Text("加载失败！点击重试！");
                  } else if (mode == LoadStatus.canLoading) {
                    body = Text("松手,加载更多!");
                  } else {
                    body = Text("没有更多数据了!");
                  }
                  return Container(
                    height: 55.0,
                    child: Center(child: body),
                  );
                },
              ),
              controller: _refreshController,
              onRefresh: _onRefresh,
              onLoading: _onLoading,
              child: ListView.builder(
                itemCount: patrolItemModelVOS.length,
                itemBuilder: (context, index) {
                  return _patrol_job_list(index);
                },
              ),
            )),
            Positioned(
              left: 0,
              right: 0,
              bottom:0,
              // flex: 7,
              child:SizedBox(
                height: 50,
                width: double.infinity,
                child: TextButton(
                  onPressed: () {
                    addItems();
                  },
                  style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all<Color>(
                        Color(0xFF4875EC)),
                    shape: MaterialStateProperty.all(
                        BeveledRectangleBorder(
                            borderRadius: BorderRadius.circular(0))),
                    foregroundColor:
                    MaterialStateProperty.all<Color>(Colors.white),
                    // padding: MaterialStateProperty.all(EdgeInsets.zero)
                  ),
                  child: const Text(ConstantString.save),
                ),
              ),
            )
          ],
        ));
  }

  void _onRefresh() async {
    if (mounted) {
      setState(() {
        index = 1;
        patrolItemModel();
      });
    }
  }

  void _onLoading() async {
    if (mounted) {
      setState(() {
        if (jobEdit.data.total > patrolItemModelVOS.length) {
          index++;
          patrolItemModel();
        } else {
          _refreshController.loadNoData();
        }
      });
    }
  }

  Widget _patrol_job_list(int index) {
    return Container(
        margin: EdgeInsets.only(top: 12, left: 10, right: 10),
        padding: EdgeInsets.only(top: 12, bottom: 10),
        color: Colors.white,
        child: ListTile(
          title: Column(
            children: [
              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(patrolItemModelVOS[index].name,
                        style: TextStyle(
                            fontSize: GSYConstant.middleTextWhiteSize,
                            fontWeight: FontWeight.bold)),
                    Checkbox(
                      value: patrolItemModelVOS[index].isCheck,
                      activeColor: Colors.blue,
                      onChanged: (bool? value) {
                        setState(() {
                          patrolItemModelVOS[index].isCheck=value!;
                        });
                      },
                    ),
                  ],
                ),

              ),
              Container(
                margin: const EdgeInsets.fromLTRB(0, 10.0, 0, 0),
                alignment: Alignment.centerLeft,
                child: Text(
                  patrolItemModelVOS[index].requirements,
                  style: GSYConstant.smallTextLight,
                ),
              ),
              const SizedBox(
                height: 5,
              ),
            ],
          ),
          onTap: () {
            // Navigator.push(
            //     context,
            //     MaterialPageRoute(
            //         builder: (context) =>
            //             PatrolJobAdd(responseData: patrolItemModelVOS[index], id: id,)));
          },
        ));
  }

  addItems() async {
    List<int>mList=[];
    for (var value in patrolItemModelVOS) {
      if(value.isCheck){
        mList.add(value.id);
      }
    }
    if(mList.isEmpty){
      showToast("请选择维保项目");
      return;
    }
    var result = await DioUtil().request('maintJob/addItems',
        method: DioMethod.post, data: {'jobId': id,'maintItemsIds':mList});
    if (result['code'] == 0) {
      setState(() {
        eventBus.fire(RefreshMaintEdit());
        Navigator.pop(context);
      });
    } else {
      showToast(result['msg']);
    }
  }

}
