import 'package:account_center/account_center.dart';
import 'package:account_center/common/sp/sp_util.dart';
import 'package:account_center/common/utils/alert_util.dart';
import 'package:account_center/common/utils/picker_tool.dart';
import 'package:account_center/page/account_company/company_auth/widget/common/comapny_http.dart';
import 'package:account_center/page/account_company/company_auth/widget/common/gesture_tap.dart';
import 'package:account_center/style/style_params.dart';
import 'package:flutter/material.dart';

import '../../company_auth/widget/common/company_define.dart';

class HistoryScreen extends StatefulWidget {
  final dynamic stampInfo;
  final String? startTime;
  final String? endTime;
  final String? serviceCode;
  final StampScreenBlock? stampScreenBlock;
  final bool showName;
  const HistoryScreen(
      {super.key,
      this.startTime,
      this.endTime,
      this.serviceCode,
      this.stampInfo,
      this.stampScreenBlock,
      this.showName = true});

  @override
  State<StatefulWidget> createState() {
    return _HistoryScreen();
  }
}

class _HistoryScreen extends State<HistoryScreen> {
  dynamic stampInfo;
  DateTime? starTime;
  DateTime? endTime;
  String? serviceCode;

  List dataSource = [];

  @override
  void initState() {
    _reset();
    super.initState();
    if (widget.showName) {
      _getStampList();
    }
  }

  void _reset() {
    stampInfo = widget.stampInfo;
    starTime = widget.startTime?.dateTime;
    endTime = widget.endTime?.dateTime;
    _controller.setContent(widget.serviceCode?.toString() ?? '');
  }

  void _getStampList() {
    CompanyHttps.listCompanySeal(
      getCompanyNo(),
      onSuccess: (data) {
        dataSource = [data?['sealUrl']];
        setState(() {});
      },
    );
  }

  final TextEditingController _controller = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 20),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(20),
        ),
        color: Colors.white,
      ),
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            if (widget.showName)
              Text(
                '签章筛选',
                style: TextStyle(
                  color: Color(0xff344254),
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
            if (widget.showName) vGap16,
            if (widget.showName)
              Wrap(
                spacing: 10,
                runSpacing: 10,
                children: _getStampWidgetList,
              ),
            if (widget.showName) vGap20,
            Text(
              '业务编码',
              style: TextStyle(
                color: Color(0xff344254),
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
            vGap16,
            TextField(
              controller: _controller,
              style: TextStyle(
                color: Color(0xff344254),
                fontSize: 14,
                fontWeight: FontWeight.w400,
              ),
              onChanged: (value) {
                serviceCode = value;
              },
              decoration: InputDecoration(
                filled: true,
                fillColor: Color(0xffF3F5F8),
                border: UnderlineInputBorder(
                  borderSide: BorderSide.none,
                  borderRadius: BorderRadius.circular(8),
                ),
                hintText: '请输入业务编码',
                hintStyle: TextStyle(
                  color: Color(0xffC9CDD4),
                  fontSize: 14,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
            vGap20,
            Text(
              '签名调用时间',
              style: TextStyle(
                color: Color(0xff344254),
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
            vGap16,
            Row(
              children: [
                _createActionBtn(starTime?.toYMD ?? '开始时间', () {
                  PickerTool.showDatePicker(context,
                      title: '请选择开始时间',
                      dateType: PickerDateType.YMD,
                      maxTime: DateTime.now().add(Duration(days: 1)),
                      selectTime: starTime, onConfirm: (select) {
                    setState(() {
                      starTime = select;
                    });
                  });
                }),
                Container(
                  margin: const EdgeInsets.symmetric(horizontal: 10),
                  height: 1,
                  width: 10,
                  color: Color(0xffDCDFE6),
                ),
                _createActionBtn(endTime?.toYMD ?? '结束时间', () {
                  PickerTool.showDatePicker(context,
                      title: '请选择结束时间',
                      dateType: PickerDateType.YMD,
                      maxTime: DateTime.now().add(Duration(days: 1)),
                      selectTime: endTime, onConfirm: (select) {
                    setState(() {
                      endTime = select;
                    });
                  });
                }),
              ],
            ),
            vGap85,
            Row(
              children: [
                _actionBtn('重置', _resetAction),
                hGap10,
                _actionBtn(
                  '确认',
                  _confirmAction,
                  isFill: true,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 重置按钮点击事件
  void _resetAction() {
    // stampInfo = null;
    // starTime = null;
    // endTime = null;
    // _controller.setContent('');
    _reset();
    setState(() {});
  }

  /// 确定按钮点击事件
  void _confirmAction() {
    Get.back();
    if (widget.showName) {
      if (!_checkTime()) {
        return;
      }
    }
    if (widget.stampScreenBlock != null) {
      widget.stampScreenBlock!(
          stampInfo, serviceCode, starTime?.toYMDStart, endTime?.toYMDEnd);
    }
  }

  bool _checkTime() {
    if (starTime != null && endTime == null) {
      AlertUtil.showCenterToast('请选择结束时间');
      return false;
    }
    if (endTime != null && starTime == null) {
      AlertUtil.showCenterToast('请选择开始时间');
      return false;
    }
    if (starTime != null && endTime != null) {
      if (starTime!.isBefore(endTime!.add(Duration(days: -60)))) {
        AlertUtil.showCenterToast('最大时间跨度为60天');
        return false;
      }
    }
    return true;
  }

  /// 创建底部按钮
  Widget _actionBtn(String title, GestureTapCallback action,
      {bool isFill = false}) {
    return Expanded(
        child: GestureTapWidget(
      onTap: action,
      child: Container(
        height: 40,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: StyleParams.themeColor, width: 1),
          color: isFill ? StyleParams.themeColor : Colors.white,
        ),
        child: Text(
          title,
          style: TextStyle(
            color: !isFill ? StyleParams.themeColor : Colors.white,
            fontSize: 17,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
    ));
  }

  /// 时间选择按钮
  Widget _createActionBtn(String title, GestureTapCallback action) {
    return Expanded(
      child: GestureTapWidget(
        onTap: action,
        child: Container(
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            color: Color(0xffF3F5F8),
          ),
          child: Text(
            title,
            style: TextStyle(
              color: (title == '开始时间' || title == '结束时间')
                  ? Color(0xffC9CDD4)
                  : Color(0xff344254),
              fontSize: 14,
              fontWeight: FontWeight.w400,
            ),
          ),
        ),
      ),
    );
  }

  /// 签章列表
  List<Widget> get _getStampWidgetList {
    return dataSource
        .map<Widget>((e) => GestureTapWidget(
              onTap: () {
                stampInfo = e;
                setState(() {});
              },
              child: UnconstrainedBox(
                child: Container(
                  height: 38,
                  alignment: Alignment.center,
                  padding: const EdgeInsets.symmetric(horizontal: 10),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    color: stampInfo == e
                        ? StyleParams.themeColor
                        : Color(0xffF3F5F8),
                  ),
                  child: Text(
                    e?['name'] ?? e?['alias'],
                    style: TextStyle(
                        color: stampInfo?['id'] == e?['id']
                            ? Colors.white
                            : Colors.black,
                        fontSize: 15,
                        fontWeight: FontWeight.w400),
                  ),
                ),
              ),
            ))
        .toList();
  }
}
