/*
 * @Author: WuXiangNan
 * @Date: 2021-05-31 19:23:26
 * @LastEditors  : WuWei
 * @LastEditTime : 2022-01-19 10:00:17
 * @Description: 
 */
import 'package:business_package/src/models/community/community_data.dart';
import 'package:business_package/src/service/impl/business_service_impl.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class WisCheckBox extends StatefulWidget {
  WisCheckBox(
      {Key? key, this.selectedCommunities, this.projectNum, this.onChange})
      : super(key: key);
  final Map? selectedCommunities;
  final projectNum;
  final Function(Map selectedCommunities)? onChange;

  static Future<Map?> show(selectedCommunities, projectNum) async {
    Map ids = Map.from(selectedCommunities ?? {});

    return await WBottomModalUtil.show<Map>(
      WNavUtil.instance!.context!,
      plain: false,
      title: Text('项目筛选'),
      onConfirm: (_) {
        return WNavUtil.instance!.pop(ids);
      },
      onCancel: (_) => WNavUtil.instance!.pop(),
      bodyConstraints: BoxConstraints.tightFor(height: 444.pt),
      body: WisCheckBox(
        selectedCommunities: ids,
        projectNum: projectNum,
        onChange: (values) {
          return ids = values;
        },
      ),
    );
  }

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

class _WisCheckBoxState extends State<WisCheckBox> {
  // 全部小区项目
  List<CommunityData>? communityData = [];

  // 筛选的项目
  late Map communityIds;

  @override
  void initState() {
    communityIds = widget.selectedCommunities ?? {};
    super.initState();
    getCommunitiesByEntCode();
  }

  // 获取项目-小区
  Future getCommunitiesByEntCode() async {
    var res = await BusinessServiceImpl().getCommunities(
        {'entCode': WisStorageUtil.get(key: 'storage-loginInfo')['entCode']});
    communityData = res.data;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var colorScheme = WTheme.of(context).colorScheme;
    return ListView(
      children: [
        Wisdom.row(
          color: Color(0xFFF2F2F2),
          padding: EdgeInsets.all(10.pt),
          children: [
            WisText(
              '当前您被授权查看',
              color: colorScheme.minor,
            ),
            WisText(
              widget.projectNum.toString(),
              color: colorScheme.primary,
            ),
            WisText(
              '个项目数据',
              color: colorScheme.minor,
            ),
          ],
        ),
        Wisdom.row(
          color: Colors.white,
          children: [
            Wisdom(
              width: MediaQuery.of(context).size.width,
              child: Wisdom.column(
                  children: communityData!.map((data) {
                List dataIdList = [];
                // 初始化选项
                communityIds[data.companyId] =
                    communityIds[data.companyId] ?? [];
                data.communities!.forEach((e) {
                  if (communityIds[data.companyId].indexOf(e.communityId) !=
                      -1) {
                    e.isSelected = true;
                  }
                });
                if (communityIds[data.companyId].length ==
                    data.communities!.length) {
                  data.isSelected = true;
                }
                return Wisdom.column(
                  children: [
                    CheckboxListTile(
                      value: data.isSelected,
                      controlAffinity: ListTileControlAffinity.leading,
                      onChanged: (newValue) {
                        setState(() {
                          data.isSelected = newValue;
                          // 全选
                          data.communities!.forEach((element) {
                            element.isSelected = data.isSelected;
                            // 保存选中的小区id
                            if (element.isSelected!) {
                              dataIdList.add(element.communityId);
                              communityIds[data.companyId] = dataIdList;
                            } else {
                              dataIdList.remove(element.communityId);
                              communityIds[data.companyId] = dataIdList;
                            }
                          });
                        });
                      },
                      title: WisText(data.companyName!),
                    ),
                    Wisdom.column(
                      padding: EdgeInsets.only(left: 40.pt),
                      children: [..._buildCheckbox(data)],
                    )
                  ],
                );
              }).toList()),
            )
          ],
        )
      ],
    );
  }

  _buildCheckbox(CommunityData params) {
    return params.communities!.map((data) {
      return Wisdom.column(
        children: [
          CheckboxListTile(
            value: data.isSelected,
            controlAffinity: ListTileControlAffinity.leading,
            onChanged: (newValue) {
              setState(() {
                data.isSelected = newValue;
                // 保存选中的小区id
                if (data.isSelected!) {
                  communityIds[params.companyId].add(data.communityId);
                } else {
                  communityIds[params.companyId].remove(data.communityId);
                }
                if (communityIds[params.companyId].length !=
                    params.communities!.length) {
                  params.isSelected = false;
                } else {
                  params.isSelected = true;
                }
              });
            },
            title: WisText(data.communityName!),
          ),
        ],
      );
    }).toList();
  }
}
