package cn.pluss.platform.channel;

import cn.hutool.core.util.RandomUtil;
import cn.pluss.platform.IdCardService;
import cn.pluss.platform.dto.AccountDTO;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.*;
import cn.pluss.platform.merchant.AccountService;
import cn.pluss.platform.merchant.MerchantCashPlaceService;
//import cn.pluss.platform.merchant.edit.MercChangeRecordService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.notice.NoticeService;
import cn.pluss.platform.pojo.CombineMercInfo;
import cn.pluss.platform.user.impl.GeneralPushUtil;
import cn.pluss.platform.util.IpUtils;
import cn.pluss.platform.util.LogExceptionUtils;
import cn.pluss.platform.wx.WxCertService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class MercAuditListenerImpl implements MercAuditListener {

    @Autowired
    private MerchantBaseInfoMapper mbiMapper;

    @Autowired
    private MerchantChannelStatusService mcsService;

    @Autowired
    private IdCardService idCardService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private WxCertService wxCertService;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private GeneralPushUtil generalPushUtil;

    @Resource
    private UserAppMapper userAppMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private MerchantStoreMapper merchantStoreMapper;

    @Resource
    private MerchantImageMapper merchantImageMapper;

    @Autowired
    private MerchantCashPlaceService cashPlaceService;

    @Autowired
    private RestTemplate restTemplate;

//    @Autowired
//    private MercChangeRecordService mcrService;

    @Override
    public void beforeCheck(String userId, Integer channelId) {
        MerchantBaseInfo mbi = mbiMapper.getByUserId(userId);
        MerchantChannelStatus mcs = mcsService.getByMerchantCode(mbi.getMerchantCode(), channelId);

        if (mcs == null) {
            throw new MsgException("商户未发起进件");
        }

        if (!mcs.getStatus().equals(MerchantChannelStatus.AUDIT_STATUS_EXAMINING)) {
            throw new MsgException("商户进件状态错误");
        }

        if (mcs.getThirdStatus().equals(MerchantChannelStatus.AUDIT_THIRD_STATUS_AUDITING)) {
            throw new MsgException("当前商户已经在后台审核中");
        }
    }

    @Override
    public CombineMercInfo getMercInfo(String userId, String channelType) {
        CombineMercInfo mercInfo = new CombineMercInfo();
        MerchantBaseInfo mbi = mbiMapper.getByUserId(userId);
        mercInfo.setMbi(mbi);

        AccountDTO realAccount = accountService.getRealAccount(userId, channelType);
        if (!mbi.getMerchantType().equals(MerchantBaseInfo.MERCH_TYPE_MICRO)) {
            IdCard legalIdCard = idCardService.getLegalIdCard(userId);
            mercInfo.setLegalIdCard(legalIdCard);
        } else {
            mercInfo.setLegalIdCard(realAccount.getIdcard());
        }

        mercInfo.setSettleIdCard(realAccount.getIdcard());
        mercInfo.setBankCard(realAccount.getBankCard());

        return mercInfo;
    }

    @Override
    public void onFail(String userId, MerchantChannelStatus mcs, String msg) {
        MerchantBaseInfo mbi = mbiMapper.queryByMerchantCode(mcs.getMerchantCode());

        String title2 = "银收客审核通知";

        String msg2;

        if (Objects.equals(mcs.getChannel(), 4)) {
            msg2 = "商户D0进件驳回，" + msg;
        } else {
            msg2 = "商户进件驳回，" + msg;
        }

        Notice notice2 = new Notice(1, 1, mbi.getUserId());
        notice2.setNoticeCode("SHSH_" + System.currentTimeMillis() + RandomUtil.randomString(2));
        notice2.setConrtent(msg2);
        noticeService.saveMerAuthNotice(notice2);

        generalPushUtil.sendAllPlatByAlias(Collections.singletonList(mbi.getUserId() + ""), title2, msg2, "1");
    }

    @Override
    public void onSuccess(String userId, MerchantChannelStatus mcs) {
        MerchantBaseInfo mbi = mbiMapper.queryByMerchantCode(mcs.getMerchantCode() + "");

        String title = "银收客审核通知";
        String msg;
        if (Objects.equals(mcs.getChannel(), 4)) {
            msg = "商户D0进件通过，完成支付宝及微信认证后即可支持相应渠道收款";
        } else {
            msg = "商户进件通过，完成支付宝及微信认证后即可支持相应渠道收款";
        }
        Notice notice = new Notice(1, 1, mbi.getUserId());
        notice.setNoticeCode("SHSH_" + System.currentTimeMillis() + RandomUtil.randomString(2));
        notice.setConrtent(msg);
        noticeService.saveMerAuthNotice(notice);

        generalPushUtil.sendAllPlatByAlias(Collections.singletonList(mbi.getUserId() + ""), title, msg, "1");

        wxCertService.wxCert(userId, mcs.getMerchantCode(), mcs.getChannel());

        // 以下代码为进件结果处理后的操作
        // 创建线上店铺
        try {
            log.info("===================>进件回调，创建店铺开始,商户编号为:{}<=====================", mcs.getMerchantId());
            createStore(mcs);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("创建店铺信息异常,异常信息:{}", e.getMessage());
        }

        try {
            MerchantBaseInfo merchantBaseInfo = mbiMapper.queryByMerchantCode(mcs.getMerchantCode());
            if (StringUtils.isNotBlank(merchantBaseInfo.getUserId())) {
                cashPlaceService.createDefaultCashPlace(Long.parseLong(merchantBaseInfo.getUserId()));
            }
        } catch (Exception e) {
            LogExceptionUtils.printStack(log, e, "创建默认收银点失败,异常信息:{}");
        }
    }

    public void createStore(MerchantChannelStatus merchantChannelStatus) {
        UserApp userApp = userAppMapper.selectByMerchantCode(merchantChannelStatus.getMerchantCode());
        UserInfo userInfo = userInfoMapper.selectById(userApp.getUserId());
        log.info("==============>当前需要同步的用户进件数据为：:{}<===================", JSONObject.toJSONString(merchantChannelStatus));
        if (userInfo != null) {
            MerchantStore merchantStore = new MerchantStore().setMerchantCode(merchantChannelStatus.getMerchantCode());
            merchantStore = merchantStoreMapper.selectOne(new QueryWrapper<>(merchantStore));
            MerchantBaseInfo merchantBaseInfo = mbiMapper.queryByMerchantCode(merchantChannelStatus.getMerchantCode());
            QueryWrapper<MerchantImage> queryWrapper = new QueryWrapper<MerchantImage>()
                    .eq("merchantCode", merchantChannelStatus.getMerchantCode()).eq("photoType", "06");
            MerchantImage merchantImage = merchantImageMapper.selectOne(queryWrapper);
            String baseUrl = "https://shop.shouyinbei.net/web/wmerchant.php?c=site&a=entry&ctrl=store&ac=oauth&op=add_merchan&do=web&m=we7_wmall&i=1";
            StringBuilder sb = new StringBuilder(baseUrl);
            sb.append("&title=").append(merchantBaseInfo.getAlias());
            sb.append("&password=").append(userInfo.getPassword().toLowerCase());
            sb.append("&mobile=").append(userInfo.getLoginName());
            sb.append("&syb_m_id=").append(merchantStore.getId());
            sb.append("&addressNo=").append(merchantBaseInfo.getAddressNo());
            sb.append("&merchantCode=").append(merchantBaseInfo.getMerchantCode());
            sb.append("&type=").append(1);
            String address = merchantBaseInfo.getProvince() + merchantBaseInfo.getCity() + merchantBaseInfo.getDistrict() + merchantBaseInfo.getAddress();
            String area = merchantBaseInfo.getProvince() +"-"+ merchantBaseInfo.getCity() +"-"+ merchantBaseInfo.getDistrict();
            try {
                String decodeAddress = URLEncoder.encode(address, "UTF-8");
                sb.append("&address=").append(decodeAddress);
                String decodeArea = URLEncoder.encode(area, "UTF-8");
                sb.append("&area=").append(decodeArea);
                String logo = URLEncoder.encode(merchantImage.getPicUrl(), "GBK");
                sb.append("&logo=").append(logo);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                log.error("=============>请求生成店铺logo门头照转码异常,异常信息:{}<===============", e.getMessage());
            }
            Map<String, String> lnxMap = IpUtils.getLocationByAddress(address);
            if (lnxMap != null) {
                sb.append("&location_x=").append(lnxMap.get("x"));
                sb.append("&location_y=").append(lnxMap.get("y"));
            }
            // 请求生成店铺j
            String result = restTemplate.getForObject(sb.toString(), String.class);
            log.info("=============>请求生成店铺URL：{}，请求响应返回的参数为:{}<===============", sb.toString(), result);
        }
    }
}
