package cn.pluss.platform.merchant.impl;

import cn.jiguang.common.utils.StringUtils;
import cn.pluss.platform.api.ResultCode;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantPluginMapper;
import cn.pluss.platform.merchant.MerchantPluginService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.merchantImage.MerchantImageService;
import cn.pluss.platform.notice.NoticeService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.user.impl.GeneralPushUtil;
import cn.pluss.platform.wx.WxTalkService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 商户插件表 服务实现类
 * </p>
 *
 * @author Djh
 * @since 2021-01-29
 */
@Service
public class MerchantPluginServiceImpl extends ServiceImpl<MerchantPluginMapper, MerchantPlugin> implements MerchantPluginService {

    @Setter(onMethod_ = {@Autowired})
    private UserAppService userAppService;
    @Setter(onMethod_ = {@Autowired})
    private MerchantChannelStatusService channelStatusService;
    @Setter(onMethod_ = {@Autowired})
    private NoticeService noticeService;
//    @Setter(onMethod_ = {@Autowired})
//    private PluginService ryxSfbMerchantPluginService;
    @Setter(onMethod_ = {@Autowired})
    private MerchantImageService merchantImageService;
    @Setter(onMethod_ = {@Autowired})
    private WxTalkService wxTalkService;

    @Autowired
    private GeneralPushUtil generalPushUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reqAudit(String userId) {
        UserApp userApp = new UserApp();
        userApp.setUserId(Long.parseLong(userId));
        userApp = userAppService.queryUserApp(userApp);
        MsgException.checkBlank(userApp.getMerchantCode(), "请完善经营信息");

        QueryWrapper<MerchantImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchantCode", userApp.getMerchantCode());
        queryWrapper.in("photoType", MerchantImage.ImageType.HAND_IDCARD_PHOTO);
        List<MerchantImage> list = merchantImageService.list(queryWrapper);
        if (list.isEmpty()) {
            throw new MsgException(ResultCode.FORBIDDEN, "缺少手持身份证图片", null);
        }

        MerchantChannelStatus merchantChannelStatus = channelStatusService.getValidData(userApp.getMerchantCode());
        MsgException.checkNull(merchantChannelStatus, "请先注册为商户之后再进行该操作");

        MerchantPlugin merchantPlugin = new MerchantPlugin();
        merchantPlugin.setUserId(Integer.parseInt(userId));
        MerchantPlugin existData = getOne(new QueryWrapper<>(merchantPlugin));
        if (existData != null) {
            switch (existData.getStatus()) {
                case MerchantChannelStatus.AUDIT_STATUS_EXAMINING:
                    throw new MsgException("该商户插件正在审核中，请勿重复操作");
                case MerchantChannelStatus.AUDIT_STATUS_SUCCESS:
                    throw new MsgException("插件已激活，请勿重复操作");
                case MerchantChannelStatus.AUDIT_STATUS_REJECT:
                case MerchantChannelStatus.AUDIT_STATUS_RESET:
                    merchantPlugin = existData;
                    break;
                default:
                    break;
            }
        }

        merchantPlugin.setStatus(MerchantChannelStatus.AUDIT_STATUS_EXAMINING);
        merchantPlugin.setThirdStatus(MerchantChannelStatus.AUDIT_THIRD_STATUS_WAITING);
        merchantPlugin.setRemark("待后台审核");

        saveOrUpdate(merchantPlugin);

        String pushMsg = "商家插件审核已提交，将会在一个工作日内给出审核结果";
        Notice notice = new Notice(1, 1, userApp);
        String uniqueKey = "auditReq" + System.currentTimeMillis();
        notice.setNoticeCode(uniqueKey);
        notice.setUniqueKey(uniqueKey);
        notice.setCreateDt(new Date());
        notice.setConrtent(pushMsg);
        noticeService.saveNotice(notice);
        generalPushUtil.sendAllPlatByAlias(Collections.singletonList(userApp.getUserId() + ""), "商家审核通知", pushMsg, "1");

        wxTalkService.sendPluginAuditAlert(userApp.getUserId() + "");
    }

    @Override
    public void audit(String userId) {
//        ryxSfbMerchantPluginService.audit(userId);
    }

    @Override
    public void refuse(String userId, String errMsg) {
        MsgException.checkBlank(errMsg, "请补充驳回原因");

        MerchantPlugin merchantPlugin = new MerchantPlugin();
        merchantPlugin.setUserId(Integer.parseInt(userId));
        merchantPlugin = getOne(new QueryWrapper<>(merchantPlugin));
        MsgException.checkNull(merchantPlugin, "暂无商户进件申请记录");

        //TODO 暂定为0，app下次更新时候改为 2
        merchantPlugin.setStatus(MerchantChannelStatus.AUDIT_STATUS_RESET);
        merchantPlugin.setUpdateTime(new Date());
        merchantPlugin.setRemark(errMsg);

        updateById(merchantPlugin);

        UserApp userApp = new UserApp().setUserId(Long.parseLong(userId));
        userApp = userAppService.queryUserApp(userApp);

        Notice notice = new Notice(1, 1, userApp);
        notice.setNoticeCode(System.currentTimeMillis() + "");
        notice.setUniqueKey(System.currentTimeMillis() + "");
        notice.setCreateDt(new Date());
        notice.setConrtent("商户插件进件驳回, " + errMsg);
        noticeService.saveNotice(notice);

        generalPushUtil.sendAllPlatByAlias(Collections.singletonList(userApp.getUserId() + ""), "收银呗审核通知", errMsg, "1");

        // 机器人发送已处理的信息到群组
        wxTalkService.sendPluginAuditResultAlert(userApp.getUserId() + "");
    }

    @Override
    public Map<String, Object> getInfo(String userId) {
        Map<String, Object> map = new HashMap<>();
        MerchantPlugin pluginInfo = getPluginInfo(userId);

        UserApp userApp = new UserApp().setUserId(Long.parseLong(userId));
        userApp = userAppService.queryUserApp(userApp);

        if (StringUtils.isEmpty(userApp.getMerchantCode())) {
            throw new MsgException("缺少商户信息");
        }

        MerchantChannelStatus channelStatus = channelStatusService.getByMerchantCode(userApp.getMerchantCode(), 3);

        map.put("pluginInfo", pluginInfo);
        // 瑞银信进件状态， true即为已经在瑞银信通道进件进件
        boolean status = channelStatus != null && new Integer(3).equals(channelStatus.getChannel());

        QueryWrapper<MerchantImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchantCode", userApp.getMerchantCode());
        queryWrapper.in("photoType", MerchantImage.ImageType.HAND_IDCARD_PHOTO, MerchantImage.ImageType.MERCHANT_PROTOCOL, MerchantImage.ImageType.MERCHANT_SUB_PROTOCOL);
        List<MerchantImage> list = merchantImageService.list(queryWrapper);

        // 缺那三张图也需要进入补交页面
        map.put("ryxStatus", status && (list.size() < 3));

        if (pluginInfo != null) {
            JSONObject extra = pluginInfo.getExtra();
            if (extra != null) {
                String posMerId = extra.getString("posMerId");
                String termCodeList = extra.getString("termList");
                if (termCodeList != null) {
                    // 只取一条
                    String[] split = termCodeList.split(",");
                    map.put("activationCode", posMerId + split[0]);
                }

                map.put("rate", "30");
            }
        }

        return map;
    }
}
