part of user_order_evaluate;

/// 用户订单评价
class UserOrderEvaluatePage extends StatefulWidget {

  final String orderNum; // 订单号
  final OrderInfoModel orderInfoModel; // 订单详情
  const UserOrderEvaluatePage({
    Key? key,
    required this.orderNum,
    required this.orderInfoModel,
  }) : super(key: key);

  @override
  State<UserOrderEvaluatePage> createState() => _UserOrderEvaluatePageState();
}

class _UserOrderEvaluatePageState extends State<UserOrderEvaluatePage> with AutomaticKeepAliveClientMixin{
  List<OrderEvaluate> orderEvaluates = [];
  List<double> ratings = [];
  int _index = 0;
  // late FocusNode _focusNode;
  @override
  void initState() {
      // myController = Get.put(UserOrderEvaluateController(widget.orderNum));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // super.build(context);
    return WillPopScope(
        onWillPop: () async {
      context.pop(true);
      return false;
    },
    child:GetBuilder<UserOrderEvaluateController>(
      init: UserOrderEvaluateController(widget.orderNum),
      builder: (controller) =>  Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: const Text('订单评价'),
        ),
        body:
        GestureDetector(
          onTap: () {
            controller.focusNodes[_index]!.unfocus();
          },
          child: (controller.orderInfoModel==null ||controller.orderInfoModel.bookList==null)?
          Container(
            alignment: Alignment.center,
            child: const CircularProgressIndicator(),):
          Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      ListView.builder(
                        physics: const NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemBuilder: (BuildContext context, int index) {
                          _index = index;
                          return listItem(
                              controller.orderInfoModel.bookList![index],index,controller
                            /*orderEvaluates,*//*controllers*/);
                        },
                        itemCount: controller.orderInfoModel.bookList?.length,
                      ),
                    ],
                  ),
                ),
              ),
              SizedBox(
                height: 26.w,
              ),
              Container(
                margin: EdgeInsets.symmetric(horizontal: 10.w),
                child: CustomGradientButton(
                  text: '提交评价',
                  isEnabled: controller.enable,
                  onPressed: () async {
                    controller.focusNodes[_index]!.unfocus();
                    print(jsonEncode(orderEvaluates));
                    Future<bool> result = controller.UpOrderEvaluate(jsonEncode(orderEvaluates));
                    if(await result){
                      context.pop(true);
                    }
                  },
                ),
              ),
              SizedBox(
                height: 41.w,
              )
            ],
          ),
        ),
      ),),);
  }

  Widget listItem(BookListModel bookListModel,int index,UserOrderEvaluateController myController) {
    // myController.updateText(bookListModel.comments.toString());
    // _focusNode = myController.focusNodes[index]!;
    int indexToUpdate = orderEvaluates.indexWhere((obj) => obj.recordId == bookListModel.recordId);
    if(indexToUpdate==-1 && myController.judgeComments(bookListModel)){
      OrderEvaluate evaluate = OrderEvaluate(recordId: bookListModel.recordId,rating: bookListModel.rating,comments: bookListModel.comments);
      orderEvaluates.add(evaluate);
      indexToUpdate = orderEvaluates.length-1;
    }
    return Container(
      margin:
          EdgeInsets.only(left: 10.w, top: 10.w, right: 10.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.w),
        color: const Color(0xFFF9F9F9),
        boxShadow: [
          BoxShadow(
            color: const Color(0xFFC7C7C7).withOpacity(0.5),
            offset: Offset(3.w, 0),
            blurRadius: 7.w,
            spreadRadius: 0.w,
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8.w),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 图书容器
            Container(
              color: Colours.cF8,
              padding: EdgeInsets.symmetric(horizontal: 11.w, vertical: 12.w),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    padding: EdgeInsets.all(2.w),
                    height: 88.w,
                    width: 73,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(4.w),
                      color: Colors.white,
                      boxShadow: [
                        BoxShadow(
                          color: const Color(0xFF707070).withOpacity(0.5),
                          offset: const Offset(0, 0),
                          blurRadius: 4.5.w,
                          spreadRadius: 0.w,
                        ),
                      ],
                    ),
                    child: Image.network(
                      // 'http://zxts-book-file.zijingebook.com/2024-01/29/b91194564969b9151fa382807977282acdffa22d.jpg',
                      bookListModel.img.toString(),
                      // 用实际图片链接替换
                      fit: BoxFit.cover,
                    ),
                  ),
                  Gaps.hGaps10,
                  Expanded(
                    child: Text(
                      bookListModel.name.toString(),
                      style: TextStyle(
                          fontSize: 13.w,
                          height: 1.5,
                          fontWeight: Fonts.boldSemi,
                          color: Colours.c3),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
            ),
            // 评价容器
            Container(
              padding: EdgeInsets.only(
                top: 1.w,
              ),
              width: double.infinity,
              height: 160.w,
              color: Colors.white,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height:15.w),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Container(
                        padding: EdgeInsets.only(left: 10.w),
                        child: const Text('评分'),
                      ),
                      Gaps.hGaps20,
                      AbsorbPointer(
                        absorbing: bookListModel.rating!.toDouble()>0,
                        child: CustomRating(
                          max: 5,
                          score:bookListModel.rating !=null ?bookListModel.rating!.toDouble():0,
                          star: Star(
                            fat: 0.5,
                            progress: 3,
                            fillColor: AppTheme.primary,
                            size: 16.w,
                            emptyColor: Colours.cE2,
                          ),
                          onRating: (double) {
                            orderEvaluates[indexToUpdate].rating=double;
                            myController.setCanClick(double: double);
                            print(double);
                          },
                        ),
                      ),
                    ],
                  ),
                  TextField(
                    style:
                    TextStyle(fontSize: 14.w, color: Colours.c3),
                    decoration: InputDecoration(
                        focusedBorder: InputBorder.none,
                        border: InputBorder.none,
                        enabledBorder: InputBorder.none,
                        disabledBorder: InputBorder.none,
                        errorBorder: InputBorder.none,
                        fillColor: Colors.white,
                        hintText: '请简要描述',
                        hintStyle: TextStyle(
                            fontSize: 14.w, height: 1.5, color: Colours.c6)),
                    maxLines: 5,
                    onChanged: (text){
                      orderEvaluates[indexToUpdate].comments=myController._commentsControllers[index].text;
                      myController.setCanClick(double:orderEvaluates[indexToUpdate].rating??0);
                    },
                    focusNode: myController.focusNodes[index],
                    controller: myController._commentsControllers[index],
                    enabled: myController.ratings[index]!>0?false:true,
                    onTap: () {
                      // 在文本框获取焦点时，将光标移动到文本末尾
                      myController._commentsControllers[index].selection = TextSelection.fromPosition(
                        TextPosition(offset: myController._commentsControllers[index].text.length),
                      );
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
