/*
 * @Author: XianKaiQun
 * @Date: 2020-09-15 16:21:47
 * @LastEditors: wuwei
 * @LastEditTime: 2024-03-04 17:22:35
 * @Description: 
 */
part of '../index.dart';

final _meterType = {
  'waterMeter': AssetList.$waterMeter_png_image,
  'electricMeter': AssetList.$amMeter_png_image,
};

class _MeterItemComponent extends StatefulWidget {
  const _MeterItemComponent({
    Key? key,
    this.id,
    this.type,
    this.name,
    this.lastAmount,
    this.lastActualAmount,
    this.transcribes,
    this.date,
    this.backhaulAmount,
    this.multiple,
    this.location,
    this.source,
    this.meterCode,
    this.item,
    required this.onSave,
  }) : super(key: key);

  final item;

  ///
  final String? id;

  ///
  final String? location;

  ///表来源 [house]住户表，[common]公共表
  final String? source;

  ///表类型
  final String? type;

  ///表名
  final String? name;

  ///上次抄表度数
  final num? lastAmount;

  ///上次行度
  final num? lastActualAmount;

  ///本期已抄？
  final bool? transcribes;

  ///时间
  final String? date;

  ///仪表回程（最大读数）
  final num? backhaulAmount;

  ///倍数
  final num? multiple;

  ///编号
  final String? meterCode;

  ///保存
  final Future<bool> Function({
    num? number,
    String? id,
    String? source,
    String? readTime,
  }) onSave;
  @override
  __MeterItemComponentState createState() => __MeterItemComponentState();
}

class __MeterItemComponentState extends State<_MeterItemComponent> {
  @override
  void initState() {
    super.initState();
    transcribes = widget.transcribes;
  }

  bool? transcribes;

  ///最新度数
  num? newestvalue;
  route2detail() {
    final store = Provider.of<PrivateIndexStore>(context, listen: false);
    WNavUtil.instance!.pushNamed('metered/detail', arguments: {
      'id': widget.id,
      'source': widget.source,
    }).then((value) => {
      /// 有撤销抄表操作之后 刷新列表
          if (value == true)
            {
              store.getData(),
            }
        });
  }

  ///行度=本次读数-上次读数
  ///低于上次行度50%或高于上次行度150%
  String? get tip {
    if (newestvalue == null) {
      return null;
    }
    if (transcribes == true) {
      return null;
    }

    num? lastActualAmount = widget.lastActualAmount;
    if (lastActualAmount == null) {
      return null;
    }
    num? lastAmount = widget.lastAmount;
    if (lastAmount == 0) {
      return null;
    } else if (newestvalue! < (lastAmount ?? 0)) {
      return '回程计算';
    } else if (newestvalue == lastAmount) {
      return '无实际行度';
    } else {
      var diff = newestvalue! - (widget.lastAmount ?? 0);
      var ratio = diff / lastActualAmount;
      if (ratio < 0.5 || ratio > 1.5) {
        return '异常波动';
      } else {
        return null;
      }
    }
  }

  Future<bool> onSave(num number, String? readTime) async {
    final res = await widget.onSave(
      id: widget.id,
      source: widget.source,
      number: number,
      readTime: readTime,
    );
    if (res) {
      newestvalue = number;
    }
    return res;
  }

  @override
  Widget build(BuildContext context) {
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
// final store = Provider.of<PrivateMeterItemStore>(context, listen: false);

    return Wisdom(
      border: widget.source == 'common'
          ? null
          : Border(
              top: BorderSide(
                width: 1,
                color: colorScheme.divider2,
                style: BorderStyle.solid,
              ),
              // bottom: BorderSide(
              //   width: 1,
              //   color: colorScheme.primary.withOpacity(0.2),
              //   style: BorderStyle.solid,
              // ),
            ),
      color: Colors.white,
      margin: EdgeInsets.symmetric(vertical: 5.pt),
      padding: widget.source == 'common'
          ? EdgeInsets.fromLTRB(15.pt, 0, 15.pt, 10.pt)
          : EdgeInsets.all(15.pt),
      child: Wisdom.column(
        onTap: () => route2detail(),
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            children: [
              Text.rich(
                TextSpan(
                  children: [
                    if (_meterType[widget.type] != null)
                      WidgetSpan(
                        alignment: PlaceholderAlignment.middle,
                        child: Image(
                          image: _meterType[widget.type]!,
                          width: 22.pt,
                          height: 22.pt,
                        ),
                      ),
                    TextSpan(
                      text: ' ${widget.name}',
                      style: TextStyle(
                        fontSize: 16.pt,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ).nestExpanded(),
              Icon(
                Icons.arrow_forward_ios,
                size: 14.pt,
                color: colorScheme.grey,
              )
            ],
          ),
          Wisdom.row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            margin: EdgeInsets.symmetric(vertical: 10.pt),
            children: [
              Wisdom.row(
                children: [
                  if (widget.multiple != null)
                    WTag(
                      color: colorScheme.primary,
                      child: Text('${widget.multiple}倍',
                          style: TextStyle(
                            fontSize: 13.pt,
                          )),
                    ),
                  WTag(
                    color: widget.transcribes == true
                        ? colorScheme.success
                        : colorScheme.danger,
                    child: Text(
                      widget.transcribes == true ? '本期已抄' : '本期未抄',
                      style: TextStyle(
                        fontSize: 13.pt,
                      ),
                    ),
                  ),
                ],
              ),
              Text.rich(
                TextSpan(
                  style: TextStyle(fontSize: 14.pt),
                  children: [
                    TextSpan(
                      text: '上次度数：',
                      style: TextStyle(color: colorScheme.grey),
                    ),
                    TextSpan(
                      text: '${widget.lastAmount ?? ''}',
                      style: TextStyle(color: colorScheme.primary),
                    ),
                  ],
                ),
              ),
            ],
          ),
          Wisdom.row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            margin: EdgeInsets.symmetric(vertical: 5.pt),
            children: [
              Text(
                '仪表回程',
                style: TextStyle(
                  color: colorScheme.minor,
                ),
              ),
              Text(
                '${widget.backhaulAmount ?? '--'}',
                style: TextStyle(
                  fontSize: 14.pt,
                  color: colorScheme.grey,
                ),
              ),
            ],
          ),
          Wisdom.row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            margin: EdgeInsets.symmetric(vertical: 5.pt),
            children: [
              Text(
                '抄表时间',
                style: TextStyle(
                  color: colorScheme.minor,
                ),
              ),
              Text(
                widget.date ?? '--',
                style: TextStyle(
                  fontSize: 14.pt,
                  color: colorScheme.grey,
                ),
              ),
            ],
          ),
          // Divider(
          //   height: 10.pt,
          //   color: colorScheme.divider,
          // ),
          Wisdom.row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            margin: EdgeInsets.only(top: 5.pt),
            children: [
              Wisdom.row(children: [
                Text(
                  '抄表读数',
                  style: TextStyle(
                    fontSize: 14.pt,
                    color: colorScheme.mainTitle,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                if (tip != null)
                  Wisdom(
                    color: colorScheme.red,
                    borderRadius: BorderRadius.circular(25.pt),
                    padding:
                        EdgeInsets.symmetric(horizontal: 8.pt, vertical: 2.pt),
                    margin: EdgeInsets.symmetric(horizontal: 5.pt),
                    child: Text(
                      '$tip',
                      style: TextStyle(
                        fontSize: 12.pt,
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
              ]),
              Wisdom.row(
                onTap: () => _showModal(
                  name: '${widget.name}（上次读数：${widget.lastAmount}）',
                  onSave: onSave,
                ),
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  if (newestvalue == null) ...[
                    Wisdom(
                      child:
                          WisText('点击抄表', size: 13.pt, color: colorScheme.grey),
                    ),
                    Image.network(
                      "https://wy.huiguanjia.cn/9ad134a361f8d778/file/images/796079358452240384",
                      width: 18.pt,
                      height: 18.pt,
                    ),
                  ] else ...[
                    Wisdom(
                      child: WisText('${newestvalue}',
                          size: 16.pt, color: colorScheme.primary),
                    ),
                    Image.network(
                      "https://wy.huiguanjia.cn/9ad134a361f8d778/file/images/796079358452240384",
                      width: 18.pt,
                      height: 18.pt,
                    ),
                  ]
                ],
              ).asExpanded(),
            ],
          ),
        ],
      ),
    );
  }
}

_showModal(
    {String? name,
    Future<bool> Function(num number, String? readTime)? onSave}) async {
  String value = '';
  String? _readtime = DateFormat('yyyy-MM-dd HH:mm').format(DateTime.now());
  _onSave() async {
    final number = num.tryParse(value);
    if (_readtime == null) {
      WToastUtil.show('请选择抄表时间');
      return;
    }

    if (number == null) {
      WToastUtil.show('请输入正确的仪表度数');
      return;
    }
    var res = await onSave!(number, _readtime);
    if (res == true) {
      WNavUtil.instance!.pop();
    }
  }

  _onPickDate(data) async {
    _readtime = data;
  }

  return await showModalBottomSheet(
    context: WNavUtil.instance!.context!,
    isScrollControlled: true,
    builder: (context) {
      return Wisdom.column(
        color: Colors.white,
        padding: EdgeInsets.fromLTRB(15.pt, 15.pt, 15.pt, 25.pt),
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text('$name', style: TextStyle(fontSize: 15.pt)),
          SizedBox(height: 10.pt),
          WFTimePicker(
            isRequired: true,
            type: 'datetime',
            title: WisText('抄表时间'),
            hintText: '请选择抄表时间',
            initialDate: _readtime,
            onChanged: (v) => _onPickDate(v),
          ),
          SizedBox(height: 10.pt),
          Row(
            children: [
              TextFormField(
                inputFormatters: [
                  UsNumberTextInputFormatter(),
                ],
                onChanged: (v) => value = v,
                autofocus: true,
                keyboardType: TextInputType.numberWithOptions(
                  decimal: true,
                  signed: false,
                ),
                style: TextStyle(
                  color: WTheme.of(context).colorScheme.primary,
                  fontWeight: FontWeight.bold,
                  fontSize: 16.pt,
                ),
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.all(13.pt),
                  filled: false,
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(4.pt),
                    borderSide: Divider.createBorderSide(context),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(4.pt),
                    borderSide: Divider.createBorderSide(context),
                  ),
                ),
              ).nestExpanded(),
              SizedBox(width: 10.pt),
              WLoadingButton(
                onPressed: _onSave,
                focusOnGesture: false,
                color: WTheme.of(context).colorScheme.primary,
                disabledColor: WTheme.of(context).colorScheme.disabled,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.pt),
                ),
                child: Text('保存'),
              ),
            ],
          ),
        ],
      );
    },
  );
}

///输入框格式化只保留两位小数
class UsNumberTextInputFormatter extends TextInputFormatter {
  final regExp = RegExp('^[0-9]+\.?([0-9]{1,2})?\$');
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    if (newValue.text == '') {
      return TextEditingValue();
    }

    ///打上0自动加上小数点
    else if (newValue.text == '0') {
      if (oldValue.text.length > newValue.text.length) {
        return TextEditingValue();
      } else {
        return TextEditingValue(
          text: '0.',
          selection: TextSelection(baseOffset: 2, extentOffset: 2),
        );
      }
    } else {
      return regExp.hasMatch(newValue.text) ? newValue : oldValue;
    }
  }
}
