import 'dart:math';

import 'package:flustars/flustars.dart' as FlutterStars;
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:liftmanager/internal/bbs/bbs_router.dart';
import 'package:liftmanager/internal/bbs/model/position_model.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/iconfont.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/fast_notification.dart';
import 'package:liftmanager/utils/theme_utils.dart';
import 'package:liftmanager/utils/time_format.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/utils/url.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/bbs_content.dart';
import 'package:liftmanager/widgets/my_card.dart';

class PositionDetail extends StatefulWidget {
  PositionDetail(this.id);

  final String id;

  @override
  State<StatefulWidget> createState() {
    return PositionDetailState();
  }
}

class PositionDetailState extends State<PositionDetail> {
  bool positionFavorited = false;

  @override
  void initState() {
    super.initState();
    getPositionDetail();
    FastNotification.addListener("apply", (isApply) {
      if (isApply == true) {
        getPositionDetail();
      }
      setState(() {});
    });
  }

  bool _hasData = false;

  PositionDetailModel detailObj;

  Future getPositionDetail() async {
    await NewApiService().getPositionDetail(int.parse(widget.id),
        onSuccess: (res) {
      if (res != null) {
        detailObj = res;
        positionFavorited = res.isFavorite == 1;
        _hasData = true;
        setState(() {});
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future changeFavorite() async {
    showLoading(context);
    print(detailObj.isFavorite);
    if (detailObj.isFavorite == 0) {
      await NewApiService().insertRecruitmentOperates(
        detailObj.id,
        3,
        onSuccess: (res) {
          print(res);
          dismissLoading(context);
          initCollect();
          this.getPositionDetail();
          setState(() {
            positionFavorited = true;
          });
        },
        onError: (code, msg) {
          dismissLoading(context);
          toasts(msg);
        },
      );
    } else {
      await NewApiService().deleteRecruitmentOperates(
        detailObj.favoriteId,
        onSuccess: (res) {
          print(res);
          dismissLoading(context);
          initCollect();
          this.getPositionDetail();
          setState(() {
            positionFavorited = false;
          });
        },
        onError: (code, msg) {
          dismissLoading(context);
          toasts(msg);
        },
      );
    }
  }

  showAlertEvent() {
    showAlert(
      context,
      "提示",
      "确定登录？",
      "确定",
      () {
        NavigatorUtils.push(context, AccountRouter.loginPage, clearStack: true);
      },
      txt2: "取消",
      onPre2: () {
        NavigatorUtils.goBack(context);
      },
    );
  }

  initCollect() {
    String collectInit = randomInt(1111, 9999).toString() +
        DateTime.now().millisecondsSinceEpoch.toString();
    FastNotification.push("collectAction", collectInit);
  }

  randomInt(int min, int max) {
    return new Random().nextInt(max) % (max - min + 1) + min;
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;

    return Scaffold(
        resizeToAvoidBottomPadding: false, //不让键盘弹上去
        appBar: MyAppBar(
          centerTitle: "职位详情",
        ),
        body: _hasData
            ? Stack(
                children: <Widget>[
                  Container(
                      child: ListView(
                    children: <Widget>[
                      SizedBox(
                        height: 10,
                      ),
                      Container(
                        child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Padding(
                                padding: EdgeInsets.symmetric(horizontal: 10),
                                child: MyCard(
                                  child: Container(
                                    color: Colors.white,
                                    padding: EdgeInsets.all(10),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Container(
                                          padding: EdgeInsets.only(
                                              bottom:
                                                  ScreenUtil().setWidth(10)),
                                          child: Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: <Widget>[
                                              Expanded(
                                                child: Text(
                                                  detailObj.job ?? '',
                                                  style: TextStyle(
                                                    fontSize: 15,
                                                    color: Color(0xff333333),
                                                  ),
                                                  textAlign: TextAlign.start,
                                                ),
                                              ),
                                              Container(
                                                padding:
                                                    EdgeInsets.only(top: 5),
                                                child: Text(
                                                  DateUtils.instance
                                                      .getFormartData(
                                                          timeSamp: detailObj
                                                              .createTime,
                                                          format: "yyyy-MM-dd"),
                                                  style: TextStyle(
                                                    color: Color(0xff999999),
                                                    fontSize: 12,
                                                  ),
                                                  textAlign: TextAlign.start,
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                        Container(
                                          child: Text(
                                            "${detailObj.lowerSalary.toInt()}-${detailObj.upperSalary.toInt()}/月",
                                            style: TextStyle(
                                              color: Color(0xffFF5B00),
                                              fontSize: 14,
                                            ),
                                            textAlign: TextAlign.start,
                                          ),
                                        ),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Row(
                                          children: [
                                            Icon(
                                              Iconfont.xueli,
                                              color: Colors.grey,
                                              size: 12,
                                            ),
                                            SizedBox(
                                              width: 10,
                                            ),
                                            Text(
                                              (detailObj.eduName != '' &&
                                                      detailObj.eduName != null)
                                                  ? detailObj.eduName
                                                  : "不限学历",
                                              style: TextStyle(
                                                color: Color(0xff999999),
                                                fontSize: 12,
                                              ),
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.start,
                                            ),
                                            SizedBox(
                                              width: 10,
                                            ),
                                            Icon(Iconfont.nianxian,
                                                size: 12, color: Colors.grey),
                                            SizedBox(
                                              width: 10,
                                            ),
                                            Text(
                                              (detailObj.upperWorking != null &&
                                                          detailObj
                                                                  .lowerWorking !=
                                                              null
                                                      ? detailObj.lowerWorking
                                                              .toString() +
                                                          "-" +
                                                          detailObj.upperWorking
                                                              .toString()
                                                      : '0') +
                                                  "年",
                                              style: TextStyle(
                                                color: Color(0xff999999),
                                                fontSize: 12,
                                              ),
                                            ),
                                          ],
                                        ),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Divider(
                                          thickness: 0.5,
                                        ),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Row(
                                          children: [
                                            Icon(
                                              Iconfont.dizhi,
                                              color: Colors.grey,
                                              size: 12,
                                            ),
                                            SizedBox(
                                              width: 10,
                                            ),
                                            Expanded(
                                              child: Text(
                                                (detailObj.provinceName ?? '') +
                                                    (detailObj.cityName ?? '') +
                                                    (detailObj.address ?? ''),
                                                style: TextStyle(
                                                  color: Color(0xff999999),
                                                  fontSize: 12,
                                                ),
                                                softWrap: true,
                                                textAlign: TextAlign.left,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                              SizedBox(
                                height: ScreenUtil().setWidth(20),
                              ),
                              CommonSectionHeader(title: '公司信息'),
                              SizedBox(
                                height: 10,
                              ),
                            ]),
                      ),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 10),
                        width: width,
                        decoration: BoxDecoration(
                          border: Border(
                            bottom: BorderSide(
                                width: 5,
                                color: ThemeUtils.getDialogTextFieldColor(
                                    context)),
                          ),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              child: Text(
                                detailObj.company?.name == null
                                    ? ''
                                    : detailObj.company.name,
                                style: TextStyle(
                                  color: Color(0xff333333),
                                  fontSize: 13,
                                ),
                                textAlign: TextAlign.left,
                              ),
                            ),
                            SizedBox(
                              height: ScreenUtil().setWidth(10),
                            ),
                            Text(
                              '${detailObj?.company?.corporator ?? ""} ${detailObj?.company?.telephone ?? ""}',
                              style: TextStyle(
                                color: Color(0xff666666),
                                fontSize: 11,
                              ),
                              textAlign: TextAlign.left,
                            ),
                            SizedBox(
                              height: ScreenUtil().setWidth(10),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      CommonSectionHeader(title: '职位信息'),
                      SizedBox(
                        height: 10,
                      ),
                      Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 10,
                        ),
                        child: Text(
                          detailObj.info ?? '',
                          style: TextStyle(
                            color: Color(0xff666666),
                            fontSize: 13,
                          ),
                          textAlign: TextAlign.left,
                        ),
                      ),
                      SizedBox(
                        height: 80,
                      )
                    ],
                  )),
                  Positioned(
                    bottom: 0,
                    left: 0,
                    child: CommonActionBar(
                      isFavorited: positionFavorited,
                      actionText: '申请职位',
                      onTapFavoriting: () {
                        if (FlutterStars.SpUtil.getString(Constant.userId) ==
                            "-1") {
                          showAlertEvent();
                        } else {
                          changeFavorite();
                        }
                      },
                      onTapSharing: () {
                        if (FlutterStars.SpUtil.getString(Constant.userId) ==
                            "-1") {
                          showAlertEvent();
                        } else {
                          String initThis = randomInt(1111, 9999).toString() +
                              DateTime.now().millisecondsSinceEpoch.toString();

                          fluwx
                              .shareToWeChat(fluwx.WeChatShareWebPageModel(
                                scene: fluwx.WeChatScene.SESSION,
                                webPage:
                                    "$jumpUrl/h5/index.html?num=$initThis&page=/bbs/positionDetail&id=${widget.id}",
                                title: detailObj.job,
                                description: detailObj.info,
                                thumbnail: "",
                              ))
                              .then((result) {}, onError: (msg) {});
                        }
                      },
                      onTapAction: () {
                        if (FlutterStars.SpUtil.getString(Constant.userId) ==
                            "-1") {
                          showAlertEvent();
                        } else {
                          if (detailObj.isApply == 1) {
                            toasts("您已经提交申请了哦");
                          } else {
                            NavigatorUtils.push(context,
                                "${BbsRouter.positionApply}?id=${detailObj.id.toString()}");
                          }
                        }
                      },
                    ),
                  ),
                ],
              )
            : Center(
                child: Text("正在加载..."),
              ));
  }
}
