/*
 * @Author       : WuWei
 * @LastEditors  : WuWei
 * @Date         : 2022-08-02 17:19:02
 * @LastEditTime : 2023-05-09 17:56:45
 * @Description  : 智能填表--提交
 */
// import 'package:app_package/app_package.dart';
import 'package:app_package/src/view_models/message_add_store.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class MessageAddPage extends StatelessWidget {
  const MessageAddPage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (providerContext) => MessageAddStore(context, providerContext),
      child: _PageView(),
      lazy: false,
    );
  }
}

class _PageView extends StatelessWidget {
  const _PageView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final store = Provider.of<MessageAddStore>(context, listen: true);
    final colorScheme = WTheme.of(context).colorScheme;
    return Scaffold(
      appBar: WAppBar(
        brightness: Brightness.light,
        title: WisText('${store.title ?? '新建表单'}',
            size: 19.pt, weight: FontWeight.w600, color: colorScheme.mainTitle),
        iconTheme: IconThemeData(
          color: colorScheme.mainTitle,
          size: 19.pt,
        ),
        backgroundColor: Colors.white,
      ),
      body: WisScrollView(
        onInit: () => store.onInit(),
        slivers: [
          _BuildFormList(),
        ],
      ),
      bottomNavigationBar: SafeArea(
        child: Wisdom.row(
            height: 60.pt,
            color: Colors.white,
            padding: EdgeInsets.symmetric(horizontal: 15.pt, vertical: 8.pt),
            children: [
              WLoadingButton(
                remain: false,
                loadingText: WisText(
                  '提交中...',
                  size: 18.pt,
                  color: colorScheme.grey,
                ),
                height: 44.pt,
                onPressed: () => store.onSubmitForm(),
                child: WisText(
                  '提交',
                  size: 18.pt,
                ),
              ).asExpanded(),
            ]),
      ),
    );
  }
}

class _BuildFormList extends StatelessWidget {
  const _BuildFormList({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final store = Provider.of<MessageAddStore>(context, listen: true);
    final colorScheme = WTheme.of(context).colorScheme;
    return SliverToBoxAdapter(
      child: WisCard(
        margin: EdgeInsets.only(
          top: 10.pt,
          left: 15.pt,
          right: 15.pt,
        ),
        child: Form(
          key: store.formKey,
          child: Wisdom.column(
            color: Colors.white,
            padding: EdgeInsets.symmetric(horizontal: 15.pt),
            children: ListTile.divideTiles(
              context: context,
              tiles: [
                WFInput(
                  isRequired: true,
                  title: WisText('标题'),
                  hintText: '输入本次填报标题',
                  type: InputType.singleLine,
                  initialValue: store.formTitle,
                  maxLength: 32,
                  onInput: (v) => store.onSetTitle(v),
                ),
                if (store.formDetail?.type == 'community' &&
                    store.formHtml == null) ...[
                  WFTreePicker(
                    isRequired: true,
                    initialValue: store.community,
                    title: WisText('所属项目'),
                    hintText: '选择所属项目',
                    onChanged: (v) => store.setCommunity(v),
                    dataList: store.communityList,
                    label: 'communityName',
                    value: 'communityId',
                    child: 'list',
                    firstName: 'propertyCompanyName',
                    firstValue: 'propertyCompanyId',
                    isMulti: false,
                  )
                ],
                if (store.formDetail?.type == 'community' &&
                    store.formHtml != null) ...[
                  Wisdom.row(
                    color: colorScheme.divider,
                    height: 44.pt,
                    children: [
                      Row(
                        children: [
                          WisText('*', color: Color(0XFFFF495E)),
                          WisText('所属项目'),
                        ],
                      ),
                      SizedBox(width: 45.pt),
                      WisText('${store.communityName ?? '--'}'),
                    ],
                  ),
                ],
                if (store.formDetail?.fillPeriodType == 'week') ...[
                  WFWeekPicker(
                    isRequired: true,
                    title: WisText('填报周期'),
                    hintText: '选择周',
                    initialWeek: store.period,
                    onChanged: (v, weekStr, weekNum) =>
                        store.onSetWeek(v, weekStr, weekNum),
                  ),
                ],
                if (store.formDetail?.fillPeriodType == 'quarter') ...[
                  WFSeasonPicker(
                    isRequired: true,
                    title: WisText('填报周期'),
                    hintText: '选择季度',
                    initialSeason: store.period,
                    onChanged: (v, str) => store.onSetSeason(v, str),
                  ),
                ],
                if (store.formDetail?.fillPeriodType == 'month') ...[
                  WFMonthPicker(
                    isRequired: true,
                    title: WisText('填报周期'),
                    hintText: '选择月',
                    initialMonth: store.period,
                    onChanged: (v) => store.onSetPeroid(v, 'month'),
                  ),
                ],
                if (store.formDetail?.fillPeriodType == 'day') ...[
                  WFDatePicker(
                    isRequired: true,
                    title: WisText('填报周期'),
                    hintText: '选择日',
                    initialDateTime: store.period,
                    onChanged: (v) => store.onSetPeroid(v, 'day'),
                  ),
                ],
                if (store.formDetail?.fillPeriodType == 'year') ...[
                  WFYearPicker(
                    isRequired: true,
                    title: WisText('填报周期'),
                    hintText: '选择年',
                    initialYear: store.period,
                    onChanged: (v) => store.onSetPeroid(v, 'year'),
                  ),
                ],
                for (var index = 0; index < store.formList.length; index++)
                  _BuildFormItem(item: store.formList[index], index: index),
              ],
            ).toList(),
          ),
        ),
      ),
    );
  }
}

class _BuildFormItem extends StatelessWidget {
  const _BuildFormItem({Key? key, required this.item, required this.index})
      : super(key: key);
  final item;
  final int index;

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

    /// 单行文本
    if (item['__config__']['tag'] == 'el-input' &&
        item['__config__']['tagIcon'] == 'input')
      return new WFInput(
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
        hintText: '${item['placeholder']}',
        type: InputType.singleLine,
        initialValue: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null
            ? store.postFormPrs[index]['value']
            : null,
        maxLength: item['maxLenth'],
        onInput: (v) => store.onSetFormPrs(index, v),
      );

    /// 多行文本
    if (item['__config__']['tag'] == 'el-input' &&
        item['__config__']['tagIcon'] == 'textarea')
      return WFInput(
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
        hintText: '${item['placeholder']}',
        type: InputType.multiLine,
        maxLength: item['maxLenth'],
        initialValue: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null
            ? store.postFormPrs[index]['value']
            : null,
        onInput: (v) => store.onSetFormPrs(index, v),
      );

    /// 日期选择
    if (item['__config__']['tag'] == 'el-date-picker' &&
        item['__config__']['tagIcon'] == 'date')
      return WFDatePicker(
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
        hintText: '请选择${item['__config__']['label']}',
        initialDateTime: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null
            ? store.postFormPrs[index]['value']
            : null,
        onChanged: (v) => store.onSetFormPrs(index, v),
      );

    ///日期范围
    if (item['__config__']['tag'] == 'el-date-picker' &&
        item['__config__']['tagIcon'] == 'dateRange')
      return WFDateRangePicker(
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
        hintText: '请选择${item['__config__']['label']}',
        onChanged: (v) => store.onSetFormPrs(index, v),
        initialDateRange: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null
            ? store.postFormPrs[index]['value']
            : null,
      );

    /// 上传
    if (item['__config__']['tag'] == 'el-upload' &&
        (item['__config__']['tagIcon'] == 'upload' ||
            item['__config__']['tagIcon'] == 'imgUpload'))
      return WFImagePicker(
        maxCount: item['limit'],
        currentCount: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null &&
                store.postFormPrs[index]['value'].length != null
            ? store.postFormPrs[index]['value'].length
            : 0,
        onDelete: (i) => {store.onImageRemoveAt(index, i)},
        onSelected: (images) => {store.onFilesChanged(images, index)},
        images: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null &&
                store.postFormPrs[index]['value'].length != null
            ? store.postFormPrs[index]['value']
            : null,
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
      );
    // 数字
    if (item['__config__']['tag'] == 'el-input-number' &&
        item['__config__']['tagIcon'] == 'number')
      return WFInputNumber(
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
        hintText: '${item['placeholder']}',
        type: InputType.number,
        onInput: (v) => store.onSetFormPrs(index, v),
        initialValue: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null
            ? store.postFormPrs[index]['value']
            : null,
      );

    ///金额
    if (item['__config__']['tag'] == 'el-input-number' &&
        item['__config__']['tagIcon'] == 'money')
      return WFInputMoney(
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
        hintText: '${item['placeholder']}',
        type: InputType.money,
        onInput: (v) => store.onSetFormPrs(index, v.toString()),
        initialValue: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null
            ? store.postFormPrs[index]['value']
            : null,
      );

    /// 手机号
    if (item['__config__']['tag'] == 'el-input' &&
        item['__config__']['tagIcon'] == 'mobile')
      return WFInput(
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
        hintText: '${item['placeholder']}',
        type: InputType.phoneNumber,
        onInput: (v) => store.onSetFormPrs(index, v),
        initialValue: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null
            ? store.postFormPrs[index]['value']
            : null,
      );

    /// 开关
    if (item['__config__']['tag'] == 'el-switch')
      return WFSwitch(
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
        initialValue: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null
            ? store.postFormPrs[index]['value']
            : false,
        onChanged: (v) => store.onSetFormPrs(index, v),
      );

    ///单选框
    if (item['__config__']['tag'] == 'el-radio-group' &&
        item['__config__']['tagIcon'] == 'radio')
      return WFRadioPicker(
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
        hintText: '${item['placeholder']}',
        initialValue: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null
            ? store.postFormPrs[index]['value']
            : null,
        dataList: item != null && item['__slot__'] != null
            ? item['__slot__']['options']
            : [],
        onChanged: (v) =>
            store.onSetFormRadioPrs(index, v, item['__slot__']['options']),
      );
    // 多选框
    if (item['__config__']['tag'] == 'el-checkbox-group' &&
        item['__config__']['tagIcon'] == 'checkbox')
      return WFMultiplePicker(
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
        hintText: item['placeholder'] ?? null,
        dataList: item != null && item['__slot__'] != null
            ? item['__slot__']['options']
            : [],
        initialValue: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null
            ? store.postFormPrs[index]['value']
            : null,
        onChanged: (v) =>
            store.onSetFormCheckGroupPrs(index, v, item['__slot__']['options']),
      );

    ///单选下拉框
    if (item['__config__']['tag'] == 'el-select' &&
        item['__config__']['tagIcon'] == 'select')
      return WFSinglePicker(
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
        hintText: item['placeholder'] ?? null,
        initialValue: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null
            ? store.postFormPrs[index]['value']
            : null,
        dataList: item != null && item['__slot__'] != null
            ? item['__slot__']['options']
            : [],
        onChanged: (v) =>
            store.onSetFormSelectPrs(index, v, item['__slot__']['options']),
      );

    ///时间范围
    if (item['__config__']['tag'] == 'el-time-picker' &&
        item['__config__']['tagIcon'] == 'timeRange')
      return WFTimeRangePicker(
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
        hintText: item['placeholder'] ?? '请选择${item['__config__']['label']}',
        initialTime: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null
            ? store.postFormPrs[index]['value']
            : [],
        mode: DateTimeRangePickerMode.time,
        onChanged: (v) => store.onSetFormPrs(index, v),
      );

    ///时间选择
    if (item['__config__']['tag'] == 'el-time-picker' &&
        item['__config__']['tagIcon'] == 'time')
      return WFTimePicker(
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
        hintText: item['placeholder'] ?? '请选择${item['__config__']['label']}',
        initialDate: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null
            ? store.postFormPrs[index]['value']
            : null,
        onChanged: (v) => store.onSetFormPrs(index, v),
      );

    /// 日期时间
    if (item['__config__']['tag'] == 'el-date-picker' &&
        item['__config__']['tagIcon'] == 'datetime')
      return WFTimePicker(
        isRequired: item['__config__']['required'],
        title: WisText('${item['__config__']['label']}'),
        type: 'datetime',
        hintText: item['placeholder'] ?? '请选择${item['__config__']['label']}',
        initialDate: store.postFormPrs.length > 0 &&
                store.postFormPrs[index]['value'] != null
            ? store.postFormPrs[index]['value']
            : null,
        onChanged: (v) => store.onSetFormPrs(index, v),
      );
    if (item['__config__']['tag'] == 'quillEditor')

      /// 富文本图片上传前缀匹配，PC端上传未带域名
      return Wisdom.column(
        color: colorScheme.divider,
        onTap: () => {
          WToastUtil.show('富文本组件，手机不可编辑，可使用电脑编辑'),
        },
        children: [
          Wisdom.row(
            height: 44.pt,
            children: [
              WisText(
                '*',
                color: Color(0XFFFF495E),
              ),
              WisText('${item['__config__']['label']}'),
            ],
          ),
          // Container(
          //   child: HtmlWidget(
          //     data: store.postFormPrs[index]['value'] == null ||
          //             store.postFormPrs[index]['value'] == ''
          //         ? '--'
          //         : store.postFormPrs[index]['value']
          //             .replaceAll(RegExp(r'\"/9ad134a361f8d778'), '"$baseUrl'),
          //     style: {
          //       'body': Style(
          //         fontSize: FontSize(15.pt),
          //       ),
          //     },
          //   ),
          // ),
        ],
      );
    else
      return Container(
        width: 0.0,
        height: 0.0,
        child: WisText(''),
      );
  }
}
