import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:liftmanager/internal/repair/repair_router.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/image_utils.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/click_item.dart';
import 'package:liftmanager/widgets/star_item.dart';

class RepairEvaluatePage extends StatefulWidget {
  RepairEvaluatePage(this.id,{this.isLook=false,this.service="0",this.star="0",this.advice="",this.imgUrl=""});
  final String id;
  final bool isLook;
  final String service;
  final String star;
  final String advice;
  final String imgUrl;


  @override
  State<StatefulWidget> createState() {
    if(isLook){
      return RepairEvaluatePageState(double.parse(this.service),double.parse(this.star),this.advice,this.imgUrl);
    }else{
      return RepairEvaluatePageState(0.0,0.0,"","");
    }

  }
}

class RepairEvaluatePageState extends State<RepairEvaluatePage> {
  RepairEvaluatePageState(service,star,advice,imgUrl){
    serviceLevel = service;
    starLevel = star;
    _controller.text = advice;
    mainSignImg = Image.network(imgUrl);
  }
  TextEditingController _controller = TextEditingController();
  double serviceLevel = 0;
  double starLevel = 0;
  var mainSignImgByte;
  Image mainSignImg = Image.asset(
    "assets/images/img_sign.png",
  );

  ///保存
  _saveEvaluate() async {
    if (mainSignImgByte == null) {
      toasts("请签名");
      return;
    }
    if (_controller.text.toString().length == 0) {
      toasts("请评价");
      return;
    }
    if (serviceLevel < 1 || serviceLevel > 5) {
      toasts("请给服务打分");
    }
    if (starLevel < 1 || starLevel > 5) {
      toasts("请给满意度打分");
    }
    String file = await ImageUtils()
        .saveCacheImageFile(mainSignImgByte, "rep_evaluate_${widget.id}");
    showLoading(context, "正在提交...");
    ApiService(context: context).upload(file, onSuccess: (data) {
      ApiService(context: context).repairEvaluate(
          widget.id, _controller.text.toString(), serviceLevel, starLevel, data,
          onSuccess: (data) {
            dismissLoading(context);
            showAlert(context, "提示", "评价成功", "确定", (){
              NavigatorUtils.goBack(context);
              NavigatorUtils.goBackWithParams(context,true);
            });
      }, onError: (code, msg) {
        toasts(msg);
        dismissLoading(context);
      });
    }, onError: (code, msg) {
      toasts(msg);
      dismissLoading(context);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //resizeToAvoidBottomPadding: false,
      appBar: MyAppBar(
        centerTitle: "急修评价",
        actions:widget.isLook?null: <Widget>[
          FlatButton(
            child: Text("保存", key: const Key('actionName')),
            textColor: Colours.dark_text,
            highlightColor: Colors.transparent,
            onPressed: () {
              _saveEvaluate();
            },
          )
        ],
      ),
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: defaultTargetPlatform == TargetPlatform.iOS
                  ? FormKeyboardActions(child: _buildBody())
                  : SingleChildScrollView(child: _buildBody()),
            )
          ],
        ),
      ),
    );
  }

  _buildBody() {
    return Padding(
        padding: EdgeInsets.only(bottom: 30),
        child: Container(
            color: ThemeUtils.getBackgroundColor(context),
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  StarItem(
                    title: "服务态度",
                    starRating: serviceLevel,
                    onRatingChanged:widget.isLook?null: (res){
                      serviceLevel = res;
                      setState(() {

                      });
                    },
                  ),
                  StarItem(
                    title: "急修满意度",
                    starRating: starLevel,
                    onRatingChanged:widget.isLook?null: (res){
                      starLevel = res;
                      setState(() {

                      });
                    },
                  ),
                  Gaps.vGap8,
                  ClickItem(title: "客户评价"),
                  Container(
                    color: ThemeUtils.getTabsBg(context),
                    child: Padding(
                      padding: const EdgeInsets.only(
                          top: 5, left: 15.0, right: 15.0, bottom: 8.0),
                      child: TextField(
                        enabled: !widget.isLook,
                          maxLength: 100,
                          maxLines: 8,
                          autofocus: false,
                          controller: _controller,
//                    keyboardType: widget.keyboardType,
                          //style: TextStyles.textDark14,
                          decoration: InputDecoration(
                              hintText: "填写现场情况描述",
                              border: InputBorder.none,
                              hintStyle: TextStyles.textGray14)),
                    ),
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  ClickItem(title: "客户手写签名", content: ""),
                  GestureDetector(
                    onTap: () {
                      if(widget.isLook){
                        return;
                      }
                      NavigatorUtils.pushResult(
                          context, RepairRouter.repairSignaturePage, (result) {
                        if (result != null) {
                          mainSignImgByte = result;
                          Image image = Image.memory(result);
                          setState(() {
                            mainSignImg = image;
                          });
                        }
                      });
                    },
                    child: Container(
                      height: 200,
                      color: ThemeUtils.getTabsBg(context),
                      alignment: Alignment.center,
                      child: Stack(
                        alignment: Alignment.center,
                        children: <Widget>[
                          Positioned(
                            child: Text(
                              "手写签名",
                              style: TextStyle(
                                  fontSize: 12, color: Colours.text_gray_c),
                            ),
                          ),
                          Container(child: mainSignImg),
                        ],
                      ),
                    ),
                  ),
                ])));
  }
}
