package com.sqx.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserMoneyDetailsDao;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.common.dao.CommonInfoDao;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.errand.entity.TbIndent;
import com.sqx.modules.errand.entity.TbIndentSmsSendLog;
import com.sqx.modules.errand.service.TbIndentService;
import com.sqx.modules.errand.service.TbIndentSmsSendLogService;
import com.sqx.modules.exportExecl.dto.AccountEntry;
import com.sqx.modules.pay.controller.query.WalletDetailQuery;
import com.sqx.modules.pay.vo.WalletDetailVO;
import com.sqx.modules.utils.excel.ExcelData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class UserMoneyDetailsServiceImpl extends ServiceImpl<UserMoneyDetailsDao, UserMoneyDetails> implements UserMoneyDetailsService {

    @Autowired
    private TbIndentSmsSendLogService smsSendLogService;

    @Autowired
    private CommonInfoDao commonInfoDao;

    @Autowired
    private TbIndentService tbIndentService;

    @Override
    public Result queryUserMoneyDetails(Integer page, Integer limit, Long userId, Integer classify, Integer type) {
        IPage<UserMoneyDetails> page1 = new Page(page, limit);
        QueryWrapper<UserMoneyDetails> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        if (classify != null) {
            queryWrapper.eq("classify", classify);
        }
        if (type != null) {
            queryWrapper.eq("type", type);
        }
        queryWrapper.eq("state", 2);
        queryWrapper.orderByDesc("create_time");
        return Result.success().put("data", baseMapper.selectPage(page1, queryWrapper));
    }

    @Override
    public Double monthIncome(String date, Long userId) {
        return baseMapper.monthIncome(date, userId);
    }

    @Override
    public Result selectShopMoneyDetails(Integer page, Integer limit, Long shopId, Integer classify, Integer type) {
        IPage<UserMoneyDetails> page1 = new Page(page, limit);
        QueryWrapper<UserMoneyDetails> queryWrapper = new QueryWrapper();
        queryWrapper.eq("shop_id", shopId);
        if (classify != null) {
            queryWrapper.eq("classify", classify);
        }
        if (type != null) {
            queryWrapper.eq("type", type);
        }
        queryWrapper.eq("state", 2);
        queryWrapper.orderByDesc("create_time");
        return Result.success().put("data", baseMapper.selectPage(page1, queryWrapper));
    }

    @Override
    public Result selectShopCashDeposit(Long shopId, Integer page, Integer limit, Integer classify) {
        Page<UserMoneyDetails> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(baseMapper.selectShopCashDeposit(pages, shopId, classify));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public PageUtils walletDetailList(WalletDetailQuery query) {
        Page<UserMoneyDetails> pages = new Page<>(query.getPage(), query.getLimit());

        IPage<WalletDetailVO> vo = baseMapper.walletDetailList(pages, query);

        return new PageUtils(vo);
    }

    @Override
    public BigDecimal walletDetailStatistics(WalletDetailQuery query) {
        query.setPage(query.getPage() - 1);
        BigDecimal result = baseMapper.walletDetailStatistics(query);
        return result;
    }

    @Override
    public ExcelData excelWalletDetails(WalletDetailQuery query) {
        List<WalletDetailVO> walletDetailVOS = baseMapper.excelWalletDetails(query);
        ExcelData data = new ExcelData();
        data.setName("保证金记录");
        data.setTitles(WalletDetailExportTitle());
        List<List<Object>> rows = new ArrayList<>();
        for (WalletDetailVO walletDetailVO:walletDetailVOS ){
            List<Object> row = new ArrayList<>();
            row.add(walletDetailVO.getId());
            row.add(walletDetailVO.getShopName());
            row.add(walletDetailVO.getContent());
            if ("1".equals(walletDetailVO.getType())){
                row.add("充值");
            }else if("2".equals(walletDetailVO.getType())){
                row.add("提现");
            }else{
                row.add("");
            }
            row.add(walletDetailVO.getCreateTime());
            row.add(walletDetailVO.getMoney());
            rows.add(row);
        }
        data.setRows(rows);
        return data;
    }

    private List<String> WalletDetailExportTitle() {
        return Arrays.asList(
                "编号",
                "店铺名称",
                "保证金金额",
                "类别",
                "提现时间",
                "金额");
    }


    @Override
    public PageUtils accountEntryManagementDetails(Integer page, Integer limit, String shopName, String shopPhone, String userPhone, String couponName, String orderNumber, String startTime, String endTime,String flag) {
        IPage<UserMoneyDetails> iPage = new Page<>();
        Integer row=(page-1)*limit;
        if("1".equals(flag)){
            Page<UserMoneyDetails> pages = new Page<>(page, limit);
            AccountEntry query = new AccountEntry();
            query.setEndTime(endTime);
            query.setShopName(shopName);
            query.setStartTime(startTime);
            query.setUserPhone(userPhone);
            query.setCouponName(couponName);
            query.setOrderNumber(orderNumber);
            query.setShopPhone(shopPhone);
            PageUtils pageUtils = new PageUtils(baseMapper.accountEntryAbnormal(pages, query));
            return pageUtils;
        }
        List<UserMoneyDetails> userMoneyDetailsList = baseMapper.accountEntryManagementDetailsList(row,limit, shopName, shopPhone, userPhone, couponName, orderNumber, startTime, endTime);
//        查询每条成功的短信金额
        CommonInfo commonInfo = commonInfoDao.findOne(421);
        String value = commonInfo.getValue();
        Double smsMoney = Double.valueOf(value);

//        计算每个订单所发送短信金额

        for (int i = 0; i < userMoneyDetailsList.size(); i++) {
            UserMoneyDetails userMoneyDetails = userMoneyDetailsList.get(i);
            BigDecimal couponMoney = userMoneyDetails.getCouponMoney();
            if (ObjectUtils.isEmpty(couponMoney)) {
                couponMoney=new BigDecimal(0);
            }
            BigDecimal activityDiscountAmount = userMoneyDetails.getActivityDiscountAmount();
            if (ObjectUtils.isEmpty(activityDiscountAmount)) {
                activityDiscountAmount=new BigDecimal(0);
            }
            BigDecimal payMoney = userMoneyDetails.getPayMoney();
            // 订单金额
            BigDecimal orderAmount = payMoney.add(couponMoney).add(activityDiscountAmount).setScale(2, BigDecimal.ROUND_DOWN);
            userMoneyDetails.setOrderAmount(orderAmount);

            LambdaQueryWrapper<TbIndent> wrapperTBI=new LambdaQueryWrapper<>();
            wrapperTBI.eq(TbIndent::getOrderId,userMoneyDetails.getOrderId());
            TbIndent tbIndent = tbIndentService.getOne(wrapperTBI);
            if (ObjectUtils.isNotEmpty(tbIndent)) {
                LambdaQueryWrapper<TbIndentSmsSendLog> wrapper=new LambdaQueryWrapper<>();
                wrapper.eq(TbIndentSmsSendLog::getSuccessFlag,"1");
                wrapper.eq(TbIndentSmsSendLog::getOrderId,tbIndent.getIndentId());
                List<TbIndentSmsSendLog> list = smsSendLogService.list(wrapper);
                Double smsMoneyTotal=smsMoney*list.size();
                BigDecimal decimal = new BigDecimal(smsMoneyTotal).setScale(2, BigDecimal.ROUND_DOWN);
                userMoneyDetails.setSmsMoneyTotal(decimal);
            }else {
                userMoneyDetails.setSmsMoneyTotal(new BigDecimal(0));
            }

        }


        int total = baseMapper.accountEntryManagementDetailsCount(shopName, shopPhone, userPhone, couponName, orderNumber, startTime, endTime);

//        当前页数
        iPage.setCurrent(page);
//        每页显示数
        iPage.setSize(limit);
//        数据
        iPage.setRecords(userMoneyDetailsList);
//        总页数

        iPage.setPages((int)Math.ceil((double)total/limit));
//        总数
        iPage.setTotal(total);
        PageUtils pageUtils = new PageUtils(iPage);

        return pageUtils;
    }

    /**
     * @param query
     * @return
     */
    @Override
    public ExcelData excelAccountEntry(AccountEntry query) {
        List<UserMoneyDetails> userMoneyDetailsList;
        if("1".equals(query.getFlag())){
            userMoneyDetailsList = baseMapper.excelAccountEntryAbnormal(query);
        }else{
            userMoneyDetailsList = baseMapper.excelAccountEntry(query);
        }
        ExcelData data = new ExcelData();
        data.setName("入账管理");
        List<String> titleList=Arrays.asList(
                "编号",
                "店铺名称",
                "店铺手机号",
                "下单用户",
                "用户手机号",
                "标题",
                "优惠活动标题",
                "优惠活动金额",
                "跑腿费",
                "订单号",
                "金额",
                "创建时间");
        data.setTitles(titleList);
        List<List<Object>> rows = new ArrayList<>();
        for (UserMoneyDetails userMoneyDetails:userMoneyDetailsList ){
            List<Object> row = new ArrayList<>();
            row.add(userMoneyDetails.getId());
            row.add(userMoneyDetails.getShopName());
            row.add(userMoneyDetails.getShopPhone());
            row.add(userMoneyDetails.getUserName());
            row.add(userMoneyDetails.getUserPhone());
            row.add(userMoneyDetails.getTitle());
            row.add(userMoneyDetails.getCouponName());
            row.add(userMoneyDetails.getCouponMoney());
            row.add(userMoneyDetails.getErrandMoney());
            row.add(userMoneyDetails.getOrderNumber()+"");
            row.add(userMoneyDetails.getMoney());
            row.add(userMoneyDetails.getCreateTime());
            rows.add(row);
        }
        data.setRows(rows);
        return data;
    }

    @Override
    public Result accountEntryAbnormal(AccountEntry accountEntry) {
        Page<UserMoneyDetails> pages = new Page<>(accountEntry.getPage(), accountEntry.getLimit());
        PageUtils pageUtils = new PageUtils(baseMapper.accountEntryAbnormal(pages, accountEntry));
        return Result.success().put("data", pageUtils);
    }
}
