///  jh_picker_tool.dart
///
///  Created by iotjin on 2020/02/17.
///  description:  底部选择器 包含日期，单列、多列文本

import 'package:account_center/common/utils/date_picker.dart';
import 'package:account_center/common/utils/picker/flutter_picker.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

const String _titleNormalText = '请选择';
const String _cancelText = '取消';
const String _confirmText = '确定';
const String _yearSuffix = '年';
const String _monthSuffix = '月';
const String _daySuffix = '日';
const List<String> _strAMPM = ['上午', '下午'];
const double _kPickerHeight = 216.0;
const double _kItemHeight = 50.0;
const double _kHeaderLineHeight = 0.25;
const double _kHeaderRadius = 10.0;
const double _kTitleFontSize = 18.0;
const double _kBtnFontSize = 17.0;
const double _selectTextFontSize = 20.0;

/// 选择回调
/// 单列选择器返回选中行对象和index
/// 多列选择器返回选中行对象数组和index数组
/// 时间选择器返回选中行时间（时间格式：2022-07-03 15:00:46）和index数组
typedef _ClickCallBack = void Function(
    dynamic selectValue, dynamic selectIndexArr);

enum PickerDateType {
  YMD, // y, m, d
  YM, // y ,m
  YMD_HM, // y, m, d, hh, mm
}

enum PickerType {
  String,
  Array,
  Date,
}

class PickerTool {
  /// 单列
  static void showStringPicker<T>(
    BuildContext context, {
    required List data,
    String? title,
    String? labelKey, // 对象数组的文字字段
    String Function(dynamic data)? titleBuilder,
    int selectIndex = 0,
    @required _ClickCallBack? clickCallBack,
  }) {
    if (data.isEmpty) {
      return;
    }

    PickerDataAdapter adapter;
    if (labelKey != null) {
      adapter =
          PickerDataAdapter(pickerdata: data.map((e) => e[labelKey]).toList());
    } else if (titleBuilder != null) {
      adapter = PickerDataAdapter(
          pickerdata: data.map<String>(titleBuilder).toList());
    } else {
      adapter = PickerDataAdapter(pickerdata: data);
    }

    _showPicker(
      context,
      data: data,
      title: title,
      selecteds: [selectIndex],
      pickerType: PickerType.String,
      adapter: adapter,
      clickCallBack: clickCallBack,
    );
  }

  /// 多列
  static void showArrayPicker<T>(
    BuildContext context, {
    required List data,
    String? title,
    String? labelKey, // 对象数组的文字字段
    List<int>? selectIndex,
    required _ClickCallBack clickCallBack,
  }) {
    if (data.length <= 0) {
      return;
    }
    _showPicker(
      context,
      data: data,
      title: title,
      selecteds: selectIndex,
      pickerType: PickerType.Array,
      adapter: labelKey != null
          ? PickerDataAdapter(
              pickerdata: data.map((e) {
                return e.map((e2) => e2[labelKey]).toList();
              }).toList(),
              isArray: true)
          : PickerDataAdapter(pickerdata: data, isArray: true),
      clickCallBack: clickCallBack,
    );
  }

  /// 日期选择器
  static void showDatePicker(
    BuildContext context, {
    String? title,
    PickerDateType? dateType,
    DateTime? maxTime,
    DateTime? minTime,
    DateTime? selectTime,
    required Function(DateTime select)? onConfirm,
  }) {
    DateType timeType;
    if (dateType == PickerDateType.YM) {
      timeType = DateType.YM;
    } else if (dateType == PickerDateType.YMD_HM) {
      timeType = DateType.YMD_HM;
    } else {
      timeType = DateType.YMD;
    }

    Get.bottomSheet(
      DatePicker(
          title: title ?? '请选择',
          selectData: selectTime,
          minValue: minTime,
          maxValue: maxTime,
          type: timeType,
          onConfirm),
    );
  }
}

/// 自定义picker
_showPicker(
  context, {
  List? data,
  String? title,
  List<int>? selecteds,
  PickerType? pickerType,
  required PickerAdapter adapter,
  _ClickCallBack? clickCallBack,
}) {
  // 默认颜色
  var bgColor = Colors.white;
  var headerColor = Colors.white;
  var kHeaderLineColor = Color(0xFFE6E6E6);
  var titleColor = Color(0xFF787878);
  var btnColor = Color(0xFF333333);
  var selectTextColor = Color(0xFF333333);
  var selectItemBgColor = Colors.grey.withOpacity(0.15);

  var picker = Picker(
      adapter: adapter,
      selecteds: selecteds,
      height: _kPickerHeight,
      itemExtent: _kItemHeight,
      title: Text(title ?? _titleNormalText,
          style: TextStyle(color: titleColor, fontSize: _kTitleFontSize)),
      cancelText: _cancelText,
      cancelTextStyle: TextStyle(color: btnColor, fontSize: _kBtnFontSize),
      confirmText: _confirmText,
      confirmTextStyle: TextStyle(color: btnColor, fontSize: _kBtnFontSize),
      textAlign: TextAlign.center,
      selectedTextStyle:
          TextStyle(color: selectTextColor, fontSize: _selectTextFontSize),
      selectionOverlay:
          Container(height: _kItemHeight, color: selectItemBgColor),
      backgroundColor: bgColor,
      headerDecoration: BoxDecoration(
        border: Border(
          bottom:
              BorderSide(color: kHeaderLineColor, width: _kHeaderLineHeight),
        ),
      ),
      onConfirm: (Picker picker, List selectIndexArr) {
        if (pickerType == PickerType.String) {
          var selectIndex = selectIndexArr[0];
          clickCallBack?.call(data![selectIndex], selectIndex);
        }
        if (pickerType == PickerType.Array) {
          var selectItemArr = [];
          for (int i = 0; i < selectIndexArr.length; i++) {
            int j = selectIndexArr[i];
            selectItemArr.add(data![i][j]);
          }
          clickCallBack?.call(selectItemArr, selectIndexArr);
        }
        if (pickerType == PickerType.Date) {
          // var time = (picker.adapter as DateTimePickerAdapter).value;
          clickCallBack?.call(
              picker.adapter.text.split('.')[0], selectIndexArr);
        }
      });

  picker.showModal(context, backgroundColor: Colors.transparent,
      builder: (context, view) {
    return Material(
        color: headerColor,
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(_kHeaderRadius),
            topRight: Radius.circular(_kHeaderRadius)),
        child: Container(
          padding: EdgeInsets.only(top: 5),
          child: view,
        ));
  });
}
