import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:zhiying_base_widget/widgets/search_result/goods_list/bloc/search_result_goods_list_bloc.dart';
import 'package:zhiying_base_widget/widgets/search_result/sort/model/search_result_sort_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';

///
/// 搜索结果页排序widget
///
class SearchResultSortWidget extends StatefulWidget {
  final Map<String, dynamic> data;
  SearchResultSortModel model;

  SearchResultSortWidget(this.data, {Key key}) : super(key: key) {
    try {
      model = SearchResultSortModel.fromJson(jsonDecode(data['data']));
    } catch (_) {}
  }

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

class _SearchResultSortWidgetState extends State<SearchResultSortWidget> {
  TextEditingController _startPriceEditingController;
  TextEditingController _endPriceEditingController;
  FocusNode _startPriceNode;
  FocusNode _endPriceNode;

  // 是否展开综合
  bool _isShowZh = false;
  bool _isShowSX = false;

  // 切换显示样式
  bool _isShowOneColumn = true;

  // 是否展开下拉选项
  bool _expand = false;

  /// 切换类型
  void _changeColumn() {
    setState(() => _isShowOneColumn = !_isShowOneColumn);
    BlocProvider.of<SearchResultGoodsListBloc>(context).add(SearchResultGoodsListChangeStyleEvent());
  }

  /// 选中综合
  void _onClickZhSort(List<SearchResultSortSelect> datas, SearchResultSortSelect model, SearchResultItemSort parent) {
    String arg = model?.query_args ?? '';
    String id = model?.id ?? '';
    parent.isSelect = true;
    model.isSelect = !model.isSelect;
    datas.forEach((item) {
      if (item.name != model.name) {
        item.isSelect = false;
      }
    });
    if (!EmptyUtil.isEmpty(id)) {
      BlocProvider.of<SearchResultGoodsListBloc>(context).add(SearchResultGoodsListSortEvent(id: id, args: arg));
    }
    setState(() {
      _expand = false;
      _isShowZh = false;
      _isShowSX = false;
    });
  }

  /// 选中补贴
  void _onClickBTSort(SearchResultItemSort model) {
    if (model.state == '0') {
      model.state = '1';
    } else if (model.state == '1') {
      model.state = '2';
    } else {
      model.state = '0';
    }

    SearchResultSortSelect item = model.state == '0' ? null : model.state == '1' ? model.select_list[0] : model.select_list[1];

    String arg = item?.query_args ?? '';
    String id = model.select_list[0].id;

    if (!EmptyUtil.isEmpty(id)) {
      // BlocProvider.of<SearchResultGoodsListBloc>(context).add(SearchResultGoodsListSortEvent(arg, id));
      BlocProvider.of<SearchResultGoodsListBloc>(context).add(SearchResultGoodsListSortEvent(id: id, args: arg));
    }
    setState(() {
      _expand = false;
      _isShowSX = false;
      _isShowZh = false;
    });
  }

  /// 选中优惠券
  void _onClickYHQSort(SearchResultItemSort data) {
    print('_onClickYHQSort');
    data.isSelect = !data.isSelect;
    SearchResultSortSelect model = data.isSelect ? data.select_list[0] : data.select_list[1];

    String arg = model?.query_args ?? '';
    String id = model?.id ?? '';
    if (!EmptyUtil.isEmpty(id)) {
      // BlocProvider.of<SearchResultGoodsListBloc>(context).add(SearchResultGoodsListSortEvent(arg, id));
      BlocProvider.of<SearchResultGoodsListBloc>(context).add(SearchResultGoodsListSortEvent(id: id, args: arg));
    }
    setState(() {
      _expand = false;
      _isShowSX = false;
      _isShowZh = false;
    });
  }

  /// 选中价格
  void _onClickSXPriceSort(SearchResultItemSort data, SearchResultSortSelect model) {
    print('走塞选');
    String arg; //model?.query_args ?? '';
    String id = model?.id ?? '';

    // is_start_price=0&is_end_price=9999999
    String startPriceStr = _startPriceEditingController?.text?.toString()?.trim() ?? '';
    String endPriceStr = _endPriceEditingController?.text?.toString()?.trim() ?? '';
    if (EmptyUtil.isEmpty(startPriceStr)) {
      Fluttertoast.showToast(msg: '请输入最低价格~');
      return;
    }
    if (EmptyUtil.isEmpty(endPriceStr)) {
      Fluttertoast.showToast(msg: '请输入最高价格~');
      return;
    }
    try {
      int starPrice = int.parse(startPriceStr);
      int endPrice = int.parse(endPriceStr);
      if (starPrice < endPrice) {
        arg = 'is_start_price=${starPrice}&is_end_price=${endPrice}';
        if (!EmptyUtil.isEmpty(id)) {
          // BlocProvider.of<SearchResultGoodsListBloc>(context).add(SearchResultGoodsListSortEvent(arg, id));
          model.isSelect = true;
          BlocProvider.of<SearchResultGoodsListBloc>(context).add(SearchResultGoodsListSortEvent(id: id, args: arg));
        }
      } else {
        Fluttertoast.showToast(msg: '最低价格不能大于等于最高价格~');
      }
    } catch (_) {}

    setState(() {
      _expand = false;
      _isShowSX = false;
      _isShowZh = false;
    });

    if (model.isSelect || data.select_list[0].isSelect) {
      data.isSelect = true;
    } else {
      data.isSelect = false;
    }
  }

  /// 自营
  void _onClickZYSort(SearchResultItemSort data, SearchResultSortSelect model) {
    String arg = model?.query_args ?? '';
    String id = model?.id ?? '';
    model.isSelect = !model.isSelect;
    if (!EmptyUtil.isEmpty(id)) {
      // BlocProvider.of<SearchResultGoodsListBloc>(context).add(SearchResultGoodsListSortEvent(arg, id));
      BlocProvider.of<SearchResultGoodsListBloc>(context).add(SearchResultGoodsListSortEvent(id: id, args: arg, remove: !model.isSelect));
    }
    setState(() {
      _expand = false;
      _isShowSX = false;
      _isShowZh = false;
    });

    if (model.isSelect || data.select_list[0].isSelect) {
      data.isSelect = true;
    } else {
      data.isSelect = false;
    }
  }

  /// 点击当前
  void _clickSortType(SearchResultItemSort model) {
    if (model.type == 'popup' || model.type == 'popup-filter') {
      setState(() {
        _expand = true;
        if (model.type == 'popup') {
          _isShowZh = true;
          _isShowSX = false;
        }
        if (model.type == 'popup-filter') {
          _isShowSX = true;
          _isShowZh = false;
        }
      });
    } else {
      /// 优惠券
      if (model.type == 'select') {
        _onClickYHQSort(model);
      }

      /// 三个选项
      if (model.type == 'sort') {
        _onClickBTSort(model);
      }
      _closeExpand();
    }
  }

  /// 关闭下拉框
  void _closeExpand() {
    setState(() {
      _expand = false;
    });
  }

  @override
  void initState() {
    _startPriceEditingController = TextEditingController();
    _endPriceEditingController = TextEditingController();
    _startPriceNode = FocusNode();
    _endPriceNode = FocusNode();
    super.initState();
  }

  @override
  void dispose() {
    _startPriceNode?.unfocus();
    _endPriceNode?.unfocus();
    _startPriceNode?.dispose();
    _endPriceNode?.dispose();
    _startPriceEditingController?.dispose();
    _endPriceEditingController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      // height: 41,
      width: double.infinity,
      // color: Colors.red,
      child: _getMainWidget(widget?.model),
    );
  }

  /// 主视图
  Widget _getMainWidget(SearchResultSortModel model) {
    return Column(
      children: <Widget>[
        /// 筛选栏
        Container(
          height: 41,
          width: double.infinity,
          color: Colors.white,
          padding: const EdgeInsets.only(left: 12.5, right: 12.5),
          child: Row(
            children: <Widget>[
              Expanded(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: _createSortListWidget(model),
                ),
              ),

              /// 切换按钮
              _getChangeIconWidget(model),
            ],
          ),
        ),

        /// 展开列表
        Visibility(
          visible: _expand,
          child: Expanded(
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () => _closeExpand(),
              child: Container(
                // height: double.infinity,
                width: double.infinity,
                decoration: BoxDecoration(
                  color: HexColor.fromHex('#33333333'),
                ),
                child: Visibility(
                  visible: _isShowSX,
                  replacement: _getZHWidget(model),
                  child: _getSXWidget(model),
                ),
              ),
            ),
          ),
        )
      ],
    );
  }

  /// ExpandedList 展开列表
  Widget _getZHWidget(SearchResultSortModel data) {
    List<SearchResultSortSelect> model;
    List<Widget> lists = [];
    int sort_list_length = data?.sort_list?.length ?? 0;
    SearchResultItemSort parentData;
    if (sort_list_length > 0) {
      data.sort_list.forEach((item) {
        if (item.type == 'popup') {
          model = item.select_list;
          parentData = item;
        }
      });

      for (int i = 0; i < model.length; i++) {
        var item = model[i];
        double borderRadius = (i == model.length - 1) ? 12.5 : 0;
        var padding = EdgeInsets.only(left: 12.5, right: 12.5, top: 10, bottom: (i == model.length - 1) ? 15 : 0);

        lists.add(GestureDetector(
          onTap: () => _onClickZhSort(model, item, parentData),
          child: Container(
            padding: padding,
            decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(width: 0, color: Colors.transparent),
                borderRadius: BorderRadius.only(
                  bottomRight: Radius.circular(borderRadius),
                  bottomLeft: Radius.circular(borderRadius),
                )),
            width: double.infinity,
            child: Text(
              item?.name ?? '',
              style: TextStyle(fontSize: 12, color: HexColor.fromHex(item.isSelect ? widget?.model?.text_select_color ?? '' : widget?.model?.text_no_select_color ?? '')),
            ),
          ),
        ));
      }
    } else {
      lists.add(Container(
        height: 1,
      ));
    }

    return Column(
      children: lists,
    );
  }

  /// 获取筛选列表
  Widget _getSXWidget(SearchResultSortModel data) {
    List<Widget> lists = [];
    List<SearchResultSortSelect> model;
    SearchResultItemSort parendData;
    int sort_list_length = data?.sort_list?.length ?? 0;
    if (sort_list_length > 0) {
      data.sort_list.forEach((item) {
        if (item.type == 'popup-filter') {
          model = item.select_list;
          parendData = item;
        }
      });

      int length = model?.length ?? 0;
      if (length > 0) {
        for (int i = 0; i < model.length; i++) {
          if (i == 0) {
            lists.add(Container(
              padding: const EdgeInsets.only(left: 12.5, right: 12.5, top: 10),
              decoration: BoxDecoration(color: Colors.white, border: Border.all(width: 0, color: Colors.white)),
              child: _getPriceBetweenWidget(parendData, model[0]),
            ));
          }
          if (i == 1) {
            lists.add(Container(
                padding: const EdgeInsets.only(left: 12.5, right: 12.5, top: 13, bottom: 15),
                decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border.all(width: 0, color: Colors.white),
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(12.5),
                      bottomRight: Radius.circular(12.5),
                    )),
                child: _getStoryType(parendData, model[1])));
          }
        }
      } else {
        lists.add(Container());
      }
    } else {
      lists.add(Container());
    }

    return Column(children: lists);
  }

  /// 价格区间
  Widget _getPriceBetweenWidget(SearchResultItemSort data, SearchResultSortSelect model) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Text(
          '价格区间（元）',
          style: TextStyle(fontSize: 14, color: HexColor.fromHex('#999999')),
        ),
        Row(
          children: <Widget>[
            /// 最低价格
            _getCustomTextField(
                controller: _startPriceEditingController, focusNode: _startPriceNode, hintText: '最低价格', hintTextColor: '#999999', onTap: (val) => _onClickSXPriceSort(data, model)),

            /// 文字 【至】
            Container(margin: const EdgeInsets.symmetric(horizontal: 8), child: Text('至', style: TextStyle(color: HexColor.fromHex('#999999'), fontSize: 14))),

            /// 最高价格
            _getCustomTextField(
                controller: _endPriceEditingController, focusNode: _endPriceNode, hintTextColor: '#999999', hintText: '最高价格', onTap: (val) => _onClickSXPriceSort(data, model)),
          ],
        ),
      ],
    );
  }

  /// 只看自营
  Widget _getStoryType(SearchResultItemSort data, SearchResultSortSelect model) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Text(
          '商家类型',
          style: TextStyle(color: HexColor.fromHex('#999999'), fontSize: 14),
        ),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () => _onClickZYSort(data, model),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 21, vertical: 8.5),
            child: Text(
              '只看自营',
              style: TextStyle(color: HexColor.fromHex(model?.isSelect ?? false ? '#FF4242' : '#999999'), fontSize: 12),
            ),
            decoration: BoxDecoration(
              border: Border.all(color: HexColor.fromHex(model?.isSelect ?? false ? '#FF4242' : '#E7E7E7'), width: 0.5),
              borderRadius: BorderRadius.circular(5),
            ),
          ),
        ),
      ],
    );
  }

  /// 输入框
  Widget _getCustomTextField({TextEditingController controller, FocusNode focusNode, String hintText, String hintTextColor, double radius = 5, ValueChanged<String> onTap}) {
    return Container(
      width: 90,
      height: 33.5,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: HexColor.fromHex('#F5F5F5'),
        borderRadius: BorderRadius.circular(radius),
      ),
      child: TextField(
        controller: controller,
        focusNode: focusNode,
        textInputAction: TextInputAction.search,
        textAlign: TextAlign.center,
        keyboardType: TextInputType.number,
        onSubmitted: onTap,
        decoration: InputDecoration(
            filled: true,
            fillColor: Colors.transparent,
            // contentPadding: const EdgeInsets.only(bottom: 6, left: ),
            border: InputBorder.none,
            focusedBorder: InputBorder.none,
            focusedErrorBorder: InputBorder.none,
            errorBorder: InputBorder.none,
            disabledBorder: InputBorder.none,
            enabledBorder: InputBorder.none,
            hintText: hintText,
            hintStyle: TextStyle(color: HexColor.fromHex(hintTextColor), fontSize: 12)),
      ),
    );
  }

  /// 自定义widget
  Widget _getCustomWidget(SearchResultItemSort model) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () => _clickSortType(model),
      child: Container(
        child: Row(
          children: <Widget>[
            Text(
              model?.name ?? '综合',
              style: TextStyle(
                color: HexColor.fromHex(
                   model.type != 'sort' ? model.isSelect ? widget?.model?.text_select_color ?? '#FF4242' : widget?.model?.text_no_select_color ?? '#333333' :
                       model.state == '0' ? '#333333' : '#FF4242'
                ),
                fontSize: 14,
              ),
            ),
            const SizedBox(width: 4),
            Container(
                width: 12,
                height: 12,
                alignment: Alignment.center,
                color: Colors.white,
                child: CachedNetworkImage(
                  imageUrl: model.type != 'sort'
                      ? model?.isSelect ?? false ? model?.icon_2 ?? '' : model?.icon_1 ?? ''
                      : model.state == '0' ? model.icon_1 : model.state == '1' ? model.icon_2 : model.state == '2' ? model.icon_3 : model.icon_1,
                  width: 12,
                ))
          ],
        ),
      ),
    );
  }

  /// 排序widget
  List<Widget> _createSortListWidget(SearchResultSortModel model) {
    List<Widget> list = [];
    int length = model?.sort_list?.length ?? 0;
    if (length > 0) {
      for (int i = 0; i < model.sort_list.length; i++) {
        SearchResultItemSort item = model.sort_list[i];
        list.add(_getCustomWidget(item));
      }
    }
    return list;
  }

  /// 切换icon
  Widget _getChangeIconWidget(SearchResultSortModel model) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () => _changeColumn(),
      child: Container(
        height: 25,
        width: 34,
        margin: const EdgeInsets.only(left: 5),
        padding: const EdgeInsets.only(left: 9),
        decoration: BoxDecoration(
            // color: Colors.yellowAccent,
            border: Border(
          left: BorderSide(color: HexColor.fromHex('#C9C5C5'), width: 0.5),
        )),
        alignment: Alignment.center,
        child: CachedNetworkImage(
          imageUrl: _isShowOneColumn ? model?.layout_icon_2 ?? '' : model?.layout_icon_1 ?? '',
          width: 12,
        ),
      ),
    );
  }
}
