package cn.pluss.platform.leshua.impl;

import cn.pluss.platform.BankCardService;
import cn.pluss.platform.IdCardService;
import cn.pluss.platform.MerchantAuditRecordService;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.leshua.*;
import cn.pluss.platform.mapper.MerchantBankCardMapper;
import cn.pluss.platform.mapper.MerchantBaseInfoMapper;
import cn.pluss.platform.mapper.MerchantStoreMapper;
import cn.pluss.platform.mapper.UserAppMapper;
import cn.pluss.platform.channel.MerchantAuditService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantImage.MerchantImageService;
import cn.pluss.platform.mswitch.CommonSwitchService;
import cn.pluss.platform.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Map;


@Slf4j
@RequiredArgsConstructor
@Service("leshuaMerchantAuditService")
public class LeshuaMerchantAuditService implements MerchantAuditService {

    private final CommonSwitchService commonSwitchService;
    private final LeshuaService leshuaService;
    private final MerchantImageService merchantImageService;
    private final BankCardService bankCardService;
    private final IdCardService idCardService;

    private final MerchantBankCardMapper merchantBankCardMapper;
    private final MerchantBaseInfoMapper merchantBaseInfoMapper;
    private final MerchantStoreMapper merchantStoreMapper;
    private final UserAppMapper userAppMapper;

    @Setter(onMethod_ = {@Autowired})
    private MerchantAuditRecordService merchantAuditRecordService;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantBaseInfoService merchantBaseInfoService;

    @Override
    public void imageUpload(MerchantImage merchantImage) {

    }

    @Override
    public void imageUpload(String url, String picType) {

    }

    @Override
    public void merchantAudit(String userId, boolean isFailCheck) {
        throw new MsgException("暂不支持乐刷进件");

//        MsgException.check(!commonSwitchService.allowMerchantRegister(), "当前不允许进件！");
//
//        LeshuaMerchantAuditDTO leshuaMerchantAuditDTO = new LeshuaMerchantAuditDTO().setUserId(userId);
//
//        MsgException.checkBlank(userId, "userId参数不存在！");
//
//        if (isFailCheck) {
//            MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getMerchantBaseInfoByUserId(userId);
//            merchantAuditRecordService.checkFailCount(merchantBaseInfo.getMerchantCode(), "连续三次复审驳回，请联系客服进件");
//        }
//
//        UserApp userApp = new UserApp();
//        userApp.setUserId(Long.valueOf(userId));
//        List<UserApp> queryUserAppList = userAppMapper.queryUserAppList(userApp);
//        if (queryUserAppList != null && queryUserAppList.size() > 0) {
//            // 当前用户信息
//            userApp = queryUserAppList.get(0);
//            if ("3".equals(userApp.getLeshuaStatus())) {
//                throw new MsgException("当前商户已进件成功！");
//            }
//
//            BankCard bankCard = new BankCard().setUserId(userId).setAccountType(BankCard.ACCOUNT_TYPE_PRIVATE);
//            bankCard = bankCardService.getOne(new QueryWrapper<>(bankCard));
//            if (bankCard == null) {
//                throw new MsgException("请先进行认证绑卡操作");
//            }
//
//            IdCard legalIdCard = idCardService.getCertIdCard(userId);
//
//            MerchantBaseInfo merchant = new MerchantBaseInfo();
//            merchant.setUserId(userId);
//            List<MerchantBaseInfo> queryMerchantBaseInfoList = merchantBaseInfoMapper.queryMerchantBaseInfoList(merchant);
//            if (queryMerchantBaseInfoList == null || queryMerchantBaseInfoList.size() == 0) {
//                throw new MsgException("请先填写商户基本资料");
//            }
//            merchant = queryMerchantBaseInfoList.get(0);
//            if (merchant.getMerchantType() == null) {
//                throw new MsgException("请先填写商户基本资料");
//            }
//
//            MerchantImage mImage = new MerchantImage();
//            mImage.setMerchantCode(merchant.getMerchantCode());
//            List<MerchantImage> queryMerchantImageList = merchantImageService.queryMerchantImageList(mImage);
//            if (queryMerchantImageList == null || queryMerchantImageList.size() == 0) {
//                throw new MsgException("请先上传相应进件的图片");
//            }
//
//            MerchantRegisterDTO convert = leshuaMerchantAuditDTO.convert(legalIdCard, bankCard, merchant, queryMerchantImageList);
//            MerchantRegisterDTO merchantRegisterDTO = convert;
//            String jsonString2 = JSONObject.toJSONString(merchantRegisterDTO);
//            log.info("===进件信息拼接结果====" + jsonString2);
//            ShopInfo shopInfo = merchantRegisterDTO.getShopInfo();
//            LicenseInfo licenseInfo = merchantRegisterDTO.getLicenseInfo();
//
//            String apply;
//            try {
//                apply = LeshuajinjianImgUploadApply(merchantRegisterDTO);
//            } catch (Exception e) {
//                throw new MsgException("上传错误");
//            }
//
//
//            JSONObject data = new JSONObject();
//            String targetUrl = ParametersUtil.LESHUA_API + "/merchant/register";
//            if(StringUtils.isNotEmpty(userApp.getLeshuaMchId())) {
//                targetUrl = ParametersUtil.LESHUA_API + "/merchant/update";
//                data.put("merchantId", userApp.getLeshuaMchId());
//            }
//            data.put("baseInfo", merchantRegisterDTO.getBaseInfo());
//            data.put("legalPerson", merchantRegisterDTO.getLegalPerson());
//            data.put("contactInfo", merchantRegisterDTO.getContactInfo());
//            data.put("addressInfo", merchantRegisterDTO.getAddressInfo());
//            data.put("licenseInfo", licenseInfo);
//            data.put("accountInfo", merchantRegisterDTO.getAccountInfo());
//            data.put("shopInfo", shopInfo);
//            Result<Object> result = leshuaService.requestApi(targetUrl, data);
//            String respCode = result.getRespCode();
//            try {
//                if ("000000".equals(respCode)) {
//                    JSONObject data2 = (JSONObject) result.getData();
//
//                    if (StringUtils.isNotEmpty(userApp.getLeshuaMchId())) {
//                        updateResultHandle(data2, userApp);
//                    } else {
//                        registerResultHandle(data2, userApp, merchant);
//                    }
//                } else {
//                    String respMsg = result.getRespMsg();
//                    throw new MsgException(respMsg);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                userApp.setLeshuaStatus("2");
//                throw e;
//            } finally {
//                userAppMapper.updateUserApp(userApp);
//            }
//        } else {
//            throw new MsgException("当前用户不存在");
//        }
    }

    @Override
    public void merchantAuditCheck(String userId, boolean isFailCheck) {

    }

    @Override
    public void editMerchantAudit(String userId) {
        // 暂未接通
    }

    @Override
    public JSONObject merchantAuditResult(Map<String, Object> result)throws Exception {
        return null;
    }

    @Override
    public JSONObject merchantAuditCallback(JSONObject auditResult) throws Exception {
        return null;
    }

    @Override
    public JSONObject editMerchantCallback(JSONObject auditResult) throws Exception {
        return null;
    }

    @Override
    public String imgTypeTransform(String imageType) {
        return null;
    }

    @Override
    public void checkSign(JSONObject receiveData) throws Exception {

    }

    /**
     * LeshuajinjianParamApply:(图片). <br/>
     *
     * @param merchantRegisterDTO
     * @return
     * 
     * @author Administrator
     * @since JDK 1.8
     */
    private String LeshuajinjianImgUploadApply(MerchantRegisterDTO merchantRegisterDTO) throws Exception {
        LegalPerson legalPerson = merchantRegisterDTO.getLegalPerson();
        String idcardBackPic = legalPerson.getIdcardBackPic();
        String idcardFrontPic = legalPerson.getIdcardFrontPic();
        idcardBackPic = leshuaService.leshuaImgUpload(idcardBackPic);
        idcardFrontPic = leshuaService.leshuaImgUpload(idcardFrontPic);
        legalPerson.setIdcardBackPic(idcardBackPic);
        legalPerson.setIdcardFrontPic(idcardFrontPic);
        LicenseInfo licenseInfo = merchantRegisterDTO.getLicenseInfo();
        if (licenseInfo != null && StringUtil.isNotEmpty(licenseInfo.getLicensePic())) {
            String licensePic = licenseInfo.getLicensePic();
            licensePic = leshuaService.leshuaImgUpload(licensePic);
            licenseInfo.setLicensePic(licensePic);
        }

        ShopInfo shopInfo = merchantRegisterDTO.getShopInfo();
        String insidePic = shopInfo.getInsidePic();
        String doorPic = shopInfo.getDoorPic();
        String cashierDeskPic = shopInfo.getCashierDeskPic();
        insidePic = leshuaService.leshuaImgUpload(insidePic);
        doorPic = leshuaService.leshuaImgUpload(doorPic);
        cashierDeskPic = leshuaService.leshuaImgUpload(cashierDeskPic);
        shopInfo.setInsidePic(insidePic);
        shopInfo.setDoorPic(doorPic);
        shopInfo.setCashierDeskPic(cashierDeskPic);
        AccountInfo accountInfo = merchantRegisterDTO.getAccountInfo();
        String bankCardFrontPic = accountInfo.getBankCardFrontPic();
        bankCardFrontPic = leshuaService.leshuaImgUpload(bankCardFrontPic);
        accountInfo.setBankCardFrontPic(bankCardFrontPic);
        log.info("idcardBackPic" + idcardBackPic);
        // log.info("licensePic"+licensePic);
        log.info("insidePic" + insidePic);
        log.info("doorPic" + doorPic);
        log.info("cashierDeskPic" + cashierDeskPic);
        log.info("bankCardFrontPic" + bankCardFrontPic);
        if (StringUtil.isEmpty(idcardBackPic)) {
            throw new MsgException("身份证反面照错误,请重新上传");
        }

        if (StringUtil.isEmpty(insidePic)) {
            throw new MsgException("经营场所内设照错误,请重新上传");
        }

        if (StringUtil.isEmpty(doorPic)) {
            throw new MsgException("门头照错误,请重新上传");
        }
        if (StringUtil.isEmpty(cashierDeskPic)) {
            throw new MsgException("收银台照片错误,请重新上传");
        }
        if (StringUtil.isEmpty(bankCardFrontPic)) {
            throw new MsgException("银行卡正面照错误,请重新上传");
        }

        return "";
    }

    private void registerResultHandle(JSONObject result, UserApp userApp, MerchantBaseInfo merchant) {
        // 乐刷分配的商户ID
//        String leshuaMerchantId = result.getString("merchantId");
//        userApp.setLeshuaMchId(leshuaMerchantId);
//        // 乐刷分配的商户账号
//        String leshuaUserName = result.getString("username");
//        userApp.setLeshuaUserName(leshuaUserName);
//        userApp.setLeshuaStatus("1");
//        merchant.setLeshuaRate(ParametersUtil.leshuarate);
//        merchant.setUpdateDt(new Date());
//        merchantBaseInfoMapper.updateMerchantBaseInfo(merchant);
//
//        MerchantStore merchantStore = new MerchantStore();
//        merchantStore.setMerchantCode(merchant.getMerchantCode());
//        List<MerchantStore> queryMerchantStoreList = merchantStoreMapper.queryMerchantStoreList(merchantStore);
//        if (queryMerchantStoreList == null || queryMerchantStoreList.size() == 0) {
//            merchantStore.setMerchantName(merchant.getAlias());
//            merchantStore.setStoreId(StringUtil.genRandomNum(6));
//            merchantStore.setStoreName(merchant.getAlias());
//            merchantStoreMapper.insert(merchantStore);
//        }
//        if (StringUtil.isNotEmpty(userApp.getParentId())) {
//            // 更新上级推广人的认证商户数量 //更新上级推广人的认证商户数量
//            UserApp parentApp = new UserApp();
//            parentApp.setUserId(userApp.getParentId());
//            List<UserApp> queryUserAppList2 = userAppMapper.queryUserAppList(parentApp);
//            if (StringUtil.isNotEmpty(userApp.getParentId()) && queryUserAppList2 != null && queryUserAppList2.size() > 0) {
//                parentApp = queryUserAppList2.get(0);
//                UserApp updateParentApp = new UserApp();
//                updateParentApp.setId(parentApp.getId());
//                updateParentApp.setAuthCount(parentApp.getAuthCount() == null ? 1 : parentApp.getAuthCount() + 1);
//                userAppMapper.updateUserApp(updateParentApp);
//            }
//        }
    }

    private void updateResultHandle(JSONObject result, UserApp userApp) {
//        userApp.setLeshuaStatus("1");
    }
}
