package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.context.LoginUserInfo;
import com.cool.store.dao.ShopStageInfoDAO;
import com.cool.store.entity.*;
import com.cool.store.enums.AuditTypeEnum;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.MessageEnum;
import com.cool.store.enums.SMSMsgEnum;
import com.cool.store.enums.point.ShopSubStageStatusEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.mapper.*;
import com.cool.store.request.AuditFranchiseFeeRequest;
import com.cool.store.request.FranchiseFeeRequest;
import com.cool.store.response.FranchiseFeeResponse;
import com.cool.store.service.FranchiseFeeService;
import com.cool.store.utils.poi.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;

@Service
@Slf4j
public class FranchiseFeeServiceImpl implements FranchiseFeeService {

    @Resource
    FranchiseFeeMapper franchiseFeeMapper;

    @Resource
    LinePayMapper linePayMapper;

    @Resource
    ShopAuditInfoMapper shopAuditInfoMapper;

    @Resource
    ShopStageInfoDAO shopStageInfoDAO;

    @Resource
    LineInfoMapper lineInfoMapper;

    @Resource
    ShopInfoMapper shopInfoMapper;

    @Resource
    CommonService commonService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean submitLicense(FranchiseFeeRequest request) {
        log.info("submitLicense request：{}", JSONObject.toJSONString(request));
        FranchiseFeeDO franchiseFeeDO = request.toFranchiseFeeDO();
        shopStageInfoDAO.updateShopStageInfo(request.getShopId(), ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_71);
        if (request.getId() != null) {
            franchiseFeeDO.setId(request.getId());
            franchiseFeeMapper.updateByPrimaryKeySelective(franchiseFeeDO);
        } else {
            FranchiseFeeDO isExist = franchiseFeeMapper.selectByShopId(request.getShopId());
            if (Objects.nonNull(isExist)){
                throw new ServiceException(ErrorCodeEnum.UNISSUED_STATEMENT_2);
            }
            franchiseFeeMapper.insertSelective(franchiseFeeDO);
        }
        ShopInfoDO shopInfoDO = shopInfoMapper.selectByPrimaryKey(request.getShopId());
        LineInfoDO lineInfoDO = lineInfoMapper.getByLineId(shopInfoDO.getLineId());
        commonService.sendSms(lineInfoDO.getMobile(), SMSMsgEnum.PAY_FRANCHISE_FEES);
        return true;
    }

    @Override
    public FranchiseFeeResponse getDetail(Long shopId) {
        FranchiseFeeDO result = franchiseFeeMapper.selectByShopId(shopId);
        if (Objects.isNull(result)){
            return new FranchiseFeeResponse();
        }
        FranchiseFeeResponse resp = FranchiseFeeResponse.from(result);
        LinePayDO linePayDO = linePayMapper.selectByPrimaryKey(result.getPayId());
        if (Objects.nonNull(linePayDO)) {
            FranchiseFeeResponse.LinePay linePayResult = FranchiseFeeResponse.LinePay.from(linePayDO);
            if (Objects.nonNull(linePayDO.getLineId())){
                LineInfoDO lineInfoDO = lineInfoMapper.getByLineId(linePayDO.getLineId());
                linePayResult.setPartnerName(lineInfoDO.getUsername());
            }
            linePayResult.setAmount(new BigInteger(result.getPerformanceBond()).add(new BigInteger(result.getFirstYearFee()))
                    .add(new BigInteger(result.getYearFranchiseFee())).add(new BigInteger(result.getLoanMargin())).toString());
            if (Objects.nonNull(result.getAuditId())) {
                ShopAuditInfoDO shopAuditInfoDO = shopAuditInfoMapper.selectByPrimaryKey(result.getAuditId());
                linePayResult.setStatus(shopAuditInfoDO.getResultType());
                linePayResult.setResult(shopAuditInfoDO.getResultType() == 0 ? shopAuditInfoDO.getPassReason() : shopAuditInfoDO.getRejectReason());
            }
            resp.setLinePayDO(linePayResult);
        }
        return resp;
    }

    @Override
    public Boolean auditFranchiseFee(AuditFranchiseFeeRequest request, LoginUserInfo user) {
        ShopAuditInfoDO shopAuditInfoDO = new ShopAuditInfoDO();
        shopAuditInfoDO.setShopId(request.getShopId());
        ShopSubStageStatusEnum shopSubStageStatusEnum = null;
        shopAuditInfoDO.setAuditType(AuditTypeEnum.PAY_FRANCHISE_FEE.getCode());
        shopAuditInfoDO.setSubmittedUserId(user.getUserId());
        shopAuditInfoDO.setSubmittedUserName(user.getName());
        shopAuditInfoDO.setDataType(1);
        shopAuditInfoDO.setResultType(request.getStatus());
        if (Constants.ZERO_INTEGER.equals(request.getStatus())) {
            shopAuditInfoDO.setPassReason(request.getResult());
            shopSubStageStatusEnum = ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_73;
            //更新阶段信息
            shopStageInfoDAO.updateShopStageInfo(request.getShopId(), ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_80);
            Map<String, String> requestMap = new HashMap<>();
            ShopInfoDO shopInfoDO = shopInfoMapper.selectByPrimaryKey(request.getShopId());
            LineInfoDO lineInfo = lineInfoMapper.getByLineId(shopInfoDO.getLineId());
            requestMap.put("storeName", shopInfoDO.getShopName());
            requestMap.put("partnerName", lineInfo.getUsername());
            requestMap.put("partnerMobile", lineInfo.getMobile());
            requestMap.put("lineId", String.valueOf(lineInfo.getId()));
            requestMap.put("shopId", String.valueOf(shopInfoDO.getId()));
            commonService.sendMessage(Collections.singletonList(lineInfo.getInvestmentManager()), MessageEnum.MESSAGE_19, requestMap);
        } else if (Constants.ONE_INTEGER.equals(request.getStatus())) {
            shopAuditInfoDO.setRejectReason(request.getResult());
            shopSubStageStatusEnum = ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_74;
            ShopInfoDO shopInfoDO = shopInfoMapper.selectByPrimaryKey(request.getShopId());
            LineInfoDO lineInfoDO = lineInfoMapper.getByLineId(shopInfoDO.getLineId());
        }
        //插入audit
        shopAuditInfoMapper.insertSelective(shopAuditInfoDO);
        shopStageInfoDAO.updateShopStageAndAuditInfo(request.getShopId(), shopSubStageStatusEnum, shopAuditInfoDO.getId());
        //更新auditId
        FranchiseFeeDO franchiseFeeDO = franchiseFeeMapper.selectByPrimaryKey(request.getId());
        franchiseFeeDO.setAuditId(shopAuditInfoDO.getId());
        franchiseFeeMapper.updateByPrimaryKeySelective(franchiseFeeDO);
//        ShopInfoDO shopInfoDO = shopInfoMapper.selectByPrimaryKey(request.getShopId());
//        LineInfoDO lineInfoDO = lineInfoMapper.getByLineId(shopInfoDO.getLineId());
//        Map<String, String> requestMap = new HashMap<>();
//        requestMap.put("storeName", shopInfoDO.getShopName());
//        requestMap.put("partnerName", lineInfoDO.getUsername());
//        requestMap.put("partnerMobile", lineInfoDO.getMobile());
//        requestMap.put("lineId", String.valueOf(lineInfoDO.getId()));
//        commonService.sendMessage(Collections.singletonList(lineInfoDO.getInvestmentManager()), MessageEnum.MESSAGE_18, requestMap);
        return true;
    }
}
