package com.cweb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.RedisUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.HuiLianTongUnionCardConfig;
import com.hai.entity.HighUser;
import com.hai.entity.HighUserCard;
import com.hai.enum_type.UserCardType;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.service.HighUserCardService;
import com.hai.service.HighUserPayPasswordService;
import com.hai.service.HighUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping(value = "/highUserCard")
@Api(value = "订单接口")
public class HighUserCardController {

    private static Logger log = LoggerFactory.getLogger(HighUserCardController.class);

    @Resource
    private UserCenter userCenter;

    @Resource
    private HighUserCardService highUserCardService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private HighUserService highUserService;

    @Resource
    private HighUserPayPasswordService highUserPayPasswordService;

    @RequestMapping(value = "/bindCard", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "绑卡")
    public ResponseData bindCard(@RequestBody JSONObject body, HttpServletRequest request) {
        try {
            if (body == null
                    || body.getInteger("type") == null
                    || StringUtils.isBlank(body.getString("cardNo"))
                    || StringUtils.isBlank(body.getString("phone"))
                    || StringUtils.isBlank(body.getString("smsCode"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            if (UserCardType.getNameByType(body.getInteger("type")) == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的卡片类型");
            }
            // 用户
            HighUserModel userInfoModel = userCenter.getSessionModel(HighUserModel.class);

            if (body.getInteger("type").equals(UserCardType.type1.getType())) {
                if (highUserCardService.isBindHtlCard(userInfoModel.getHighUser().getId()) == true) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "绑定失败！只能绑定一张工会卡");
                }
            } else if (body.getInteger("type").equals(UserCardType.type2.getType())) {
                if (highUserCardService.getListByUser(userInfoModel.getHighUser().getId(), UserCardType.type2.getType()).size() != 0) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "绑定失败！只能绑定一张油卡");
                }
            }
            if (highUserCardService.getDetailByUserCardNo(userInfoModel.getHighUser().getId(), body.getString("cardNo")) != null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "已绑定此卡，请勿重复绑定");
            }

            // 获取手机号验证码
            String phoneSmsCode = (String) redisUtil.get("SMS_"+body.getString("phone"));

            // 验证码校验
            if (StringUtils.isNotBlank(phoneSmsCode) && Objects.equals(phoneSmsCode,body.getString("smsCode"))) {

                // 绑定卡片
                highUserCardService.bindCard(body.getInteger("type"),body.getString("cardNo"),userInfoModel.getHighUser().getId());

                redisUtil.del("SMS_"+body.getString("phone"));

                // 定义个人所有数据
                HighUserModel highUserModel = new HighUserModel();
                HighUser detailData = highUserService.getDetailDataByUser(userInfoModel.getHighUser().getId());
                detailData.setPassword(null);
                highUserModel.setHighUser(detailData);
                SessionObject so = new SessionObject(detailData.getPhone(), 1 , highUserModel);
                return ResponseMsgUtil.success(so);
            }

            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "验证码错误");

        } catch (Exception e) {
            log.error("HighUserCardController --> bindCard() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getUserCardList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户卡号列表")
    public ResponseData getUserCardList(@RequestParam(name = "type", required = false) Integer type, HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();
            return ResponseMsgUtil.success(highUserCardService.getListByUser(userInfoModel.getHighUser().getId(),type));
        } catch (Exception e) {
            log.error("HighUserCardController --> getUserCardList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/delUserCard", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除用户卡号")
    public ResponseData delUserCard(@RequestBody JSONObject body, HttpServletRequest request) {
        try {
            if (body == null || StringUtils.isBlank(body.getString("cardNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            highUserCardService.delUserCard(body.getString("cardNo"), userInfoModel.getHighUser().getId());

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("HighUserCardController --> delUserCard() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getHuiLianTongCardByCardNo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据卡号查询汇联通工会卡详情")
    public ResponseData getHuiLianTongCardByCardNo(@RequestParam(name = "cardNo", required = true) String cardNo) {
        try {
            JSONObject cardInfo = HuiLianTongUnionCardConfig.queryCardInfo(cardNo);
            if (!cardInfo.getString("respCode").equals("0000")) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到卡号信息");
            }
            JSONObject cardInfoObject = HuiLianTongUnionCardConfig.resolveResponse(cardInfo.getString("data"));
            if (cardInfoObject.getBoolean("success") == false) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, cardInfoObject.getString("message"));
            }
            return ResponseMsgUtil.success(cardInfoObject);

        } catch (Exception e) {
            log.error("HighUserCardController --> getHuiLianTongCardByCardNo() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/bindHuiLianTongCard", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "绑定汇联通工会卡")
    public ResponseData bindHuiLianTongCard(@RequestBody JSONObject body, HttpServletRequest request) {
        try {
            if (body == null
                    || StringUtils.isBlank(body.getString("cardNo"))
                    || StringUtils.isBlank(body.getString("phone"))
                    || StringUtils.isBlank(body.getString("smsCode"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            if (highUserCardService.isBindHtlCard(userInfoModel.getHighUser().getId()) == true) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "绑定失败！只能绑定一张工会卡");
            }

            if (highUserCardService.getDetailByUserCardNo(userInfoModel.getHighUser().getId(), body.getString("cardNo")) != null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "已绑定此卡，请勿重复绑定");
            }

            // 获取手机号验证码
            String phoneSmsCode = (String) redisUtil.get("SMS_"+body.getString("phone"));

            // 验证码校验
            if (StringUtils.isNotBlank(phoneSmsCode) && Objects.equals(phoneSmsCode,body.getString("smsCode"))) {
                // 验证码校验成功
                HighUserCard userCard = new HighUserCard();
                userCard.setUserId(userInfoModel.getHighUser().getId());
                userCard.setCardNo(body.getString("cardNo"));
                userCard.setType(UserCardType.type1.getType());
                highUserCardService.editCard(userCard);

                redisUtil.del("SMS_"+body.getString("phone"));

                // 定义个人所有数据
                HighUserModel highUserModel = new HighUserModel();
                HighUser detailData = highUserService.getDetailDataByUser(userInfoModel.getHighUser().getId());
                detailData.setPassword(null);
                highUserModel.setHighUser(detailData);
                SessionObject so = new SessionObject(detailData.getPhone(), 1 , highUserModel);
                return ResponseMsgUtil.success(so);
            }
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "验证码错误");

        } catch (Exception e) {
            log.error("HighUserCardController --> bindHuiLianTongCard() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getHuiLianTongCardByPhone", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据手机号获取汇联通工会卡列表")
    public ResponseData getHuiLianTongCardByPhone(@RequestParam(name = "phone", required = true) String phone,
                                                  HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            // 验证码校验成功
            // 根据手机号查询卡号
            JSONObject jsonObject = HuiLianTongUnionCardConfig.queryCardByMobile(phone);
            if(jsonObject.getString("respCode").equals("0000") && jsonObject.getString("respMessage").equals("ok")) {
                JSONObject dataObject = HuiLianTongUnionCardConfig.resolveResponse(jsonObject.getString("data"));
                JSONArray cards = dataObject.getJSONArray("cards");
                for (Object cardObject : cards) {
                    JSONObject card = (JSONObject)cardObject;
                    if (highUserCardService.getDetailByUserCardNo(userInfoModel.getHighUser().getId(), card.getString("cardNo")) != null) {
                        card.put("bindStatus", true);
                    } else {
                        card.put("bindStatus", false);
                    }
                }
                return ResponseMsgUtil.success(cards);
            }
            System.out.println(jsonObject);
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "查询失败");
        } catch (Exception e) {
            log.error("HighUserCardController --> getHuiLianTongCardByPhone() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getHuiLianTongCardInfo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询汇联通工会卡详情")
    public ResponseData getHuiLianTongCardInfo(@RequestParam(name = "cardNo", required = true) String cardNo,HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            HighUserCard card = highUserCardService.getDetailByUserCardNo(userInfoModel.getHighUser().getId(), cardNo);
            if (card == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到数据");
            }

            JSONObject cardInfo = HuiLianTongUnionCardConfig.queryCardInfo(cardNo);
            if (StringUtils.isBlank(cardInfo.getString("data"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQUEST_ERROR, "");
            }
            return ResponseMsgUtil.success(HuiLianTongUnionCardConfig.resolveResponse(cardInfo.getString("data")));

        } catch (Exception e) {
            log.error("HighUserCardController --> getHuiLianTongCardInfo() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getHuiLianTongCardBalance", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询汇联通工会卡余额")
    public ResponseData getHuiLianTongCardBalance(@RequestParam(name = "cardNo", required = true) String cardNo,HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            HighUserCard card = highUserCardService.getDetailByUserCardNo(userInfoModel.getHighUser().getId(), cardNo);
            if (card == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到数据");
            }

            JSONObject cardInfo = HuiLianTongUnionCardConfig.queryBalance(cardNo);
            if (StringUtils.isBlank(cardInfo.getString("data"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQUEST_ERROR, "");
            }
            return ResponseMsgUtil.success(HuiLianTongUnionCardConfig.resolveResponse(cardInfo.getString("data")));

        } catch (Exception e) {
            log.error("HighUserCardController --> getHuiLianTongCardBalance() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getHuiLianTongCardConsume", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询汇联通工会卡消费记录")
    public ResponseData getHuiLianTongCardConsume(@RequestParam(name = "businessType", required = true) String businessType,
                                                  @RequestParam(name = "cardNo", required = true) String cardNo,
                                                  @RequestParam(name = "sdate", required = true) Long sdate,
                                                  @RequestParam(name = "edate", required = true) Long edate,
                                                  @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                                  @RequestParam(name = "pageSize", required = true) Integer pageSize,
                                                  HttpServletRequest request) {
        try {
            // 用户

            JSONObject consumptionRecord = HuiLianTongUnionCardConfig.queryConsumptionRecordByBusiness(businessType, cardNo, sdate, edate, pageNum, pageSize);
            if (StringUtils.isBlank(consumptionRecord.getString("data"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQUEST_ERROR, "");
            }
            JSONArray array = HuiLianTongUnionCardConfig.resolveResponse(consumptionRecord.getString("data")).getJSONArray("records");

            String s = "HFR";
            String s1 = "AGAIN";

            List<JSONObject> list = new ArrayList<>();


            for (Object data : array) {
                JSONObject dataObject = (JSONObject) data;
                if (!StringUtils.contains(dataObject.getString("orderNo"),s) && !StringUtils.contains(dataObject.getString("orderNo"),s1)) {
                    list.add(dataObject);
                }

            }

            return ResponseMsgUtil.success(list);

        } catch (Exception e) {
            log.error("HighUserCardController --> getHuiLianTongCardConsume() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
