package cn.pluss.platform.task;

import cn.pluss.platform.entity.*;
import cn.pluss.platform.mapper.MerchantImageMapper;
import cn.pluss.platform.mapper.MerchantStoreMapper;
import cn.pluss.platform.mapper.UserAppMapper;
import cn.pluss.platform.mapper.UserInfoMapper;
import cn.pluss.platform.merchant.MerchantCashPlaceService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.util.IpUtils;
import cn.pluss.platform.util.LogExceptionUtils;
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.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.client.RestTemplate;

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

/**
 * @author djh
 */
@Slf4j
public abstract class BaseMerAuditHandler<T extends IMerAuditHandler> implements IMerAuditHandler {

    @Autowired
    @Lazy
    protected T self;

    @Autowired
    protected RestTemplate restTemplate;

    @Autowired
    protected MerchantBaseInfoService merchantBaseInfoService;

    @Autowired
    protected MerchantCashPlaceService cashPlaceService;

    @Resource
    protected UserAppMapper userAppMapper;

    @Resource
    protected UserInfoMapper userInfoMapper;

    @Resource
    protected MerchantStoreMapper merchantStoreMapper;

    @Resource
    protected MerchantImageMapper merchantImageMapper;

    @Autowired
    @Lazy
    protected MerchantChannelStatusService mcsService;

    @Override
    @Async
    public void auditHandler(JSONObject auditResult) {
        execute(auditResult);

        try {
            self.afterAudit(auditResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void execute(JSONObject auditResult) {
        // 进件结果处理
        MerchantChannelStatus mcs = self.auditCallback(auditResult);

        if (mcs == null) {
            return;
        }

        mcs = mcsService.getById(mcs.getId());

        if (!mcs.getStatus().equals(MerchantChannelStatus.AUDIT_STATUS_SUCCESS)) {
            return;
        }

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

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

    @Override
    public void createStore(MerchantChannelStatus merchantChannelStatus) {
//        if (!"4".equals(merchantChannelStatus.getStatus()) && !"3".equals(merchantChannelStatus.getStatus())) {
//            return;
//        }
        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 = merchantBaseInfoService.getMerchantBaseInfoByMerchantCode(merchantChannelStatus.getMerchantCode());
            QueryWrapper<MerchantImage> queryWrapper = new QueryWrapper<MerchantImage>()
                    .eq("merchantCode", merchantChannelStatus.getMerchantCode()).eq("photoType", "06");
            MerchantImage merchantImage = merchantImageMapper.selectOne(queryWrapper);
            String baseUrl = "https://life.sxczgkj.cn/web/wmerchant.php?c=site&a=entry&ctrl=store&ac=oauth&op=add_merchan&do=web&m=we7_wmall&i=1";
            StringBuffer sb = new StringBuffer(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());
            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);
        }
    }
}
