import 'dart:convert' show json;

import 'package:base/consts/color.dart';
import 'package:base/consts/share_prefers_key_const.dart';
import 'package:base/model/ContactInfo.dart';
import 'package:base/services/company_services.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../model/name_value.dart';

class MultySelContact extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MultySelContact();
  }
}

class _MultySelContact extends State<MultySelContact> {
  bool isAnimating = false;
  int pageIndex = 1;
  bool hasNext = true;
  List<ContractInfo> pageData = [];
  List<ContractInfo> tmpData = [];
  List<String> selDeptList = []; //获取选中的用户的Dept
  List<String> selUserList = []; //获取选中的用户
  List<String> selUserIdList = []; //获取选中的用户
  final EasyRefreshController _controllers = EasyRefreshController();
  String theme = '';

  @override
  Widget build(BuildContext context) {
    if (theme.isEmpty) {
      return const Scaffold(body: Text(''));
    }
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '执行人/部门选择',
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
      ),
      body: ModalProgressHUD(
        child: Container(
          color: Colors.white,
          child: EasyRefresh(
            enableControlFinishRefresh: false,
            enableControlFinishLoad: true,
            controller: _controllers,
            footer: MaterialFooter(),
            header: MaterialHeader(),
            child: ListView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemBuilder: (BuildContext context, int index) => NameItemWidget(pageData[index]),
              itemCount: pageData.length,
            ),
            onRefresh: () async {
              await Future.delayed(const Duration(seconds: 1), () {
                setState(() {});
              });
            },
            onLoad: () async {
              await Future.delayed(const Duration(seconds: 1), () {
                if (hasNext) {
                  setState(() {});
                }
              });
            },
          ),
        ),
        inAsyncCall: isAnimating,
        opacity: 0.7,
        progressIndicator: const CircularProgressIndicator(),
      ),
      persistentFooterButtons: <Widget>[
        Row(
          children: <Widget>[
            Container(
              width: MediaQuery.of(context).size.width - 20,
              child: MaterialButton(
                color: GetConfig.getColor(theme),
                height: 40,
                textColor: Colors.white,
                child: const Text('确定'),
                onPressed: () {
                  ///去除重复的部门
                  List<String> sigalList = [];
                  for (final String dept in mSel.selDeptList) {
                    if (!sigalList.contains(dept)) {
                      sigalList.add(dept);
                    }
                  }
                  var deptUserInfo = {
                    'uName': mSel.selUserList.join(','),
                    'uDept': sigalList.join(','),
                    'uIds': mSel.selUserIdList.join(',')
                  };
                  Navigator.pop(context, NameValue(json.encode(deptUserInfo), 0));
                },
              ),
            ),
          ],
        ),
      ],
      resizeToAvoidBottomPadding: false,
    );
  }

  @override
  void initState() {
    super.initState();
    getData();
    initConfig();
  }

  Future<void> getData() async {
    String orgCode = '';
    await SharedPreferences.getInstance().then((sp) {
      orgCode = json.decode(sp.getString(SharePrefersKey.companyModelKey))["sequenceNbr"].toString();
    }).then((data) {
      getContractInfo(orgCode).then((data) {
        if (mounted) {
          setState(() {
            pageData = data;
            tmpData = data;
            mSel.selUserIdList = [];
            mSel.selDeptList = [];
            mSel.selUserList = [];
          });
        }
      });
    });
  }

  Future<void> initConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        theme = preferences.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }
}

_MultySelContact mSel = _MultySelContact();

class NameItemWidget extends StatefulWidget {
  var bean;

  NameItemWidget(this.bean);

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

class _NameItemWidgetState extends State<NameItemWidget> {
  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: _buildItem(widget.bean),
    );
  }

  Widget _buildItem(var bean) {
    if (bean.type == 'user') {
      return ListTile(
        title: CheckboxListTile(
          value: bean.isSelected,
          onChanged: (bool) {
            setState(() {
              bean.isSelected = !bean.isSelected;
              //保存已选中的
              if (bean.isSelected) {
                mSel.selDeptList.add(bean.departmentName);
                if (!mSel.selUserList.contains(bean.name)) mSel.selUserList.add(bean.name);
                if (!mSel.selUserIdList.contains(bean.id)) mSel.selUserIdList.add(bean.id);
              } //删除
              else {
                if (mSel.selDeptList != null && mSel.selDeptList.contains(bean.departmentName)) {
                  mSel.selDeptList.remove(bean.departmentName);
                }
                if (mSel.selUserList != null && mSel.selUserList.contains(bean.name)) mSel.selUserList.remove(bean.name);
                if (mSel.selUserIdList != null && mSel.selUserIdList.contains(bean.id)) mSel.selUserIdList.remove(bean.id);
              }
            });
          },
          title: Text(
            bean.name,
            style: const TextStyle(fontWeight: FontWeight.w500),
          ),
          controlAffinity: ListTileControlAffinity.platform,
          activeColor: Colors.green,
        ),
        onTap: () {},
      );
    }

    return ExpansionTile(
      // key: PageStorageKey<NameBean>(bean),
      title: Text(bean.name),
      children: bean.children.map<Widget>(_buildItem).toList(),
      leading: CircleAvatar(
        backgroundColor: Colors.green,
        child: Text(
          bean.name.substring(0, 1),
          style: const TextStyle(color: Colors.white),
        ),
      ),
    );
  }
}

