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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import com.aliyun.dts.subscribe.clients.record.OperationType;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
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.KxsTicket;
import com.kxs.store.api.model.KxsWarehouse;
import com.kxs.store.api.model.KxsWarehouseCreditAmount;
import com.kxs.store.api.model.KxsWarehouseLimit;
import com.kxs.store.api.model.KxsWarehouseStock;
import com.kxs.transfer.api.mapper.store.KxsWarehouseCreditAmountMapper;
import com.kxs.transfer.api.mapper.store.KxsWarehouseLimitMapper;
import com.kxs.transfer.api.mapper.store.KxsWarehouseMapper;
import com.kxs.transfer.api.mapper.store.KxsWarehouseStockMapper;
import com.kxs.transfer.api.mapper.user.KxsUserMapper;
import com.kxs.transfer.api.model.table.DMLData;
import com.kxs.transfer.api.model.table.FieldData;
import com.kxs.transfer.api.service.store.KxsWarehouseService;
import com.kxs.user.api.model.KxsUser;
import com.kxs.user.api.model.KxsUserAmount;
import com.kxs.user.api.model.KxsUserReal;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


/**
 * 客小爽仓库表(KxsWarehouse)表服务实现类
 *
 * @author 系统
 * @since 2024-01-08 09:46:01
 */
@Service("kxsWarehouseService")
@RequiredArgsConstructor
public class KxsWarehouseServiceImpl extends ServiceImpl<KxsWarehouseMapper, KxsWarehouse> implements KxsWarehouseService {

    private final KxsUserMapper kxsUserMapper;

    private final KxsWarehouseStockMapper kxsWarehouseStockMapper;
    private final KxsWarehouseLimitMapper kxsWarehouseLimitMapper;
    private final KxsWarehouseCreditAmountMapper kxsWarehouseCreditAmountMapper;

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

        KxsWarehouse warehouse = new KxsWarehouse();

        KxsWarehouseStock warehouseStock = new KxsWarehouseStock();

        //操作类型
        OperationType operation = dmlData.getOperation();
        if(operation.equals(OperationType.DELETE)){
            baseMapper.deleteById(id);
            return;
        }
        for (String field : changeFieldList) {

            switch (field) {
                case "UserId":
                    int userId = Integer.parseInt(validFieldDataMap.get(field).toString());
                    KxsUser user = kxsUserMapper.selectById(userId);
                    if (user != null){
                        warehouse.setContacts(user.getUsername());
                        warehouse.setWarehouseUserName(user.getUsername());
                        warehouse.setWarehouseUserCode(user.getUserCode());
                    }
                    warehouse.setUserId(userId);
                    break;
                case "StoreNo":
                    warehouse.setWarehouseNo(validFieldDataMap.get(field).toString());
                    break;
                case "StoreName":
                    warehouse.setWarehouseName(validFieldDataMap.get(field).toString());
                    break;
                case "ProductName":
                    warehouse.setBrandName(validFieldDataMap.get(field).toString());
                    break;
                case "BrandId":
                    warehouse.setBrandId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "Address":
                    warehouse.setWarehouseAddress(validFieldDataMap.get(field).toString());
                    break;
                case "ManageUserId":
                    warehouse.setWarehouseAdminId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "ManagerEmail":
                    warehouse.setAdminEmail(validFieldDataMap.get(field).toString());
                    break;
                case "ParentStoreId":
                    warehouse.setPid(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "Areas":
                    String[] split = validFieldDataMap.get(field).toString().split(",");
                    if(split.length == 3){
                        warehouse.setProvince(split[0]);
                        warehouse.setCity(split[1]);
                        warehouse.setArea(split[2]);
                    }
                    break;
                case "StoreStatus":
                    warehouse.setStatus(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "StoreKind":
                    int warehouseType = Integer.parseInt(validFieldDataMap.get(field).toString());
                    if(warehouseType == 0){
                        warehouse.setWarehouseType(1);
                    }
                    if(warehouseType == 1){
                        warehouse.setWarehouseType(0);
                    }
                    if(warehouseType == 2){
                        warehouse.setWarehouseType(2);
                    }
                    break;
                case "FilePath":
                    if(validFieldDataMap.get(field) != null){
                        warehouse.setFileUrl(validFieldDataMap.get(field).toString());
                    }
                    break;
                case "ManageMobile":
                    warehouse.setWarehousePhone(validFieldDataMap.get(field).toString());
                    break;
                case "CreateMan":
                    warehouse.setCreateBy(validFieldDataMap.get(field).toString());
                    break;
                case "Deposit":
                    warehouse.setPledgeAmount(new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "Remark":
                    if(validFieldDataMap.get(field) != null){
                        warehouse.setRemark(validFieldDataMap.get(field).toString());
                    }
                    break;
                case "UpdateMan":
                    warehouse.setUpdateBy(validFieldDataMap.get(field).toString());
                    break;
                case "CreateDate":
                    warehouse.setCreateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
                case "UpdateDate":
                    warehouse.setUpdateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
                case "TotalNum":
                    warehouseStock.setStockTotal(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "LaveNum":
                    warehouseStock.setStockNum(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "OutNum":
                    warehouseStock.setDeliveryNum(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
            }
        }
        if(operation.equals(OperationType.UPDATE)){
            if(BeanUtil.isNotEmpty(warehouse, "entityClass")){
                warehouse.setId(id);
                baseMapper.updateById(warehouse);
            }
            if(BeanUtil.isNotEmpty(warehouseStock, "entityClass")){
                warehouseStock.setId(id);
                kxsWarehouseStockMapper.updateById(warehouseStock);
            }
        }
        if(operation.equals(OperationType.INSERT)){
            KxsWarehouse kxsWarehouse = baseMapper.selectById(id);
            if(kxsWarehouse == null){
                warehouse.setId(id);
                baseMapper.insert(warehouse);
            }
            KxsWarehouseStock kxsWarehouseStock = kxsWarehouseStockMapper.selectById(id);
            if(kxsWarehouseStock == null){
                warehouseStock.setId(id);
                warehouseStock.setWarehouseId(id);
                kxsWarehouseStockMapper.insert(warehouseStock);
            }
        }

    }

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

        KxsWarehouseCreditAmount creditAmount = new KxsWarehouseCreditAmount();

        creditAmount.setId(id);

        //操作类型
        OperationType operation = dmlData.getOperation();
        if(operation.equals(OperationType.DELETE)){
            kxsWarehouseCreditAmountMapper.deleteById(id);
            return;
        }
        for (String field : changeFieldList) {

            switch (field) {
                case "Status":
                    if(Integer.parseInt(validFieldDataMap.get(field).toString()) == -1){
                        kxsWarehouseCreditAmountMapper.deleteById(id);
                        return;
                    }else{
                        creditAmount.setStatus(Integer.parseInt(validFieldDataMap.get(field).toString()));
                    }
                    break;
                case "PromissAmount":
                    creditAmount.setCreditAmount(new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "FromUserId":
                    Integer userId = Integer.valueOf(validFieldDataMap.get(field).toString());
                    KxsUser user = kxsUserMapper.selectById(userId);
                    creditAmount.setCreditUserId(userId);
                    creditAmount.setUsername(user.getUsername());
                    creditAmount.setUserCode(user.getUserCode());
                    break;
                case "ToUserId":
                    creditAmount.setToCreditUserId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "SeoDescription":
                    creditAmount.setRemark(validFieldDataMap.get(field).toString());
                    break;

                case "CreateDate":
                    creditAmount.setCreateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
                case "UpdateDate":
                    creditAmount.setUpdateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
            }
        }
        if(operation.equals(OperationType.INSERT)){
            KxsWarehouseCreditAmount kxsWarehouseCreditAmount = kxsWarehouseCreditAmountMapper.selectById(id);
            if(kxsWarehouseCreditAmount == null){
                kxsWarehouseCreditAmountMapper.insert(creditAmount);
            }
        }
        if(operation.equals(OperationType.UPDATE)){

            kxsWarehouseCreditAmountMapper.updateById(creditAmount);
        }
    }

    @Override
    @DSTransactional
    public void changeAccountData(DMLData dmlData) {
        //修改的字段值
        Map<String, Object> validFieldDataMap = dmlData.getValidFieldDataMap();
        //全部字段值
        Map<String, FieldData> fieldDataMap = dmlData.getFieldDataMap();
        //修改的字段
        List<String> changeFieldList = dmlData.getChangeFieldList();
        //操作的主键
        int id = Integer.parseInt(dmlData.getId());
        KxsWarehouseLimit warehouseLimit = new KxsWarehouseLimit();

        for (String field : changeFieldList) {

            switch (field) {
                case "UserId":
                    warehouseLimit.setUserId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "ValidAmount":
                    warehouseLimit.setValidAmount(new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "FixedAmount":
                    warehouseLimit.setFixedAmount(new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "TempAmount":
                    warehouseLimit.setForAmount(new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "TempAmountForBalance":
                    warehouseLimit.setYueForAmount(new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "CreateDate":
                    warehouseLimit.setCreateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
                case "UpdateDate":
                    warehouseLimit.setUpdateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
            }
        }
        if (BeanUtil.isNotEmpty(warehouseLimit, "entityClass")) {
            //更新全部字段
            if(fieldDataMap.get("ValidAmount").getValue() != null){
                warehouseLimit.setValidAmount(new BigDecimal(fieldDataMap.get("ValidAmount").getValue().toString()));
            }
            if(fieldDataMap.get("FixedAmount").getValue() != null){
                warehouseLimit.setFixedAmount(new BigDecimal(fieldDataMap.get("FixedAmount").getValue().toString()));
            }
            if(fieldDataMap.get("TempAmount").getValue() != null){
                warehouseLimit.setForAmount(new BigDecimal(fieldDataMap.get("TempAmount").getValue().toString()));
            }
            if(fieldDataMap.get("TempAmountForBalance").getValue() != null){
                warehouseLimit.setYueForAmount(new BigDecimal(fieldDataMap.get("TempAmountForBalance").getValue().toString()));
            }
            //仓库担保金额
            KxsWarehouseCreditAmount kxsWarehouseCreditAmount = kxsWarehouseCreditAmountMapper.selectOne(Wrappers.<KxsWarehouseCreditAmount>query()
                    .select("sum(credit_amount) as creditAmount")
                    .eq("to_credit_user_id", id)
                    .groupBy("to_credit_user_id"));
            if(kxsWarehouseCreditAmount != null){
                warehouseLimit.setCreditAmount(kxsWarehouseCreditAmount.getCreditAmount());
            }


            KxsWarehouseLimit kxsWarehouseLimit = kxsWarehouseLimitMapper.selectOne(Wrappers.<KxsWarehouseLimit>lambdaQuery()
                    .eq(KxsWarehouseLimit::getWarehouseType, 0)
                    .eq(KxsWarehouseLimit::getUserId, id));
            if (kxsWarehouseLimit == null) {
                warehouseLimit.setUserId(id);
                kxsWarehouseLimitMapper.insert(warehouseLimit);
            }else{
                warehouseLimit.setId(kxsWarehouseLimit.getId());
                kxsWarehouseLimitMapper.updateById(warehouseLimit);
            }
        }
    }

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

        KxsWarehouseLimit warehouseLimit = new KxsWarehouseLimit();

        for (String field : changeFieldList) {

            switch (field) {
                case "UserId":
                    warehouseLimit.setUserId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "ValidPreAmount":
                    warehouseLimit.setValidAmount(new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "ThisMonthPreAmount":
                    warehouseLimit.setFixedAmount(new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "PreTempAmount":
                    warehouseLimit.setForAmount(new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "PreTempAmountForBalance":
                    warehouseLimit.setYueForAmount(new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "CreateDate":
                    warehouseLimit.setCreateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
                case "UpdateDate":
                    warehouseLimit.setUpdateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
            }
        }
        if (BeanUtil.isNotEmpty(warehouseLimit, "entityClass")) {
            //更新全部字段
            if(fieldDataMap.get("ValidPreAmount").getValue() != null){
                warehouseLimit.setValidAmount(new BigDecimal(fieldDataMap.get("ValidPreAmount").getValue().toString()));
            }
            if(fieldDataMap.get("ThisMonthPreAmount").getValue() != null){
                warehouseLimit.setFixedAmount(new BigDecimal(fieldDataMap.get("ThisMonthPreAmount").getValue().toString()));
            }
            if(fieldDataMap.get("PreTempAmount").getValue() != null){
                warehouseLimit.setForAmount(new BigDecimal(fieldDataMap.get("PreTempAmount").getValue().toString()));
            }
            if(fieldDataMap.get("PreTempAmountForBalance").getValue() != null){
                warehouseLimit.setYueForAmount(new BigDecimal(fieldDataMap.get("PreTempAmountForBalance").getValue().toString()));
            }


            KxsWarehouseLimit kxsWarehouseLimit = kxsWarehouseLimitMapper.selectOne(Wrappers.<KxsWarehouseLimit>lambdaQuery()
                    .eq(KxsWarehouseLimit::getWarehouseType, 1)
                    .eq(KxsWarehouseLimit::getUserId, id));
            if (kxsWarehouseLimit == null) {
                warehouseLimit.setUserId(id);
                //小分仓
                warehouseLimit.setWarehouseType(1);
                kxsWarehouseLimitMapper.insert(warehouseLimit);
            }else{
                warehouseLimit.setId(kxsWarehouseLimit.getId());
                kxsWarehouseLimitMapper.updateById(warehouseLimit);
            }
        }
    }
}

