/*
 * @Author: ChenYaJin
 * @Date: 2021-11-09 15:43:49
 * @LastEditors: ChenYaJin
 * @LastEditTime: 2023-03-30 17:50:26
 * @Description: 添加费用需要填的表单信息
 */
part of '../add_index.dart';

class _FormComponent extends StatelessWidget {
  const _FormComponent({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final store = Provider.of<FeeIndexStore>(context);
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    final reportDetail = store.reportDetail;
    final data = store.serviceFeeDetail;
    final houseNo = (data?.houseId?.isNotEmpty ?? false)
        ? data!.houseNo
        : (reportDetail?.houseId?.isNotEmpty ?? false)
            ? reportDetail!.houseName
            : '';
    return Container(
      child: WisCard(
        color: Colors.white,
        margin: EdgeInsets.symmetric(horizontal: 15.pt, vertical: 10.pt),
        elevation: 0,
        child: WForm(
          key: store.formKey,
          initialValues: store.formValue,
          onChanged: () => store.formChange(),
          child: Wisdom.column(
            color: Colors.white,
            padding: EdgeInsets.symmetric(horizontal: 15.pt),
            border: Border.symmetric(
              vertical: Divider.createBorderSide(context),
            ),
            children: ListTile.divideTiles(
              context: context,
              tiles: [
                // 已关联住户，不可编辑
                if (houseNo.isNotEmpty)
                  WFormTile(
                    required: true,
                    minWidth: 120.pt,
                    leading: Text('房号'),
                    child: TextFormField(
                      readOnly: true,
                      textAlign: TextAlign.end,
                      initialValue: houseNo,
                      maxLines: null,
                      decoration: InputDecoration(
                        fillColor: Colors.white,
                      ),
                    ),
                  )
                else
                  WFormTile(
                    required: true,
                    leading: Text('房号'),
                    child: WInfinityPickerFormField.textField(
                      field: 'house',
                      title: Text('选择报修住户房号'),
                      textAlign: TextAlign.end,
                      getData: (List<CascadeHouseModel>? list) =>
                          store.getHouseData(list!),
                      buildName: (List<CascadeHouseModel>? list) =>
                          list != null && list.length > 0 ? list.last.name ?? '' : '',
                      isLast: (List<CascadeHouseModel>? list) async =>
                          list != null && list.length > 0 ? list.last.status == 'house' : false,
                      decoration: InputDecoration(
                        fillColor: Colors.white,
                        hintText: '选择报修住户房号',
                        hintStyle: TextStyle(
                          fontSize: 14.pt,
                          color: colorScheme.placeholder,
                        ),
                      ),
                    ),
                  ),
                WFormTile(
                  required: true,
                  leading: Text('项目名称'),
                  child: WSinglePickerFormField.textField(
                    field: 'payServiceProject',
                    textAlign: TextAlign.end,
                    getData: () => store.getProjectList(),
                    onChanged: (v) => store.selectProject(v as ServiceProject),
                    title: Text('请选择项目'),
                    decoration: InputDecoration(
                      fillColor: Colors.white,
                      hintText: '请选择项目',
                      hintStyle: TextStyle(
                        fontSize: 14.pt,
                        color: colorScheme.placeholder,
                        fontWeight: FontWeight.w300,
                      ),
                    ),
                  ),
                ),
                if (store.hasSelectProject)
                  WFormTile(
                    minWidth: 120.pt,
                    leading: Text('单价'),
                    child: TextFormField(
                      readOnly: true,
                      controller:
                          TextEditingController(text: store.priceAndUnit),
                      textAlign: TextAlign.end,
                      maxLines: null,
                      decoration: InputDecoration(
                        fillColor: Colors.white,
                      ),
                    ),
                  ),
                if (store.isHasPriceAndUnit && store.hasSelectProject)
                  WFormTile(
                    required: true,
                    minWidth: 120.pt,
                    leading: Text('数量'),
                    child: WTextFormField(
                      keyboardType: TextInputType.number,
                      textAlign: TextAlign.end,
                      field: 'quantity',
                      onChanged: (v) => store.changeQuantity(v),
                      onTap: () => store.setFee(),
                      inputFormatters: [
                        _SingleLineQuantityFormatter(maxLength: 32),
                      ],
                      decoration: InputDecoration(
                        fillColor: Colors.white,
                        hintText: '输入数量，最多1位小数',
                      ),
                    ),
                  ),
                if (!store.isHasPriceAndUnit && store.hasSelectProject)
                  WFormTile(
                    minWidth: 120.pt,
                    leading: Text('数量'),
                    child: TextFormField(
                      readOnly: true,
                      textAlign: TextAlign.end,
                      initialValue: '--',
                      maxLines: null,
                      decoration: InputDecoration(
                        fillColor: Colors.white,
                      ),
                    ),
                  ),
                if (store.isHasPriceAndUnit && store.hasSelectProject)
                  WFormTile(
                    minWidth: 120.pt,
                    leading: Text('金额(元)'),
                    child: TextFormField(
                      readOnly: true,
                      textAlign: TextAlign.end,
                      controller: TextEditingController(text: store.fee),
                      maxLines: null,
                      decoration: InputDecoration(
                        fillColor: Colors.white,
                      ),
                    ),
                  ),
                if (!store.isHasPriceAndUnit && store.hasSelectProject)
                  WFormTile(
                    required: true,
                    minWidth: 120.pt,
                    leading: Text('金额(元)'),
                    child: WTextFormField(
                      keyboardType:
                          TextInputType.numberWithOptions(decimal: true),
                      textAlign: TextAlign.end,
                      field: 'fee',
                      inputFormatters: [
                        _SingleLineMoneyFormatter(maxLength: 32)
                      ],
                      decoration: InputDecoration(
                        fillColor: Colors.white,
                        hintText: '输入该项费用金额',
                      ),
                    ),
                  ),
              ],
            ).toList(),
          ),
        ),
      ),
    ).nestSliverToBoxAdapter();
  }
}

validator(value) {
  if (value == null || value == '') {
    return '数量不能为空';
  }
  var parse = double.tryParse(value) ?? 0;

  if (parse <= 0) {
    return '只支持大于0的数字';
  }
  Pattern pattern =
      r'^([1-9][0-9]*)+([.][0-9]{1}){0,1}$|^[0]+([.][1-9]{1}){0,1}$';
  RegExp time = new RegExp(pattern as String);

  if (!time.hasMatch(value)) {
    return '只支持一位小数的数字';
  }
  return null;
}

class _SingleLineQuantityFormatter extends TextInputFormatter {
  _SingleLineQuantityFormatter({this.maxLength});
  final int? maxLength;

  @override
  TextEditingValue formatEditUpdate(preValue, newValue) {
    final _maxLength = maxLength ?? 64;
    TextEditingValue value = newValue;
    final length = value.text.length;
    //保留一位小数
    Pattern pattern = r'^([0-9]?\d*)\.\d{0,1}$|^\d*$';
    RegExp time = new RegExp(pattern as String);
    if (!time.hasMatch(value.text)) {
      value = preValue;
    }
    // 保留最大长度
    if (length > _maxLength)
      value = value.copyWith(
        text: value.text.substring(0, _maxLength),
      );
    return value;
  }
}

class _SingleLineMoneyFormatter extends TextInputFormatter {
  _SingleLineMoneyFormatter({this.maxLength});
  final int? maxLength;

  @override
  TextEditingValue formatEditUpdate(preValue, newValue) {
    final _maxLength = maxLength ?? 64;
    TextEditingValue value = newValue;
    final length = value.text.length;
    // 保留两位小数
    Pattern pattern = r'^([0-9]?\d*)\.\d{0,2}$|^\d*$';
    RegExp time = new RegExp(pattern as String);
    if (!time.hasMatch(value.text)) {
      value = preValue;
    }
    // 保留最大长度
    if (length > _maxLength)
      value = value.copyWith(
        text: value.text.substring(0, _maxLength),
      );
    return value;
  }
}
