package com.user.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.SessionObject;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.PageUtil;
import com.hfkj.common.utils.RedisUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.BsUserCard;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserSessionObject;
import com.hfkj.service.card.BsUserCardService;
import com.hfkj.service.hlt.HuiLianTongUnionCardService;
import com.hfkj.sysenum.UserCardTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @className: UserCardController
 * @author: HuRui
 * @date: 2024/5/17
 **/
@Controller
@RequestMapping(value="/userCard")
@Api(value="用户卡包")
public class UserCardController {
    Logger log = LoggerFactory.getLogger(UserCardController.class);
    @Resource
    private BsUserCardService userCardService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private UserCenter userCenter;

    @RequestMapping(value="/bind",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "绑定")
    public ResponseData bind(@RequestBody JSONObject body) {
        try {
            // 用户
            UserSessionObject userSessionObject = userCenter.getSessionModel(UserSessionObject.class);
            if (userSessionObject == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_LOGIN_NOT, "");
            }
            if (body == null
                    || body.getInteger("type") == null
                    || StringUtils.isBlank(body.getString("cardNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 卡类型
            UserCardTypeEnum typeEnum = UserCardTypeEnum.getData(body.getInteger("type"));
            if (typeEnum == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的类型");
            }
            userCardService.bindCard(
                    typeEnum,
                    userSessionObject.getUser().getId(),
                    body.getString("cardNo"));

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

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

    @RequestMapping(value="/unBind",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "解绑")
    public ResponseData unBind(@RequestBody JSONObject body) {
        try {
            // 用户
            UserSessionObject userSessionObject = userCenter.getSessionModel(UserSessionObject.class);
            if (userSessionObject == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_LOGIN_NOT, "");
            }
            if (body == null || StringUtils.isBlank(body.getString("cardNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            userCardService.unbindCard(userSessionObject.getUser().getId(),body.getString("cardNo"));

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

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

    @RequestMapping(value="/queryHltCard",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询汇联通卡")
    public ResponseData queryHltCard(@RequestParam(value = "phone" , required = true) String phone,
                                     @RequestParam(value = "smsCode" , required = true) String smsCode) {
        try {
            // 手机号的验证码
            Object phoneCodeObject = redisUtil.get("SMS_CODE:" + phone);
            if (phoneCodeObject == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "短信验证码错误");
            }
            if (!smsCode.equals(phoneCodeObject.toString())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "短信验证码错误");
            }

            // 请求汇联通
            JSONObject responseObj = HuiLianTongUnionCardService.queryCardByMobile(phone);
            if(responseObj.getString("respCode").equals("0000") && responseObj.getString("respMessage").equals("ok")) {
                // 解密
                JSONObject dataObject = HuiLianTongUnionCardService.resolveResponse(responseObj.getString("data"));
                // 删除验证码
                redisUtil.del("SMS_CODE:" + phone);

                return ResponseMsgUtil.success(dataObject.getJSONArray("cards"));
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "查询失败！请稍候重试");
            }

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

    @RequestMapping(value = "/queryHltBalance", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询汇联通工会卡余额")
    public ResponseData queryHltBalance(HttpServletRequest request) {
        try {
            // 用户
            UserSessionObject sessionObject = userCenter.getSessionModel(UserSessionObject.class);
            if (sessionObject == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_LOGIN_NOT, "");
            }
            List<BsUserCard> cardList = userCardService.getCardList(sessionObject.getUser().getId(), UserCardTypeEnum.type1);
            if (cardList.isEmpty()) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未绑定工会卡");
            }
            JSONObject cardInfo = HuiLianTongUnionCardService.queryBalance(cardList.get(0).getCardNo());
            if (StringUtils.isBlank(cardInfo.getString("data"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请求失败");
            }
            return ResponseMsgUtil.success(HuiLianTongUnionCardService.resolveResponse(cardInfo.getString("data")));

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

    @RequestMapping(value="/queryUserCard",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询用户卡号")
    public ResponseData queryUserCard(@RequestParam(value = "type" , required = false) Integer type) {
        try {
            // 用户
            UserSessionObject userSessionObject = userCenter.getSessionModel(UserSessionObject.class);
            if (userSessionObject == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_LOGIN_NOT, "");
            }
            UserCardTypeEnum typeEnum = null;
            if (type!= null) {
                typeEnum = UserCardTypeEnum.getData(type);
                if (typeEnum == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的类型");
                }
            }
            return ResponseMsgUtil.success(userCardService.getCardList(userSessionObject.getUser().getId(), typeEnum));

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

    @RequestMapping(value = "/getHuiLianTongCardConsume", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询汇联通工会卡消费记录")
    public ResponseData getHuiLianTongCardConsume(@RequestParam(name = "cardNo", required = true) String cardNo) {
        try {

            // 用户
            UserSessionObject userSessionObject = userCenter.getSessionModel(UserSessionObject.class);

            BsUserCard userCard = userCardService.getCard(userSessionObject.getUser().getId());

            if (userCard != null) {
                JSONObject consumptionRecord = HuiLianTongUnionCardService.queryConsumptionRecordByBusiness("HiSen_phg_goods", cardNo, 1661498490000L, 1882423290000L, 1, 10000);
                if (StringUtils.isBlank(consumptionRecord.getString("data"))) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "");
                }

                JSONArray array = HuiLianTongUnionCardService.resolveResponse(consumptionRecord.getString("data")).getJSONArray(
                        "records");

                return ResponseMsgUtil.success(array);
            }

            return ResponseMsgUtil.success(null);


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


    @RequestMapping(value = "/queryTransJournal", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询汇联通工会卡消费记录")
    public ResponseData queryTransJournal(@RequestParam(name = "tranType", required = true) String tranType,
                                          @RequestParam(name = "cardNo", required = true) String cardNo,
                                          @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                          @RequestParam(value = "pageSize" , required = true) Integer pageSize) {
        try {


            JSONObject consumptionRecord = HuiLianTongUnionCardService.queryTransJournal(cardNo , tranType);
            if (StringUtils.isBlank(consumptionRecord.getString("data"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "");
            }

            JSONArray array = HuiLianTongUnionCardService.resolveResponse(consumptionRecord.getString("data")).getJSONArray(
                    "journals");

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

            for (Object object : array) {
                JSONObject journal = (JSONObject) object;
                journal.put("tranAmount", journal.getBigDecimal("tranAmount").divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
                list.add(journal);
            }

            return ResponseMsgUtil.success(PageUtil.initPageInfoObj(pageNum, list.size(), pageSize, new PageInfo<>(list)));

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


}
