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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.ums.UmsSupplementRecordVO;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.enums.UMSDiscountCodeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.StringUtil;
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 org.springframework.transaction.annotation.Transactional;

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

@Service
@Slf4j
@RequiredArgsConstructor
public class SupplementRecordLogic {

    private final CommonMapper commonMapper;
    private final UmsSupplementRecordService umsSupplementRecordService;
    private final UmsRegionCodeService umsRegionCodeService;
    private final OrderDetailService orderDetailService;
    private final CommonLogic commonLogic;
    private final AdminCompanyWechatService adminCompanyWechatService;
    private final OrderInfoService orderInfoService;
    private final AdminWebsitService adminWebsitService;

    @Transactional(rollbackFor = Exception.class)
    public String generateSupplementRecord(String orderId) {
        final OrderInfo orderInfo = orderInfoService.getById(orderId);

        return this.generateSupplementRecord(orderInfo);
    }

    public String generateSupplementRecord(OrderInfo orderInfo) {
        final AdminUserCom adminUser = commonLogic.getAdminUser();
        final AdminWebsit adminWebsit = adminWebsitService.getById(orderInfo.getWebsitId());
        if (!orderInfo.getPayType().equals("云闪付")
                || StringUtils.isBlank(adminWebsit.getYunSpCode())
                || orderInfo.getCouponMerchantContribute().compareTo(BigDecimal.ZERO) <= 0
                || StringUtils.isBlank(orderInfo.getBuyerIdCard())) {
            // 不生成补贴申请记录
            throw new RemoteServiceException("非云闪付补贴订单，生成记录失败");
        }

        final Integer count = umsSupplementRecordService.lambdaQuery()
                .eq(UmsSupplementRecord::getOrderId, orderInfo.getOrderId())
                .count();

        if (count > 0) {
            throw new RemoteServiceException("已生成补贴申请记录");
        }

        UmsSupplementRecord record = new UmsSupplementRecord();
        String traceId = adminWebsit.getYunSpCode() + IdUtil.fastSimpleUUID();
        String merOrderId = adminWebsit.getYunCompany() + orderInfo.getOrderId();
        final UmsRegionCode province = umsRegionCodeService.lambdaQuery()
                .eq(UmsRegionCode::getProvinceName, orderInfo.getProvince())
                .last("limit 1")
                .one();
        final UmsRegionCode city = umsRegionCodeService.lambdaQuery()
                .eq(UmsRegionCode::getCityName, orderInfo.getCity())
                .last("limit 1")
                .one();
        final UmsRegionCode country = umsRegionCodeService.lambdaQuery()
                .eq(UmsRegionCode::getCountryName, orderInfo.getArea())
                .last("limit 1")
                .one();
        String provinceCode = Objects.isNull(province) ? null : province.getProvinceId();
        String provinceName = Objects.isNull(province) ? null : province.getProvinceName();
        String cityCode = Objects.isNull(city) ? null : city.getCityId();
        String cityName = Objects.isNull(city) ? null : city.getCityName();
        String districtCode = Objects.isNull(country) ? null : country.getCountryId();
        String districtName = Objects.isNull(country) ? null : country.getCountryName();

        final OrderDetail orderDetail = orderDetailService.lambdaQuery()
                .eq(OrderDetail::getOrderId, orderInfo.getOrderId())
                .last("limit 1")
                .one();

        final String newEei = UMSDiscountCodeEnum.findNameByCode(orderDetail.getUmsDiscountCode()).contains("一级") ? "L1" : "L2";

        String goodsName = orderDetail.getGoodsName().replace("以旧换新", "")
                .replace("一级能效", "")
                .replace("二级能效", "")
                .replace("格力", "")
                .replace("品牌", "")
                .replace("【", "")
                .replace("】", "")
                .replaceAll(" ", "");

        final boolean validStr = StringUtil.isByteLengthValid(goodsName, 100, StandardCharsets.UTF_8);

        final String newElecAppBrandAndModel = validStr ? goodsName : null;

        record.setCompanyId(orderInfo.getCompanyId())
                .setWebsitId(orderInfo.getWebsitId())
                .setOrderId(orderInfo.getOrderId())
                .setTraceId(traceId)
                .setMerOrderId(merOrderId)
                .setActiveBigClass("ELEC")
                .setProvinceCode(provinceCode)
                .setProvinceName(provinceName)
                .setCityCode(cityCode)
                .setCityName(cityName)
                .setDistrictCode(districtCode)
                .setDistrictName(districtName)
                .setAddress(orderInfo.getReceAddress())
                .setNewElecAppCnt(1)
                .setBrand("格力")
                .setNewEei(newEei)
                .setNewElecAppBrandAndModel(newElecAppBrandAndModel)
                .setTransDate(DateUtil.formatDate(orderInfo.getPayTime()))
                .setSalesCompName(adminWebsit.getUmsApName())
                .setSalesCompCode(adminWebsit.getYunTax())
                .setClientIp(orderInfo.getClientIp())
                .setApId(adminWebsit.getUmsApId())
                .setCreateBy(adminUser.getNickName())
                .setCreateTime(DateUtil.date());

        record.insert();

        orderInfoService.lambdaUpdate()
                .set(OrderInfo::getIsGenerateSupplement, true)
                .eq(OrderInfo::getOrderId, orderInfo.getOrderId())
                .update();

        return record.getId();
    }

    public IPage<UmsSupplementRecordVO> list(Page page, ZfireParamBean zfireParam) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        //1.组装查询条件
        FieldUtils.supplyParam(zfireParam, UmsSupplementRecordVO.class, adminUser);
        return commonMapper.supplementRecordList(page, zfireParam);
    }

    public UmsSupplementRecord detail(String id) {
        return umsSupplementRecordService.getById(id);
    }

    public void submit(UmsSupplementRecord record) {
        final AdminUserCom adminUser = commonLogic.getAdminUser();
        final AdminWebsit adminWebsit = adminWebsitService.getById(record.getWebsitId());
        if (StringUtils.isNotBlank(record.getId())) {
            final UmsSupplementRecord oldData = umsSupplementRecordService.getById(record.getId());
            if (!oldData.getStatus().equals("SAVE")) {
                throw new RemoteServiceException("记录状态已更新，请刷新");
            }
        }

        if (StringUtils.isBlank(record.getProvinceCode())) {
            throw new RemoteServiceException("收货地的省编码不能为空");
        }

        if (StringUtils.isBlank(record.getCityCode())) {
            throw new RemoteServiceException("收货地的市编码不能为空");
        }

        if (StringUtils.isBlank(record.getDistrictCode())) {
            throw new RemoteServiceException("收货地的区编码不能为空");
        }

        if (StringUtils.isBlank(record.getNewElecAppBrandAndModel())) {
            throw new RemoteServiceException("品牌及型号不能为空");
        }

        if (!StringUtil.isByteLengthValid(record.getNewElecAppBrandAndModel(), 100, StandardCharsets.UTF_8)) {
            throw new RemoteServiceException("品牌及型号不能超100字节");
        }

        if (StringUtils.isBlank(record.getNewCelecAppInvPicKey())) {
            throw new RemoteServiceException("发票图片不能为空");
        }

        if (StringUtils.isBlank(record.getNewInvNo())) {
            throw new RemoteServiceException("发票号码不能为空");
        }

        if (StringUtils.isBlank(record.getInvoiceIssueDate())) {
            throw new RemoteServiceException("开票日期不能为空");
        }

        if (Objects.isNull(record.getNewTotalPrice())) {
            throw new RemoteServiceException("含税发票金额不能为空");
        }

        if (Objects.isNull(record.getNewTotalPriceExcTax())) {
            throw new RemoteServiceException("不含税发票金额不能为空");
        }

        if (StringUtils.isBlank(record.getNewElecAppPicKey1())
                && StringUtils.isBlank(record.getNewElecAppPicKey2())
                && StringUtils.isBlank(record.getNewElecAppPicKey3())
                && StringUtils.isBlank(record.getNewElecAppPicKey4())
                && StringUtils.isBlank(record.getNewElecAppPicKey5())) {
            throw new RemoteServiceException("购买商品照片不能为空");
        }

        if (StringUtils.isBlank(record.getNewTransRecPicKey1())
                && StringUtils.isBlank(record.getNewTransRecPicKey2())
                && StringUtils.isBlank(record.getNewTransRecPicKey3())
                && StringUtils.isBlank(record.getNewTransRecPicKey4())
                && StringUtils.isBlank(record.getNewTransRecPicKey5())) {
            throw new RemoteServiceException("支付购买凭证图片不能为空");
        }

        record.setStatus("SUBMIT");
        if (StringUtils.isBlank(record.getId())) {
            if (StringUtils.isNotBlank(record.getTraceId())) {
                final boolean reset = umsSupplementRecordService.lambdaUpdate()
                        .set(UmsSupplementRecord::getStatus, "RESET")
                        .eq(UmsSupplementRecord::getTraceId, record.getTraceId())
                        .update();
                if (reset) {
                    throw new RemoteServiceException(record.getTraceId() + "流水号记录已经重新生成过记录，不能再提交");
                }
            }
            String traceId = adminWebsit.getYunSpCode() + IdUtil.fastSimpleUUID();
            record.setCreateTime(DateUtil.date())
                    .setCreateBy(adminUser.getNickName())
                    .setTraceId(traceId)
                    .setTraceStatus("")
                    .setTraceMsg("")
                    .setBillId("")
                    .setCheckStatus("")
                    .setGrantFlag("")
                    .setReason("")
                    .insert();
        } else {
            record.updateById();
        }
    }

    public List<UmsRegionCode> regionCodeList(HttpServletRequest request, String provinceCode, String cityCode) {
        final List<UmsRegionCode> list = umsRegionCodeService.lambdaQuery()
                .eq(StringUtils.isNotBlank(provinceCode), UmsRegionCode::getProvinceId, provinceCode)
                .eq(StringUtils.isNotBlank(cityCode), UmsRegionCode::getCityId, cityCode)
                .groupBy(StringUtils.isBlank(provinceCode) && StringUtils.isBlank(cityCode), UmsRegionCode::getProvinceId)
                .groupBy(StringUtils.isNotBlank(provinceCode) && StringUtils.isBlank(cityCode), UmsRegionCode::getProvinceId, UmsRegionCode::getCityId)
                .list();

        return list;
    }

}
