package com.ruoyi.frequency.illegaldeductionrecord.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.page.PageResult;
import com.ruoyi.controller.req.IllegalDeductionPageReq;
import com.ruoyi.controller.req.MonthReq;
import com.ruoyi.controller.resp.IllegalDeductionPageResp;
import com.ruoyi.enums.message.OrderMessageEnums;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.illegaldeductionrecord.entity.IllegalDeductionRecord;
import com.ruoyi.frequency.illegaldeductionrecord.mapper.IllegalDeductionRecordMapper;
import com.ruoyi.frequency.illegaldeductionrecord.model.result.OrderInfoResp;
import com.ruoyi.frequency.illegaldeductionrecord.service.IllegalDeductionRecordService;
import com.ruoyi.frequency.ordermessage.service.OrderMessageUtilService;
import com.ruoyi.frequency.store.entity.Store;
import com.ruoyi.frequency.store.mapper.StoreMapper;
import com.ruoyi.frequency.store.model.result.OrderResult;
import com.ruoyi.frequency.withdrawalrecord.entity.WithdrawalRecord;
import com.ruoyi.frequency.withdrawalrecord.service.WithdrawalRecordService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.vo.BodyIdReq;
import com.ruoyi.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 扣款记录Service业务层处理
 *
 * @author liwenlong
 * @date 2023-11-08
 */
@Service
public class IllegalDeductionRecordServiceImpl extends ServiceImpl<IllegalDeductionRecordMapper, IllegalDeductionRecord> implements IllegalDeductionRecordService {
    @Autowired
    private IllegalDeductionRecordMapper illegalDeductionRecordMapper;

    /**
     * 查询扣款记录
     *
     * @param id 扣款记录主键
     * @return 扣款记录
     */
    @Override
    public IllegalDeductionRecord selectIllegalDeductionRecordById(Long id) {
        return illegalDeductionRecordMapper.selectIllegalDeductionRecordById(id);
    }

    /**
     * 查询扣款记录列表
     *
     * @param illegalDeductionRecord 扣款记录
     * @return 扣款记录
     */
    @Override
    public List<IllegalDeductionRecord> selectIllegalDeductionRecordList(IllegalDeductionRecord illegalDeductionRecord) {
        return illegalDeductionRecordMapper.selectIllegalDeductionRecordList(illegalDeductionRecord);
    }

    /**
     * 新增扣款记录
     *
     * @param illegalDeductionRecord 扣款记录
     * @return 结果
     */
    @Override
    public int insertIllegalDeductionRecord(IllegalDeductionRecord illegalDeductionRecord) {
        illegalDeductionRecord.setCreateData();
        return illegalDeductionRecordMapper.insert(illegalDeductionRecord);
    }

    /**
     * 修改扣款记录
     *
     * @param illegalDeductionRecord 扣款记录
     * @return 结果
     */
    @Override
    public int updateIllegalDeductionRecord(IllegalDeductionRecord illegalDeductionRecord) {
        illegalDeductionRecord.setUpdateData();
        return illegalDeductionRecordMapper.updateIllegalDeductionRecord(illegalDeductionRecord);
    }

    @Autowired
    private WithdrawalRecordService withdrawalRecordService;

    @Autowired
    private OrderMessageUtilService orderMessageService;

    /**
     * 批量删除扣款记录
     *
     * @param ids 需要删除的扣款记录主键
     * @return 结果
     */
    @Override
    public int deleteIllegalDeductionRecordByIds(Long[] ids, Integer delFlag) {

        IllegalDeductionRecord illegalDeductionRecord = getById(ids[0]);

        //查询要删除的记录是否是最近一次提现之前，是的话，不可取消
        if (PublicCommon.删除.equals(delFlag)) {
            WithdrawalRecord withdrawalRecord = withdrawalRecordService.getOne(new QueryWrapper<WithdrawalRecord>().lambda().eq(WithdrawalRecord::getUserId, illegalDeductionRecord.getStoreId())
                    .orderByDesc(BaseEntity::getCreateTime).last(" limit 1"));

            BigDecimal price = BigDecimal.ZERO;

            for (Long id : ids) {
                IllegalDeductionRecord cur = getById(id);
                if (withdrawalRecord != null) {
                    if (withdrawalRecord.getCreateTime().getTime() > cur.getCreateTime().getTime()) {
                        throw new ServiceException("存在扣款被抵消，不可删除扣款记录");
                    }
                }
                price = price.add(cur.getPrice());

            }
            for (Long id : ids) {
                IllegalDeductionRecord cur = getById(id);
                OrderResult orderResult = storeMapper.getOrderInfo(cur.getOrderId());
                if (orderResult != null) {
                    //添加订单消息
                    orderMessageService.addOrderMessage(new UserVo(UserEnums.customer.getCode(), cur.getStoreId()), cur.getOrderId(), orderResult.getOrderNo(), cur.getPrice() + "", PublicCommon.Order.订单, OrderMessageEnums.ORDER_ILLEGAL_DEDUCTION_CANCEL);

                }
            }
            if (price.compareTo(BigDecimal.ZERO) != 0) {
                if (price.compareTo(BigDecimal.ZERO) > 0) {
                    storeMapper.subViolationDeduction(illegalDeductionRecord.getStoreId(), price);
                } else {
                    storeMapper.addViolationDeduction(illegalDeductionRecord.getStoreId(), price.negate());
                }
            }

        }


        this.lambdaUpdate().set(IllegalDeductionRecord::getDelFlag, delFlag).in(IllegalDeductionRecord::getId, ids).update();
        return ids.length;
    }


    @Autowired
    private StoreMapper storeMapper;

    @Override
    public void updateViolationDeduction(Long storeId, Long withId, BigDecimal price, int type, Long orderId, String deductionType, String remark) {
        if (price.compareTo(BigDecimal.ZERO) == 0) {
            return;
        }

        if (price.compareTo(BigDecimal.ZERO) > 0) {
            storeMapper.addViolationDeduction(storeId, price);
        } else {
            boolean b = storeMapper.subViolationDeduction(storeId, price.negate());
            if (!b) {
                throw new CustomException("扣款金额错误");
            }
        }

        Store store = storeMapper.selectById(storeId);
        //添加违规款记录
        IllegalDeductionRecord illegalDeductionRecord = new IllegalDeductionRecord();
        illegalDeductionRecord.setStoreId(storeId)
                .setWithdrawalRecordId(withId)
                .setPrice(price)
                .setCurrentPrice(store.getViolationDeduction())
                .setType(type)
                .setOrderId(orderId)
                .setDeductionType(deductionType)
                .setRemark(remark);
        this.insertIllegalDeductionRecord(illegalDeductionRecord);

    }

    @Override
    public Object getPage(MonthReq req, UserVo userVo) {
        LambdaUpdateWrapper<IllegalDeductionRecord> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(IllegalDeductionRecord::getStoreId, userVo.getUserId());
        if (req.getBeginTime() != null) {
            lambdaUpdateWrapper.ge(BaseEntity::getCreateTime, req.getBeginTime());
        }
        if (req.getEndTime() != null) {
            lambdaUpdateWrapper.le(BaseEntity::getCreateTime, req.getEndTime());
        }
        lambdaUpdateWrapper.eq(IllegalDeductionRecord::getDelFlag, PublicCommon.启用);
        lambdaUpdateWrapper.eq(IllegalDeductionRecord::getType,1);
        lambdaUpdateWrapper.orderByDesc(BaseEntity::getCreateTime);

        List<IllegalDeductionRecord> illegalDeductionRecords = this.baseMapper.selectList(lambdaUpdateWrapper);
        //按月筛选
        Map<String, List<IllegalDeductionRecord>> illegalDeductionMap = new LinkedHashMap<>();

        if (CollectionUtil.isNotEmpty(illegalDeductionRecords)) {
            for (IllegalDeductionRecord cur : illegalDeductionRecords) {
                String yearMonth = DateUtil.year(cur.getCreateTime()) + "年" + (DateUtil.month(cur.getCreateTime())+1) + "月";
                if (!illegalDeductionMap.containsKey(yearMonth)) {
                    illegalDeductionMap.put(yearMonth, new ArrayList<>());
                }
                illegalDeductionMap.get(yearMonth).add(cur);
            }

        }
        List<Map> resultList = new ArrayList<>();
        Iterator<Map.Entry<String, List<IllegalDeductionRecord>>> iterator = illegalDeductionMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, List<IllegalDeductionRecord>> next = iterator.next();
            Map map = new HashMap();
            map.put("date", next.getKey());
            map.put("list", next.getValue());
            resultList.add(map);
        }

        return resultList;
    }

    @Override
    public Object detail(BodyIdReq req, UserVo userVo) {
        IllegalDeductionRecord illegalDeductionRecord = getById(req.getId());
        if (illegalDeductionRecord.getOrderId() != null) {
            OrderInfoResp orderInfoResp = baseMapper.getOrderInfo(illegalDeductionRecord.getOrderId());
            illegalDeductionRecord.setOrderNo(orderInfoResp.getOrderNo());
        }

        return illegalDeductionRecord;
    }


    public static void main(String[] args) {
        Date date = new Date();
        String s = DateUtil.formatDate(new Date());
        System.out.println(DateUtil.year(date) + "年" + DateUtil.month(date) + "月");
    }

    @Override
    public ResponseData<IllegalDeductionPageResp> illegalDeductionPage(IllegalDeductionPageReq req, UserVo userVo) {
        Page<IllegalDeductionPageResp> page = this.baseMapper.illegalDeductionPage(new Page<>(req.getPageNo(), req.getPageSize()), req, userVo);
        // 查询分页结果
        return ResponseData.success(new PageResult<>(page));
    }
}
