import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:zhiying_base_widget/pages/orders_page/models/order_filter_model.dart';
import 'package:zhiying_base_widget/pages/orders_page/models/order_page_item_style_model.dart';
import 'package:zhiying_base_widget/pages/orders_page/models/order_page_style_model.dart';
import 'package:zhiying_base_widget/widgets/others/action_date_alert/action_date_alert.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class OrderFilterWidget extends StatefulWidget {
  final OrderPageStyleModel style;
  final OrderFilterModel filterModel;

  final VoidCallback onDismiss;
  final ValueChanged<OrderFilterModel> onConfirm;
  final ValueChanged<OrderFilterModel> onReset;

  const OrderFilterWidget(
    this.style,
    this.filterModel, {
    Key key,
    this.onDismiss,
    this.onConfirm,
    this.onReset,
  }) : super(key: key);

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

class _OrderFilterWidgetState extends State<OrderFilterWidget> {
  int _currentProvider = 0; //订单来源
  int _currentType = 0; // 订单类型
  int _startTime = 0; // 起始时间
  int _endTime = 0; // 结束时间

  @override
  void initState() {
    if (widget?.filterModel?.provider != null &&
        widget.filterModel.provider != '') {
      List<OrderTypeModel> list = widget?.style?.filter?.providerType;
      for (int index = 0; index < list.length; index++) {
        if (list[index].type == widget.filterModel.provider) {
          _currentProvider = index;
          break;
        }
      }
    }

    if (widget?.filterModel?.type != null && widget.filterModel.type != '') {
      List<OrderTypeModel> list = widget?.style?.filter?.orderType;
      for (int index = 0; index < list.length; index++) {
        if (list[index].type == widget.filterModel.type) {
          _currentType = index;
          break;
        }
      }
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: widget.onDismiss,
      child: Container(
        width: double.infinity,
        height: double.infinity,
        color: Color(0x55555555),
        child: GestureDetector(
          onTap: () {},
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              _creteTitle(widget?.style?.filter?.providerTitle ?? ''),
              _createSources(),
              _creteTitle(widget?.style?.filter?.orderTitle ?? ''),
              _createType(),
              _creteTitle(widget?.style?.filter?.orderTimeTitle ?? ''),
              _creteTime(),
              Container(
                width: double.infinity,
                height: 0.5,
                color: Color(0xffe3e3e3),
              ),
              _createButtons(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _creteTitle(String title) {
    return Container(
      padding: EdgeInsets.only(left: 12.5, right: 12.5, top: 4, bottom: 4),
      width: double.infinity,
      color: Colors.white,
      child: Text(
        title,
        style: TextStyle(
            color: Color(0xff333333),
            fontSize: 14,
            fontWeight: FontWeight.bold),
      ),
    );
  }

  Widget _createSources() {
    return Container(
      width: double.infinity,
      padding:
          const EdgeInsets.only(left: 12.5, right: 12.5, bottom: 5, top: 5),
      color: Colors.white,
      child: Wrap(
        crossAxisAlignment: WrapCrossAlignment.start,
        spacing: 20,
        runSpacing: 10,
        children: List.generate(
            widget?.style?.filter?.providerType?.length ?? 0, (index) {
          return GestureDetector(
            onTap: () {
              setState(() {
                _currentProvider = index;
              });
            },
            child: _createTag(
                widget.style.filter.providerType[index].name ?? '',
                index == _currentProvider),
          );
        }).toList(),
      ),
    );
  }

  Widget _createType() {
    return Container(
      width: double.infinity,
      padding:
          const EdgeInsets.only(left: 12.5, right: 12.5, bottom: 5, top: 5),
      color: Colors.white,
      child: Wrap(
        crossAxisAlignment: WrapCrossAlignment.start,
        spacing: 20,
        runSpacing: 10,
        children: List.generate(widget?.style?.filter?.orderType?.length ?? 0,
            (index) {
          return GestureDetector(
            onTap: () {
              setState(() {
                _currentType = index;
              });
            },
            child: _createTag(widget.style.filter.orderType[index].name ?? '',
                _currentType == index),
          );
        }).toList(),
      ),
    );
  }

  Widget _createTag(String title, bool isSelected) {
    return Container(
      padding: EdgeInsets.only(left: 12, right: 12, top: 6, bottom: 6),
      decoration: BoxDecoration(
          color: isSelected
              ? HexColor.fromHex(widget?.style?.appActivateColor ?? '#ff4242')
              : Color(0xfff1f1f1),
          borderRadius: BorderRadius.circular(5)),
      child: Text(
        title ?? '',
        style: TextStyle(
            fontSize: 12, color: isSelected ? Colors.white : Color(0xff999999)),
      ),
    );
  }

  Widget _createButtons() {
    return Container(
      height: 54,
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(12.5),
          bottomRight: Radius.circular(12.5),
        ),
      ),
      child: Row(
        children: <Widget>[
          Expanded(
            child: GestureDetector(
              onTap: () {
                Logger.debug('重置');
                _resetFilter();
              },
              child: Container(
                color: Colors.transparent,
                child: Center(
                  child: Text(
                    '重置',
                    style: TextStyle(fontSize: 15, color: Color(0xff999999)),
                  ),
                ),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 12, bottom: 12),
            height: double.infinity,
            width: 0.5,
            color: Color(0xffe3e3e3),
          ),
          Expanded(
            child: GestureDetector(
              onTap: () {
                Logger.debug('确定');
                _confirmFilter();
              },
              child: Container(
                color: Colors.transparent,
                child: Center(
                  child: Text(
                    '确定',
                    style: TextStyle(fontSize: 15, color: Colors.redAccent),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _creteTime() {
    var formatter = new DateFormat('yyyy-MM-dd');
    String starTime =
        formatter.format(DateTime.fromMillisecondsSinceEpoch(_startTime));
    if (_startTime == 0) {
      starTime = '不限';
    }

    String endTime =
        formatter.format(DateTime.fromMillisecondsSinceEpoch(_endTime));
    if (_endTime == 0) {
      endTime = '不限';
    }

    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 12, right: 12, top: 4, bottom: 20),
      child: Row(
        children: <Widget>[
          GestureDetector(
            child: Container(
              width: 125,
              height: 25,
              margin: EdgeInsets.only(right: 10),
              decoration: BoxDecoration(
                  color: Color(0xfff1f1f1),
                  borderRadius: BorderRadius.circular(5)),
              child: Center(
                child: Text(
                  starTime,
                  style: TextStyle(
                    fontSize: 12,
                    color: Color(0xff999999),
                  ),
                ),
              ),
            ),
            onTap: () {
              _selectStartDate();
            },
          ),
          Text(
            '至',
            style: TextStyle(
              fontSize: 12,
              color: Color(0xff999999),
            ),
          ),
          GestureDetector(
            child: Container(
              width: 125,
              height: 25,
              margin: EdgeInsets.only(left: 10),
              decoration: BoxDecoration(
                  color: Color(0xfff1f1f1),
                  borderRadius: BorderRadius.circular(5)),
              child: Center(
                child: Text(
                  endTime,
                  style: TextStyle(
                    fontSize: 12,
                    color: Color(0xff999999),
                  ),
                ),
              ),
            ),
            onTap: () {
              _selectEndDate();
            },
          ),
        ],
      ),
    );
  }

  void _selectStartDate() async {
    DateTime dateTime = await showModalBottomSheet(
        context: context,
        builder: (context) {
          return ActionDateAlert(
            title: '选择起始日期',
          );
        },
        isScrollControlled: false,
        backgroundColor: Colors.transparent);
    if (dateTime != null) {
      _startTime = dateTime.millisecondsSinceEpoch;
    }
    setState(() {});
  }

  void _selectEndDate() async {
    DateTime dateTime = await showModalBottomSheet(
        context: context,
        builder: (context) {
          return ActionDateAlert(
            title: '选择结束日期',
          );
        },
        isScrollControlled: false,
        backgroundColor: Colors.transparent);
    if (dateTime != null) {
      _endTime = dateTime.millisecondsSinceEpoch;
    }
    setState(() {});
  }

  // 确定筛选条件
  void _confirmFilter() {
    List<OrderTypeModel> list = widget?.style?.filter?.providerType ?? [];
    if (_currentProvider < list.length) {
      widget?.filterModel?.provider = list[_currentProvider].type;
    }
    List<OrderTypeModel> types = widget?.style?.filter?.orderType ?? [];
    if (_currentType < types.length) {
      widget?.filterModel?.type = types[_currentType].type;
    }

    var formatter = new DateFormat('yyyy-MM-dd');
    if (_startTime == 0) {
      widget.filterModel?.startTime = '';
    } else {
      String starTime =
          formatter.format(DateTime.fromMillisecondsSinceEpoch(_startTime));
      var sTime = DateTime.parse(starTime);
      var _intendtime = (sTime.millisecondsSinceEpoch / 1000).ceil(); //方法一
      Logger.debug('${_intendtime.toString()}');
      widget.filterModel?.startTime = _intendtime.toString();
    }

    if (_endTime == 0) {
      widget.filterModel?.endTime = '';
    } else {
      String endTime =
          formatter.format(DateTime.fromMillisecondsSinceEpoch(_endTime));
      var eTime = DateTime.parse('${endTime} 23:59:59');
      var _intendtime = (eTime.millisecondsSinceEpoch / 1000).ceil(); //方法一
      Logger.debug('${_intendtime.toString()}');
      widget.filterModel?.endTime = _intendtime.toString();
    }
    if (widget?.onConfirm != null) {
      widget.onConfirm(widget.filterModel);
    }
  }

  void _resetFilter() {
    widget.filterModel?.type = '';
    widget.filterModel?.provider = '';
    widget.filterModel?.startTime = '';
    widget.filterModel?.endTime = '';
    _currentProvider = 0; //订单来源
    _currentType = 0; // 订单类型
    _startTime = 0; // 起始时间
    _endTime = 0; // 结束时间
    setState(() {});
    if (widget?.onReset != null) {
      widget.onReset(widget.filterModel);
    }
  }
}
