package com.gree.mall.manager.logic.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.PayDetail;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.serivce.BuyServiceRecordVO;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.common.WechatLogic;
import com.gree.mall.manager.plus.entity.BuyCompanyInfo;
import com.gree.mall.manager.plus.entity.BuyNormConfig;
import com.gree.mall.manager.plus.entity.BuyServiceRecord;
import com.gree.mall.manager.plus.service.BuyCompanyInfoService;
import com.gree.mall.manager.plus.service.BuyNormConfigService;
import com.gree.mall.manager.plus.service.BuyServiceRecordService;
import com.gree.mall.manager.utils.IpUtil;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
@RequiredArgsConstructor
public class BuyServiceLogic {

    private final CommonMapper commonMapper;
    private final CommonLogic commonLogic;
    private final BuyNormConfigService buyNormConfigService;
    private final BuyCompanyInfoService buyCompanyInfoService;
    private final BuyServiceRecordService buyServiceRecordService;
    private final WechatLogic wechatLogic;

    public IPage<BuyServiceRecordVO> list(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.supplyParam(zfireParamBean, BuyServiceRecordVO.class);
        String companyName = null;
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            companyName = adminUser.getAdminCompanyWechat().getCompanyName();
        }

        return commonMapper.buyServiceRecordList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean, companyName);
    }

    public List<BuyNormConfig> configList() {
        return buyNormConfigService.list();
    }

    public String add(BuyCompanyInfo info) {
        if (StringUtils.isBlank(info.getCompanyName())) {
            throw new RemoteServiceException("公司名称不能为空");
        }
        if (StringUtils.isBlank(info.getManager())) {
            throw new RemoteServiceException("负责人不能为空");
        }
        if (StringUtils.isBlank(info.getMobile())) {
            throw new RemoteServiceException("联系电话不能为空");
        }
        info.setCompanyName(StrUtil.trim(info.getCompanyName()));
        Integer count = buyCompanyInfoService.lambdaQuery()
                .eq(BuyCompanyInfo::getCompanyName, info.getCompanyName())
                .count();

        if (count > 0) {
            throw new RemoteServiceException("公司名称已存在");
        }

        info.insert();
        return info.getId();
    }

    public PayDetail pay(String id, String normId, HttpServletRequest request) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String ip = IpUtil.getIpAddr(request);
        BuyNormConfig config = buyNormConfigService.getById(normId);
        if (Objects.isNull(config)) {
            throw new RemoteServiceException("收费名称不存在");
        }

        BuyCompanyInfo info = buyCompanyInfoService.getById(id);

        if (Objects.isNull(info)) {
            throw new RemoteServiceException("购买方信息不存在");
        }

        Integer count = buyServiceRecordService.lambdaQuery()
                .eq(BuyServiceRecord::getCompanyName, info.getCompanyName())
                .eq(BuyServiceRecord::getIsPay, true)
                .count();

        BigDecimal payAmount = config.getNormAmount().subtract(config.getDiscountAmount());

        BuyServiceRecord record = new BuyServiceRecord();
        record.setId("BS" + IdWorker.getIdStr());
        record.setBuyCompanyInfoId(id);
        record.setCompanyName(info.getCompanyName());
        record.setNormId(normId);
        record.setNormName(config.getNormName());
        record.setNormAmount(config.getNormAmount());
        record.setDiscountAmount(config.getDiscountAmount());
        record.setPayAmount(payAmount);
        record.setBuyMode(count > 0 ? "续费" : "首次购买");
        record.setBuyChannel(Objects.isNull(adminUser) ? "官网" : "后台");
        record.insert();

        return wechatLogic.serviceNormPayment(record.getId(), payAmount, "", ip, "1");

    }

    public Boolean queryPayCode(String companyName, String payId) {
//        DateTime curDate = DateUtil.date();
//        String startDate = DateUtil.formatDate(curDate) + " 00:00:00";
//        String endDate = DateUtil.formatDate(curDate) + " 23:59:59";
        Integer count = buyServiceRecordService.lambdaQuery()
                .eq(BuyServiceRecord::getCompanyName, companyName)
                .eq(BuyServiceRecord::getIsPay, true)
                .eq(BuyServiceRecord::getId, payId)
//                .between(BuyServiceRecord::getCreateTime, startDate, endDate)
                .count();

        return count > 0;
    }

    public BuyCompanyInfo detail(String companyName) {
        return buyCompanyInfoService.lambdaQuery()
                .eq(BuyCompanyInfo::getCompanyName, StrUtil.trim(companyName))
                .last("limit 1")
                .one();
    }
}
