/*
 * @Author: XianKaiQun
 * @LastEditors  : WuWei
 * @Date: 2020-10-26 09:57:02
 * @LastEditTime : 2023-05-10 10:51:59
 */

import 'dart:convert';
import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:oa_package/src/view_models/private_detail_store.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
part 'components/actionDialog.dart';

class DetailPageView extends StatelessWidget {
  const DetailPageView({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final store = Provider.of<DetailStore>(context, listen: false);
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    return Scaffold(
      appBar: WAppBar(
        brightness: Brightness.light,
        title: WisText(
          '审批详情',
          size: 19.pt,
          weight: FontWeight.w600,
          color: colorScheme.mainTitle,
        ),
        iconTheme: IconThemeData(
          color: colorScheme.mainTitle,
          size: 19.pt,
        ),
        backgroundColor: Colors.white,
      ),
      body: WisScrollView(
        onInit: () => store.onGetFlowsDetail(),
        slivers: [
          SizedBox(height: 15.pt).asSliver(),

          /// 顶部审批表单内容详情
          SliverToBoxAdapter(
            child: Observer(
              builder: (context) {
                return WisCard(
                  margin: EdgeInsets.only(
                    bottom: 10.pt,
                    left: 15.pt,
                    right: 15.pt,
                  ),
                  child: Wisdom.column(
                    color: Colors.white,
                    children: [
                      ...() {
                        final map = {
                          '发起人': '${store.taskDetail?.creator ?? '--'}',
                          '发起人部门': '${store.taskDetail?.organ ?? '--'}',
                        };
                        return map.keys
                            .map(
                              (key) => Wisdom.row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                padding:
                                    EdgeInsets.fromLTRB(15.pt, 15.pt, 15.pt, 0),
                                children: [
                                  Wisdom(
                                    width: 90.pt,
                                    child: Text(
                                      '$key',
                                      style: TextStyle(
                                        color: colorScheme.minor,
                                        fontSize: 14.pt,
                                      ),
                                    ),
                                  ),
                                  Text(
                                    '${map[key]}',
                                    style: TextStyle(
                                      color: colorScheme.mainTitle,
                                      fontSize: 14.pt,
                                    ),
                                  ).asExpanded(),
                                ],
                              ),
                            )
                            .toList();
                      }(),
                      for (var htmlitem in store.formHtml ?? [])
                        Wisdom.row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          padding: EdgeInsets.fromLTRB(15.pt, 15.pt, 15.pt, 0),
                          children: [
                            Wisdom(
                              width: 90.pt,
                              child: Text(
                                '${htmlitem['__config__']['label'] ?? '--'}',
                                style: TextStyle(
                                  color: colorScheme.minor,
                                  fontSize: 14.pt,
                                ),
                              ),
                            ),
                            if (htmlitem['__config__']['tag'] == 'el-upload' &&
                                htmlitem['__config__']['tagIcon'] ==
                                    'imgUpload' &&
                                htmlitem['_value_'] is List)
                              for (var image in htmlitem['_value_'])
                                Wisdom(
                                  onTap: () => store.onShowImage(image),
                                  padding:
                                      EdgeInsets.only(right: 5.pt, top: 5.pt),
                                  child: DecoratedBox(
                                    position: DecorationPosition.foreground,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(4.pt),
                                      border: Border.all(
                                          color: Colors.black12, width: 0.5.pt),
                                    ),
                                    child: WImage.network(
                                      AppParseUtil.image('$image'),
                                      width: 58.pt,
                                      height: 58.pt,
                                      fit: BoxFit.fill,
                                      borderRadius: BorderRadius.circular(4.pt),
                                    ),
                                  ),
                                ),
                            if (htmlitem['__config__']['tag'] == 'el-upload' &&
                                htmlitem['__config__']['tagIcon'] == 'upload' &&
                                htmlitem['_value_'] is List)
                              for (var file in htmlitem['_value_'])
                                Wisdom(
                                  onTap: () => store.onCopyLink(file),
                                  padding:
                                      EdgeInsets.only(right: 5.pt, top: 5.pt),
                                  child: Text(
                                    '${file['name']}',
                                    style: TextStyle(
                                      color: colorScheme.blue,
                                      fontSize: 14.pt,
                                    ),
                                  ),
                                ).asExpanded(),
                            if (htmlitem['__config__']['tag'] != 'el-upload')
                              Text(
                                '${htmlitem['_value_'] ?? '--'}',
                                style: TextStyle(
                                  color: colorScheme.mainTitle,
                                  fontSize: 14.pt,
                                ),
                              ).asExpanded(),
                          ],
                        ),
                      SizedBox(height: 15.pt),
                    ],
                  ),
                );
              },
            ),
          ),

          /// 表单审批流程详情
          SliverToBoxAdapter(
            child: Observer(
              builder: (context) {
                return WisCard(
                  margin: EdgeInsets.only(
                    bottom: 15.pt,
                    left: 15.pt,
                    right: 15.pt,
                  ),
                  child: Wisdom.column(
                    margin: EdgeInsets.only(bottom: 59.pt),
                    padding: EdgeInsets.symmetric(horizontal: 15.pt),
                    color: Colors.white,
                    children: [
                      Wisdom.row(
                        padding: EdgeInsets.symmetric(vertical: 25.pt),
                        children: [
                          Text(
                            '审批环节',
                            style: TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: 15.pt,
                            ),
                          ),
                          SizedBox(width: 5.pt),
                        ],
                      ),

                      /// 审批流程
                      if (store.taskDetail != null &&
                          store.taskDetail?.traces != null &&
                          store.taskDetail!.traces!.length > 0)
                        for (var i = 0;
                            i < store.taskDetail!.traces!.length;
                            i++)
                          Stack(
                            children: [
                              Wisdom.column(
                                padding:
                                    EdgeInsets.only(left: 28.pt, bottom: 25.pt),
                                crossAxisAlignment: CrossAxisAlignment.stretch,
                                children: [
                                  Row(
                                    children: [
                                      Text(
                                        '${store.taskDetail?.traces![i].operator ?? ''}${store.taskDetail?.traces![i].title ?? ''} ${store.taskDetail?.traces![i].action ?? ''}',
                                        style: TextStyle(
                                          fontWeight: FontWeight.w600,
                                          color: colorScheme.mainTitle,
                                          height: 1.2,
                                        ),
                                      ).asExpanded(),
                                      Text(
                                        '${store.taskDetail?.traces![i].finishTime ?? '--'}',
                                        style: TextStyle(
                                          color: colorScheme.placeholder,
                                          fontSize: 12.pt,
                                        ),
                                      ),
                                    ],
                                  ),

                                  /// 审批备注
                                  (store.taskDetail?.traces![i].firstNode !=
                                              null &&
                                          !store.taskDetail!.traces![i]
                                              .firstNode! &&
                                          store.taskDetail?.traces![i]
                                                  .content !=
                                              null)
                                      ? Text(
                                          jsonDecode(store.taskDetail
                                                  ?.traces![i].content ??
                                              '')['formVar']['auditDesc'],
                                          style: TextStyle(
                                            color: colorScheme.minor,
                                            height: 1.7,
                                            fontSize: 13.pt,
                                          ),
                                        )
                                      : Container(
                                          height: 0,
                                          width: 0,
                                          child: Text(''),
                                        )
                                ],
                              ),

                              ///审批索引
                              _BuildProcessIndex(
                                index: i,
                              ),
                            ],
                          )
                      else
                        Container(
                          height: 0,
                          width: 0,
                          child: Text(''),
                        )
                    ],
                  ),
                );
              },
            ),
          ),
        ],
      ),

      /// 底部按钮
      bottomSheet: _BottomComponent(),
    );
  }
}

/// 审批流程索引
class _BuildProcessIndex extends StatelessWidget {
  const _BuildProcessIndex({Key? key, this.index}) : super(key: key);
  final num? index;
  @override
  Widget build(BuildContext context) {
    final store = Provider.of<DetailStore>(context, listen: false);
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    final item = store.taskDetail!.traces![index as int];
    return Positioned(
      left: 0,
      top: 0,
      bottom: 0,
      child: Wisdom.column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Wisdom(
            minWidth: 17.pt,
            padding: EdgeInsets.symmetric(horizontal: 3.pt),
            height: 17.pt,
            borderRadius: BorderRadius.circular(10.pt),
            alignment: Alignment.center,
            color: item.action == "驳回"
                ? Colors.white
                : index == (store.taskDetail!.traces!.length - 1) &&
                        store.taskDetail?.activeTaskName != 'end'
                    ? colorScheme.background
                    : index == (store.taskDetail!.traces!.length - 2) &&
                            item.taskName == store.taskDetail?.activeTaskName
                        ? colorScheme.primary
                        : Colors.white,
            border: Border.all(
              color: _processIndexColor(
                  context,
                  item,
                  index,
                  store.taskDetail!.traces!.length,
                  false,
                  store.taskDetail?.activeTaskName),
            ),
            child: Text(
              (index! + 1).toString(),
              style: TextStyle(
                color: _processIndexColor(
                    context,
                    item,
                    index,
                    store.taskDetail!.traces!.length,
                    true,
                    store.taskDetail?.activeTaskName),
                fontSize: 11.pt,
              ),
            ),
          ),
          Wisdom(
            margin: EdgeInsets.symmetric(horizontal: 8.pt),
            width: 1.pt,
            color: _processIndexColor(
              context,
              item,
              index,
              store.taskDetail!.traces!.length,
              false,
              store.taskDetail?.activeTaskName,
            ),
          ).asExpanded(),
        ],
      ),
    );
  }
}

/// 底部操作按钮
class _BottomComponent extends StatefulWidget {
  _BottomComponent({Key? key}) : super(key: key);

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

class __BottomComponentState extends State<_BottomComponent> {
  final modalformKey = GlobalKey<FormState>();
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final _store = Provider.of<DetailStore>(context, listen: false);
    final style = WTheme.of(context);
    final colorScheme = style.colorScheme;
    return Observer(
      builder: (BuildContext context) {
        if (_store.taskDetail != null &&
            _store.taskDetail?.firstNode != null &&
            _store.taskDetail!.firstNode! &&
            _store.taskDetail?.operateAble != null &&
            _store.taskDetail!.operateAble!)
          return BottomAppBar(
            child: Wisdom.row(
              height: 60.pt,
              padding: EdgeInsets.symmetric(horizontal: 15.pt, vertical: 8.pt),
              children: <Widget>[
                Wisdom(
                  borderRadius: BorderRadius.circular(25.pt),
                  padding:
                      EdgeInsets.symmetric(horizontal: 15.pt, vertical: 5.pt),
                  margin: EdgeInsets.only(right: 9.pt),
                  border: Border.all(
                    color: colorScheme.red,
                    width: 1.pt,
                  ),
                  onTap: () => _store.onTerminateTask(),
                  width: 125.pt,
                  alignment: Alignment.center,
                  child: WisText(
                    '终止',
                    size: 18.pt,
                    color: colorScheme.red,
                  ),
                ),
                Expanded(
                  child: Wisdom(
                    borderRadius: BorderRadius.circular(25.pt),
                    onTap: () => _store.onToute2TaskDetail(),
                    color: colorScheme.primary,
                    child: Wisdom(
                      alignment: Alignment.center,
                      child: WisText.white('提交审批', size: 18.pt),
                    ),
                  ),
                ),
              ],
            ),
          );
        else if (_store.taskDetail != null &&
            _store.taskDetail?.firstNode != null &&
            !_store.taskDetail!.firstNode! &&
            _store.taskDetail?.operateAble != null &&
            _store.taskDetail!.operateAble!)
          return BottomAppBar(
            child: Wisdom.row(
              height: 60.pt,
              padding: EdgeInsets.symmetric(horizontal: 15.pt, vertical: 8.pt),
              children: <Widget>[
                Wisdom(
                  borderRadius: BorderRadius.circular(25.pt),
                  margin: EdgeInsets.only(right: 9.pt),
                  border: Border.all(
                    color: colorScheme.red,
                    width: 1.pt,
                  ),
                  onTap: () => _RejectDialogComponent.show(
                      context,
                      'reject',
                      '驳回',
                      _store.taskDetail?.activeTaskId,
                      _store.taskDetail?.audit),
                  width: 125.pt,
                  alignment: Alignment.center,
                  child: WisText(
                    '驳回',
                    size: 18.pt,
                    color: colorScheme.red,
                  ),
                ),
                Expanded(
                  child: Wisdom(
                    borderRadius: BorderRadius.circular(25.pt),
                    onTap: () => _RejectDialogComponent.show(
                        context,
                        'approve',
                        '同意',
                        _store.taskDetail?.activeTaskId,
                        _store.taskDetail?.audit),
                    color: colorScheme.primary,
                    child: Wisdom(
                      alignment: Alignment.center,
                      child: WisText.white('同意', size: 18.pt),
                    ),
                  ),
                ),
              ],
            ),
          );
        else
          return Container(
            height: 0,
            width: 0,
            child: Text(''),
          );
      },
    );
  }
}

/// 索引颜色
_processIndexColor(context, item, index, length, isText, activeTask) {
  final style = WTheme.of(context);
  final colorScheme = style.colorScheme;
  if (item.action == "驳回") {
    return Color(0xffF6595D);
  }
  if (index == (length - 1)) {
    if (activeTask != 'end') {
      return isText ? colorScheme.minor : colorScheme.divider;
    } else {
      return colorScheme.success;
    }
  }
  if (index == (length - 2)) {
    if (activeTask != item.taskName) {
      return colorScheme.success;
    } else {
      return isText ? Colors.white : colorScheme.primary;
    }
  }
  return colorScheme.success;
}
