package com.kxs.transfer.api.service.product.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.dts.subscribe.clients.record.OperationType;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.product.api.model.KxsMachine;
import com.kxs.product.api.model.KxsMachineRatio;
import com.kxs.product.api.model.KxsMerchant;
import com.kxs.store.api.model.KxsWarehouse;
import com.kxs.transfer.api.mapper.product.KxsMachineMapper;
import com.kxs.transfer.api.mapper.product.KxsMachineRatioMapper;
import com.kxs.transfer.api.mapper.product.KxsMerchantMapper;
import com.kxs.transfer.api.mapper.store.KxsWarehouseMapper;
import com.kxs.transfer.api.model.table.DMLData;
import com.kxs.transfer.api.service.product.KxsMachineService;
import com.kxs.user.api.model.KxsPartner;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 客小爽机具表(KxsMachine)表服务实现类
 *
 * @author 系统
 * @since 2023-12-20 10:09:35
 */
@Service("kxsMachineService")
@RequiredArgsConstructor
public class KxsMachineServiceImpl extends ServiceImpl<KxsMachineMapper, KxsMachine> implements KxsMachineService {

    private final KxsWarehouseMapper kxsWarehouseMapper;

    private final KxsMachineRatioMapper kxsMachineRatioMapper;
    private final KxsMerchantMapper kxsMerchantMapper;

    @Override
    public void changeData(DMLData dmlData) {
        //修改的字段值
        Map<String, Object> validFieldDataMap = dmlData.getValidFieldDataMap();
        //修改的字段
        List<String> changeFieldList = dmlData.getChangeFieldList();
        //操作的主键
        int id = Integer.parseInt(dmlData.getId());

        KxsMachine machine = new KxsMachine();
        machine.setId(id);

        //操作类型
        OperationType operation = dmlData.getOperation();
        if(operation.equals(OperationType.DELETE)){
            baseMapper.deleteById(id);
            return;
        }
        UpdateWrapper<KxsMachine> wrapper = new UpdateWrapper<>();
        LambdaUpdateWrapper<KxsMachine> lambda = wrapper.lambda().eq(KxsMachine::getId, id);

        for (String field : changeFieldList) {

            switch (field) {
                case "BuyUserId":
                    int userId = Integer.parseInt(validFieldDataMap.get(field).toString());
                    if(userId > 0){
                        machine.setStatus(1);
                    }else{
                        machine.setStatus(0);
                    }
                    machine.setUserId(Integer.parseInt(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getUserId, userId);
                    break;
                case "Status":
                    int status = Integer.parseInt(validFieldDataMap.get(field).toString());
                    if(status == -1){
                        machine.setStatus(status);
                        lambda.set(KxsMachine::getStatus, status);
                    }
                    break;
                case "PosSn":
                    machine.setPosSn(validFieldDataMap.get(field).toString());
                    break;
                case "StoreId":
                    Integer warehouseId = Integer.valueOf(validFieldDataMap.get(field).toString());
                    KxsWarehouse warehouse = kxsWarehouseMapper.selectById(warehouseId);
                    if(warehouse != null){
                        machine.setWarehouseName(warehouse.getWarehouseName());
                        lambda.set(KxsMachine::getWarehouseName, warehouse.getWarehouseName());
                    }
                    machine.setWarehouseId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getWarehouseId, warehouseId);
                    break;
                case "BindMerchantId":
                    machine.setMerchantId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getMerchantId, Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "PreUserId":
                    machine.setPreUserId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getPreUserId, Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "BrandId":
                    machine.setBrandId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getBrandId, Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "RecycEndDate":
                    if(validFieldDataMap.get(field) != null){
                        machine.setRecycleEndTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                        lambda.set(KxsMachine::getRecycleEndTime, LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    }else{
                        lambda.set(KxsMachine::getRecycleEndTime, null);
                    }
                    break;

                case "PosSnType":
                    machine.setMachineType(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getMachineType, Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "PrizeParams":
                    if(validFieldDataMap.get(field) != null && !validFieldDataMap.get(field).toString().isEmpty()){
                        machine.setCashPledge(new BigDecimal(validFieldDataMap.get(field).toString()));
                        lambda.set(KxsMachine::getCashPledge, new BigDecimal(validFieldDataMap.get(field).toString()));
                    }else{
                        machine.setCashPledge(new BigDecimal(299));
                        lambda.set(KxsMachine::getCashPledge, new BigDecimal(299));
                    }
                    break;
                case "SeoKeyword":
                    if(validFieldDataMap.get(field) != null && StrUtil.isNotBlank(validFieldDataMap.get(field).toString())){
                        BigDecimal bigDecimal = new BigDecimal(validFieldDataMap.get(field).toString());
                        if(bigDecimal.intValue() > 1000){
                            bigDecimal = NumberUtil.div(bigDecimal, 100);
                        }
                        machine.setSourcePledge(bigDecimal);
                    }else{
                        lambda.set(KxsMachine::getSourcePledge, null);
                    }
                    break;
                case "BindingTime":
                    if(validFieldDataMap.get(field) != null){
                        machine.setBindTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    }else{
                        lambda.set(KxsMachine::getBindTime, null);
                    }
                    break;
                case "ActivationTime":
                    if(validFieldDataMap.get(field) != null){
                        machine.setActTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    }else{
                        lambda.set(KxsMachine::getActTime, null);
                    }
                    break;
                case "DownFee":
                    machine.setMachineRatio(new BigDecimal(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getMachineRatio, new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "CreditTrade":
                    machine.setCreditTrade(new BigDecimal(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getCreditTrade, new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "DebitCardTrade":
                    machine.setDebitCardTrade(new BigDecimal(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getDebitCardTrade, new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "ScanQrTrade":
                    machine.setScanQrTrade(new BigDecimal(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getScanQrTrade, new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "ActivationState":
                    machine.setIsAct(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getIsAct, Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "IsPurchase":
                    int isPurchase = Integer.parseInt(validFieldDataMap.get(field).toString());
                    //过期时间
                    LocalDateTime recycleEndTime = machine.getRecycleEndTime();
                    //激活条件
                    Integer isAct = machine.getIsAct();
                    //如果没有过期时间查询机具
                    if(recycleEndTime == null || isAct == null){
                        KxsMachine kxsMachine = baseMapper.selectById(machine.getId());
                        if(kxsMachine != null && kxsMachine.getRecycleEndTime() != null){
                            recycleEndTime = kxsMachine.getRecycleEndTime();
                        }
                        if(kxsMachine != null && kxsMachine.getIsAct() > 0){
                            isAct = kxsMachine.getIsAct();
                        }
                    }

                    if(isPurchase == 0 && recycleEndTime != null && isAct != null && recycleEndTime.isAfter(LocalDateTime.now()) && isAct == 1){
                        machine.setRecycleStatus(1);
                        lambda.set(KxsMachine::getRecycleStatus, 1);
                    }else{
                        machine.setRecycleStatus(0);
                        lambda.set(KxsMachine::getRecycleStatus, 0);
                    }
                    break;
                case "BindingState":
                    machine.setBindStatus(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getBindStatus, Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "IsFirst":
                    machine.setIsFirst(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getIsFirst, Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "SourcePosSn":
                    if(validFieldDataMap.get(field) != null ){
                        machine.setSourcePosSn(validFieldDataMap.get(field).toString());
                        lambda.set(KxsMachine::getSourcePosSn, validFieldDataMap.get(field).toString());
                    }else{
                        lambda.set(KxsMachine::getSourcePosSn, null);
                    }
                    break;
                case "LeaderUserId":
                    machine.setLeaderId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getLeaderId, Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "OpId":
                    machine.setPartnerId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getPartnerId, Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "UpFeeFlag":
                    int up = Integer.parseInt(validFieldDataMap.get(field).toString());
                    machine.setUpFeeFlag(up);
                    lambda.set(KxsMachine::getUpFeeFlag, up);
                    //监听到调升费率增加记录
                    if(up == 1 && operation.equals(OperationType.UPDATE)){
                        KxsMachine kxsMachine = baseMapper.selectById(id);
                        KxsMachineRatio machineRatio = new KxsMachineRatio();
                        machineRatio.setMachineId(id);
                        machineRatio.setStatus(1);
                        machineRatio.setPosUserId(kxsMachine.getUserId());
                        machineRatio.setPosSn(kxsMachine.getPosSn());
                        machineRatio.setBrandId(kxsMachine.getBrandId());
                        machineRatio.setMerchantId(kxsMachine.getMerchantId());
                        machineRatio.setRatio(kxsMachine.getMachineRatio());
                        machineRatio.setUserId(kxsMachine.getUserId());
                        machineRatio.setVersion(1);
                        kxsMachineRatioMapper.insert(machineRatio);
                        //增加秒到费字段
                        machine.setSecondFee(new BigDecimal("3"));
                        lambda.set(KxsMachine::getSecondFee, new BigDecimal("3"));
                    }
                    break;
                case "DownFeeFlag":
                    int downFlag = Integer.parseInt(validFieldDataMap.get(field).toString());
                    machine.setDownFeeFlag(downFlag);
                    lambda.set(KxsMachine::getDownFeeFlag, Integer.valueOf(validFieldDataMap.get(field).toString()));
                    if(downFlag == 1){
                        //增加秒到费字段
                        machine.setSecondFee(new BigDecimal("0"));
                        lambda.set(KxsMachine::getSecondFee, new BigDecimal("0"));
                    }
                    break;
                case "IsSupplement":
                    machine.setIsSupply(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getIsSupply, Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "IsOpAct":
                    machine.setIsOpAct(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    lambda.set(KxsMachine::getIsOpAct, Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "TransferTime":
                    if(validFieldDataMap.get(field) != null){
                        machine.setDeliveryTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    }else{
                        lambda.set(KxsMachine::getDeliveryTime, null);
                    }
                    break;
                case "BatchNo":
                    machine.setBatchNo(validFieldDataMap.get(field).toString());
                    break;
                case "OutBatchNo":
                    machine.setDevLocation(validFieldDataMap.get(field).toString());
                    break;
                case "CreateDate":
                    machine.setCreateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
                case "UpdateDate":
                    if(validFieldDataMap.get(field) != null){
                        machine.setUpdateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    }else{
                        lambda.set(KxsMachine::getUpdateTime, null);
                    }
                    break;
            }
        }
        if(operation.equals(OperationType.UPDATE)){
            baseMapper.update(machine, lambda);
        }
        if(operation.equals(OperationType.INSERT)){
            KxsMachine kxsMachine = baseMapper.selectById(machine.getId());
            if(kxsMachine == null){
                if(machine.getCashPledge() == null){
                    machine.setCashPledge(new BigDecimal("299"));
                }
                baseMapper.insert(machine);
            }
        }
    }
}

