import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:flutterflow_ui/flutterflow_ui.dart';
import 'package:timeline_tile/timeline_tile.dart';
import 'package:vbvs_app/common/color/appColors.dart';
import 'package:vbvs_app/common/color/appFontsize.dart';
import 'package:vbvs_app/common/color/repair_status.dart';
import 'package:vbvs_app/common/util/FitTool.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/controller/mh_controller/repair_process.dart';
import 'package:vbvs_app/pages/mh_page/repair_process_widget.dart';

import '../../component/img/img_preview_widget.dart';
import '../../controller/mh_controller/apply_repair_controller.dart';
import '../../controller/mh_controller/repair_info_controller.dart';

class RepairHistoryListPage extends GetView<RepairInfoController> {
  Map data;
  RepairHistoryListPage({Key? key, required this.data});
  final scaffoldKey = GlobalKey<ScaffoldState>();

  BoxConstraints? bodysize;

  @override
  Widget build(BuildContext context) {
    // controller.model.applyRepairModel = ApplyRepairModel()
    //   ..id = 1001
    //   ..apply_name = '张三'
    //   ..tel = '13812345678'
    //   ..desc = '床垫传感器失灵，无法监测心率和呼吸'
    //   ..create_time = DateTime.parse('2025-05-01 10:00:00')
    //   ..device_type = 1
    //   ..device_category = 'BY-H'
    //   ..device_id = 'BD202505011001'
    //   ..device_name = '智能床垫 BY-H 型号'
    //   ..issue_img = [
    //     'https://example.com/img1.jpg',
    //     'https://example.com/img2.jpg'
    //   ]
    //   ..imagesLImit = 3
    //   ..img_bucket = 'mianhuatang_repair'
    //   ..status = '待处理'
    //   ..select_device = '床垫/BY-H/智能床垫'
    //   ..device_list = ['床垫/BY-H/智能床垫', '床垫/BY-A/智能床垫', '床垫/BY-C/智能床垫']
    //   ..score = null
    //   ..score_time = null
    //   ..messageType = 1
    //   ..repairId = 1001;

    controller.model.repairProcessList = [
      RepairProcessModel()
        ..status = '申请提交'
        ..create_time = DateTime.parse('2025-05-01 10:05:00')
        ..desc = '用户提交了维修申请'
        ..record_id = 1001
        ..deal_user = null,
      RepairProcessModel()
        ..status = '客服受理'
        ..create_time = DateTime.parse('2025-05-01 10:20:00')
        ..desc = '客服已联系用户确认问题'
        ..record_id = 1001
        ..deal_user = 2001,
      RepairProcessModel()
        ..status = '维修完成'
        ..create_time = DateTime.parse('2025-05-02 15:30:00')
        ..desc = '维修人员完成修复，等待用户确认'
        ..record_id = 1001
        ..deal_user = 3001,
    ];

    final List events = controller.model.repairProcessList;
    return LayoutBuilder(builder: (context, cc) {
      bodysize = cc;
      return WillPopScope(
        child: GestureDetector(
            onTap: () => FocusScope.of(context).unfocus(),
            child: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/new_background.png'), // 本地图片
                  fit: BoxFit.fill, // 填满整个 Container
                ),
              ),
              child: Scaffold(
                // key: scaffoldKey,
                backgroundColor: Colors.transparent,
                appBar: AppBar(
                  backgroundColor: Colors.transparent,
                  iconTheme: const IconThemeData(color: Colors.white),
                  automaticallyImplyLeading: false,
                  titleSpacing: 0,
                  title: SizedBox(
                    width: double.infinity,
                    height: 180.rpx,
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        // 中间居中的标题
                        Text(
                          '详情',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 30.rpx,
                          ),
                        ),
                        // 左侧图标
                        Positioned(
                          left: 0.rpx,
                          child: returnIconButtomNew,
                        ),
                      ],
                    ),
                  ),
                  centerTitle: false,
                ),

                body: Container(
                  width: bodysize!.maxWidth,
                  height: bodysize!.maxHeight * 1,
                  child: Column(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      Expanded(
                        child: Padding(
                          padding: EdgeInsetsDirectional.fromSTEB(
                              30.rpx, 30.rpx, 30.rpx, 0),
                          child: Container(
                            width: bodysize!.maxWidth,
                            height: bodysize!.maxHeight * 1,
                            child: SingleChildScrollView(
                              child: Column(
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  Padding(
                                    padding: EdgeInsetsDirectional.fromSTEB(
                                        0, 0, 0, 20.rpx),
                                    child: Container(
                                      width: MediaQuery.sizeOf(context).width,
                                      decoration: BoxDecoration(
                                        color: Color(0xFF003058), //true
                                        borderRadius: BorderRadius.circular(8),
                                      ),
                                      child: Padding(
                                          padding:
                                              EdgeInsetsDirectional.fromSTEB(
                                                  34.rpx, 10, 0, 0),
                                          child: Container(
                                            decoration: const BoxDecoration(),
                                            child: Column(
                                              mainAxisSize: MainAxisSize.max,
                                              children: [
                                                Align(
                                                  alignment:
                                                      const AlignmentDirectional(
                                                          -1, 0),
                                                  child: Text(
                                                    // 'SWES01号智能一键入眠床',
                                                    data['device'][0]['name'] ??
                                                        '未命名',
                                                    style: TextStyle(
                                                      fontFamily: 'Readex Pro',
                                                      fontSize: 30.rpx,
                                                      letterSpacing: 0,
                                                      color: Colors.white,
                                                    ),
                                                  ),
                                                ),
                                                Align(
                                                  alignment:
                                                      const AlignmentDirectional(
                                                          -1, 0),
                                                  child: Text(
                                                    '系列：' +
                                                        (data['device'][0][
                                                                'device_category'] ??
                                                            '未命名'),
                                                    style: TextStyle(
                                                      fontFamily: 'Readex Pro',
                                                      color: const Color(
                                                          0xFF929699),
                                                      fontSize: 26.rpx,
                                                      letterSpacing: 0,
                                                    ),
                                                  ),
                                                ),
                                                Align(
                                                  alignment:
                                                      const AlignmentDirectional(
                                                          -1, 0),
                                                  child: Text(
                                                    '类型：' +
                                                        getDeviceTypeName(
                                                          controller
                                                              .model
                                                              .applyRepairModel
                                                              ?.device_type,
                                                        ),
                                                    style: TextStyle(
                                                      fontFamily: 'Readex Pro',
                                                      color: const Color(
                                                          0xFF929699),
                                                      fontSize: 26.rpx,
                                                      letterSpacing: 0,
                                                    ),
                                                  ),
                                                ),
                                                Align(
                                                  alignment:
                                                      const AlignmentDirectional(
                                                          -1, 0),
                                                  child: Text(
                                                    '序列号：' +
                                                        (controller
                                                                .model
                                                                .applyRepairModel!
                                                                .device_id ??
                                                            '未命名'),
                                                    style: TextStyle(
                                                      fontFamily: 'Readex Pro',
                                                      color: const Color(
                                                          0xFF929699),
                                                      fontSize: 26.rpx,
                                                      letterSpacing: 0,
                                                    ),
                                                  ),
                                                ),
                                                Align(
                                                  alignment:
                                                      const AlignmentDirectional(
                                                          -1, 0),
                                                  child: Text(
                                                    '报修单号：' +
                                                        (controller
                                                                .model
                                                                .applyRepairModel!
                                                                .id
                                                                .toString() ??
                                                            '未命名'),
                                                    style: TextStyle(
                                                      fontFamily: 'Readex Pro',
                                                      color: const Color(
                                                          0xFF929699),
                                                      fontSize: 26.rpx,
                                                      letterSpacing: 0,
                                                    ),
                                                  ),
                                                ),
                                                Align(
                                                  alignment:
                                                      const AlignmentDirectional(
                                                          -1, 0),
                                                  child: Text(
                                                    '提交时间：' +
                                                        (MyUtils.formatDateTimeDay(
                                                            data['device'][0][
                                                                'create_time']!)),
                                                    style: TextStyle(
                                                      fontFamily: 'Readex Pro',
                                                      color: const Color(
                                                          0xFF929699),
                                                      fontSize: 26.rpx,
                                                      letterSpacing: 0,
                                                    ),
                                                  ),
                                                ),
                                                Align(
                                                  alignment:
                                                      const AlignmentDirectional(
                                                          -1, 0),
                                                  child: Text(
                                                    '问题描述：' +
                                                        (data['device'][0]
                                                                ['desc'] ??
                                                            '未命名'),
                                                    style: TextStyle(
                                                      fontFamily: 'Readex Pro',
                                                      color: const Color(
                                                          0xFF929699),
                                                      fontSize: 26.rpx,
                                                      letterSpacing: 0,
                                                    ),
                                                  ),
                                                ),
                                                Padding(
                                                    padding:
                                                        const EdgeInsetsDirectional
                                                            .fromSTEB(
                                                            0, 10, 0, 24),
                                                    child: Container(
                                                      width: MediaQuery.sizeOf(
                                                              context)
                                                          .width,
                                                      height: MediaQuery.sizeOf(
                                                                  context)
                                                              .height *
                                                          0.15,
                                                      constraints:
                                                          const BoxConstraints(

                                                              // minHeight: 140,
                                                              ),
                                                      child: Container(
                                                          width: 100,
                                                          height: 100,
                                                          child: Obx(() =>
                                                              ListView(
                                                                  shrinkWrap:
                                                                      true,
                                                                  scrollDirection:
                                                                      Axis
                                                                          .horizontal,
                                                                  children: getImage(controller
                                                                          .model
                                                                          .applyRepairModel!)
                                                                      .divide(
                                                                          const SizedBox(
                                                                        width:
                                                                            12,
                                                                      ))
                                                                      .addToStart(
                                                                          const SizedBox(
                                                                        width:
                                                                            0,
                                                                      ))))),
                                                    )),
                                              ]
                                                  .divide(
                                                      const SizedBox(height: 5))
                                                  .addToStart(const SizedBox(
                                                    height: 5,
                                                  )),
                                            ),
                                          )),
                                    ),
                                  ),
                                  Padding(
                                    padding:
                                        const EdgeInsetsDirectional.fromSTEB(
                                            0, 25, 0, 25), // 设置上下间距为 34
                                    child: Align(
                                      alignment: AlignmentDirectional
                                          .centerStart, // 文字左对齐
                                      child: Text(
                                        '报修状态',
                                        style: TextStyle(
                                          fontFamily: 'Readex Pro',
                                          color: Colors.white,
                                          fontSize: 30.rpx,
                                          letterSpacing: 0.0,
                                        ),
                                      ),
                                    ),
                                  ),
                                  Container(
                                    width: bodysize!.maxWidth, // 设置宽度自适应
                                    child: ListView.builder(
                                      shrinkWrap: true, // 让ListView根据内容自适应高度
                                      physics:
                                          const NeverScrollableScrollPhysics(), // 禁用内部滚动，交由外部滚动视图处理
                                      itemCount: events.length,
                                      itemBuilder: (context, index) {
                                        bool isLast =
                                            index == events.length - 1;
                                        return TimelineTile(
                                          isFirst: index == 0,
                                          isLast: isLast,
                                          axis:
                                              TimelineAxis.vertical, // 垂直方向时间轴
                                          alignment:
                                              TimelineAlign.start, // 线条左对齐
                                          lineXY: 0.5, // 线条和圆圈相对位置
                                          indicatorStyle: IndicatorStyle(
                                            width: 15, // 圆圈的宽度
                                            padding: const EdgeInsets.all(
                                                1), // 避免线条进入圆圈内部
                                            indicatorXY: 0.2, // 圆圈居中
                                            indicator: Container(
                                              decoration: BoxDecoration(
                                                shape: BoxShape.circle,
                                                border: Border.all(
                                                  color: const Color(
                                                      0xFFC8CBD2), // 最后一个元素为蓝色
                                                  width: 1,
                                                ),
                                                color: stringToColor("#C8CBD2"),
                                              ),
                                            ),
                                          ),
                                          beforeLineStyle: LineStyle(
                                            color: stringToColor(
                                                "#C8CBD2"), // 上方线条颜色
                                            thickness: 1, // 线条厚度
                                          ),
                                          afterLineStyle: LineStyle(
                                            color: stringToColor(
                                                "#C8CBD2"), // 最后一个节点的线条颜色
                                            thickness: 1, // 线条厚度
                                          ),
                                          endChild: Padding(
                                            padding: const EdgeInsets.all(8.0),
                                            child: RepairStatusWidget(
                                              index: index,
                                              repairInfoController: controller,
                                            ),
                                          ),
                                        );
                                      },
                                    ),
                                  ),
                                  Obx(() {
                                    if (RepairStatus.completed ==
                                            controller.model.applyRepairModel!
                                                .status &&
                                        controller.model.applyRepairModel!
                                                .score ==
                                            null) {
                                      return Align(
                                        alignment:
                                            const AlignmentDirectional(1, 0),
                                        child: Padding(
                                          padding:
                                              EdgeInsetsDirectional.fromSTEB(
                                                  34.rpx, 66.rpx, 0, 48.rpx),
                                          child: Container(
                                            width: 61,
                                            height: MediaQuery.sizeOf(context)
                                                    .height *
                                                0.03,
                                            constraints: const BoxConstraints(
                                              minHeight: 24,
                                            ),
                                            decoration: const BoxDecoration(),
                                            child: FFButtonWidget(
                                              onPressed: () {
                                                Get.toNamed("/scorePage");
                                              },
                                              text: '待评价',
                                              options: FFButtonOptions(
                                                height: 40,
                                                padding:
                                                    const EdgeInsetsDirectional
                                                        .fromSTEB(0, 0, 0, 0),
                                                iconPadding:
                                                    const EdgeInsetsDirectional
                                                        .fromSTEB(0, 0, 0, 0),
                                                // color: FlutterFlowTheme.of(context)
                                                //     .secondaryBackground,
                                                color: Colors.white,
                                                textStyle: TextStyle(
                                                  fontFamily: 'Readex Pro',
                                                  // color: Color(0xFF333333),
                                                  // color: stringToColor("#D3B684"),
                                                  color:
                                                      stringToColor("#117EFD"),
                                                  fontSize: 11,
                                                  letterSpacing: 0,
                                                ),
                                                elevation: 0,
                                                borderSide: BorderSide(
                                                  // color: Color(0xFFC8CBD2),
                                                  // color: stringToColor("#D3B684"),
                                                  color:
                                                      stringToColor("#117EFD"),
                                                  width: 1,
                                                ),
                                                borderRadius:
                                                    BorderRadius.circular(50),
                                              ),
                                            ),
                                          ),
                                        ),
                                      );
                                    }
                                    return Container();
                                  }),
                                  Obx(() {
                                    if (RepairStatus.completed ==
                                            controller.model.applyRepairModel!
                                                .status &&
                                        controller.model.applyRepairModel!
                                                .score !=
                                            null) {
                                      return Padding(
                                        padding: EdgeInsetsDirectional.fromSTEB(
                                            0, 0, 0, 10.rpx),
                                        child: Container(
                                          width:
                                              MediaQuery.sizeOf(context).width,
                                          decoration: BoxDecoration(
                                            color: Colors.white, //true
                                            borderRadius:
                                                BorderRadius.circular(16.rpx),
                                          ),
                                          child: Padding(
                                            padding: const EdgeInsetsDirectional
                                                .fromSTEB(0, 0, 0, 0),
                                            child: Container(
                                              decoration: const BoxDecoration(),
                                              child: Column(
                                                mainAxisSize: MainAxisSize.max,
                                                children: [
                                                  Padding(
                                                    padding:
                                                        const EdgeInsetsDirectional
                                                            .fromSTEB(
                                                            17, 0, 30, 10),
                                                    child: Container(
                                                      width: MediaQuery.sizeOf(
                                                              context)
                                                          .width,
                                                      height: 30,
                                                      decoration:
                                                          const BoxDecoration(),
                                                      child: Align(
                                                        alignment:
                                                            const AlignmentDirectional(
                                                                -1, 0),
                                                        child: Text(
                                                          '评价状态',
                                                          style: TextStyle(
                                                            fontFamily:
                                                                'Readex Pro',
                                                            color: const Color(
                                                                0xFF333333),
                                                            fontSize: 15,
                                                            letterSpacing: 0.0,
                                                          ),
                                                        ),
                                                      ),
                                                    ),
                                                  ),
                                                  Align(
                                                    alignment:
                                                        const AlignmentDirectional(
                                                            -1, 0),
                                                    child: Padding(
                                                      padding:
                                                          EdgeInsetsDirectional
                                                              .fromSTEB(34.rpx,
                                                                  0, 0, 0),
                                                      child: Container(
                                                        width:
                                                            MediaQuery.sizeOf(
                                                                    context)
                                                                .width,
                                                        constraints:
                                                            const BoxConstraints(
                                                          minHeight: 24,
                                                        ),
                                                        decoration:
                                                            const BoxDecoration(),
                                                        child: // Generated code for this Column Widget...
                                                            Column(
                                                          mainAxisSize:
                                                              MainAxisSize.max,
                                                          children: [
                                                            Align(
                                                              alignment:
                                                                  const AlignmentDirectional(
                                                                      -1, 0),
                                                              child: Padding(
                                                                padding: EdgeInsetsDirectional
                                                                    .fromSTEB(
                                                                        0,
                                                                        0,
                                                                        0,
                                                                        20.rpx),
                                                                child: Text(
                                                                  // '2023-08-22 12:12:44',
                                                                  MyUtils.formatDateTime(
                                                                      controller
                                                                          .model
                                                                          .applyRepairModel!
                                                                          .score_time!),
                                                                  style:
                                                                      TextStyle(
                                                                    fontFamily:
                                                                        'Readex Pro',
                                                                    fontSize:
                                                                        AppFontsize
                                                                            .normal_text_size,
                                                                    letterSpacing:
                                                                        0.0,
                                                                  ),
                                                                ),
                                                              ),
                                                            ),
                                                            Row(
                                                              mainAxisSize:
                                                                  MainAxisSize
                                                                      .max,
                                                              children: [
                                                                Align(
                                                                  alignment:
                                                                      const AlignmentDirectional(
                                                                          -1,
                                                                          0),
                                                                  child:
                                                                      Padding(
                                                                    padding:
                                                                        const EdgeInsetsDirectional
                                                                            .fromSTEB(
                                                                            0,
                                                                            0,
                                                                            5,
                                                                            0),
                                                                    child: Text(
                                                                      '已评价',
                                                                      style:
                                                                          TextStyle(
                                                                        fontFamily:
                                                                            'Readex Pro',
                                                                        fontSize:
                                                                            AppFontsize.normal_text_size,
                                                                        letterSpacing:
                                                                            0.0,
                                                                      ),
                                                                    ),
                                                                  ),
                                                                ),
                                                                Icon(
                                                                  Icons.star,
                                                                  color: controller
                                                                              .model
                                                                              .applyRepairModel!
                                                                              .score! >=
                                                                          1
                                                                      ? stringToColor(
                                                                          "#F8AE00")
                                                                      : stringToColor(
                                                                          "#D0D0D0"),
                                                                  size: 14,
                                                                ),
                                                                Icon(
                                                                  Icons.star,
                                                                  color: controller
                                                                              .model
                                                                              .applyRepairModel!
                                                                              .score! >=
                                                                          2
                                                                      ? stringToColor(
                                                                          "#F8AE00")
                                                                      : stringToColor(
                                                                          "#D0D0D0"),
                                                                  size: 14,
                                                                ),
                                                                Icon(
                                                                  Icons.star,
                                                                  color: controller
                                                                              .model
                                                                              .applyRepairModel!
                                                                              .score! >=
                                                                          3
                                                                      ? stringToColor(
                                                                          "#F8AE00")
                                                                      : stringToColor(
                                                                          "#D0D0D0"),
                                                                  size: 14,
                                                                ),
                                                                Icon(
                                                                  Icons.star,
                                                                  color: controller
                                                                              .model
                                                                              .applyRepairModel!
                                                                              .score! >=
                                                                          4
                                                                      ? stringToColor(
                                                                          "#F8AE00")
                                                                      : stringToColor(
                                                                          "#D0D0D0"),
                                                                  size: 14,
                                                                ),
                                                                Icon(
                                                                  Icons.star,
                                                                  color: controller
                                                                              .model
                                                                              .applyRepairModel!
                                                                              .score! >=
                                                                          5
                                                                      ? stringToColor(
                                                                          "#F8AE00")
                                                                      : stringToColor(
                                                                          "#D0D0D0"),
                                                                  size: 14,
                                                                ),
                                                              ],
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                    ),
                                                  ),
                                                ]
                                                    .divide(const SizedBox(
                                                        height: 0))
                                                    .addToStart(const SizedBox(
                                                      height: 5,
                                                    ))
                                                    .addToEnd(const SizedBox(
                                                      height: 15,
                                                    )),
                                              ),
                                            ),
                                          ),
                                        ),
                                      );
                                    }
                                    return Container();
                                  }),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            )),
        onWillPop: () async {
          // 处理返回事件，比如弹出提示框等
          print("页面返回事件");
          return true; // 返回 true 允许页面返回，返回 false 阻止页面返回
        },
      );
    });
  }

  List<Widget> getImage(ApplyRepairModel applyRepairModel) {
    List<Widget> images = [];
    ApplyRepairController controller = Get.find();
    applyRepairModel.issue_img!.forEach((element) async {
      images.add(
        Container(
          // height: 10,
          // width: 10,

          child: ImgPreviewWidget(
            imgUrl: element,
            index: applyRepairModel.issue_img!.indexOf(element),
            applyRepairController: controller,
            isDel: false,
          ),
        ),
      );
    });

    return images;
  }

  String getDeviceTypeName(int? type) {
    switch (type) {
      case 1:
        return '体征检测设备';
      case 2:
        return '智能床';
      case 3:
        return '智能床垫';
      default:
        return '未知设备';
    }
  }
}
