package com.ylx.web.controller.massage;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylx.common.annotation.Log;
import com.ylx.common.core.controller.BaseController;
import com.ylx.common.core.domain.R;
import com.ylx.common.enums.BusinessType;
import com.ylx.common.exception.ServiceException;
import com.ylx.common.utils.poi.ExcelUtil;
import com.ylx.massage.domain.TTxRecord;
import com.ylx.massage.enums.TTxRecordEnum;
import com.ylx.massage.service.TTxRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 提现表 前端控制器
 */
@RestController
@RequestMapping("api/tx/record")
@Api(tags = {"提现记录"})
@Slf4j
public class TTxRecordController extends BaseController {
    @Resource
    private TTxRecordService recordService;
    @Value("${percent}")
    private String percent;

    /**
     * 添加申请记录
     * cash
     * @return
     */
    @ApiOperation("申请提现")
    @RequestMapping(value = "wx/applicationCash", method = RequestMethod.POST)
    public R applicationCash(@RequestBody TTxRecord record) {
        try {
            return R.ok(recordService.applicationCash(record));
        } catch (ServiceException s) {
            log.error(s.getMessage());
            return R.fail(s.getMessage());
        } catch (Exception e) {
            StackTraceElement stackTraceElement= e.getStackTrace()[0];
            log.error("系统出错，错误信息:"+ e +" at "+stackTraceElement.getClassName()+"."+stackTraceElement.getMethodName()+":"+stackTraceElement.getLineNumber());
            return R.fail("系统异常");
        }
    }
    @ApiOperation("查询上次提现记录")
    @RequestMapping(value = "wx/last", method = RequestMethod.POST)
    public R<TTxRecord> last(@RequestBody TTxRecord record) {
        try {
            LambdaQueryWrapper<TTxRecord> tTxRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
            tTxRecordLambdaQueryWrapper.eq(TTxRecord::getcOpenId,record.getcOpenId()).orderByDesc(TTxRecord::getcId).last("LIMIT 1");;
            return R.ok(recordService.getOne(tTxRecordLambdaQueryWrapper));
        } catch (ServiceException s) {
            log.error(s.getMessage());
            return R.fail(s.getMessage());
        } catch (Exception e) {
            StackTraceElement stackTraceElement= e.getStackTrace()[0];
            log.error("系统出错，错误信息:"+ e +" at "+stackTraceElement.getClassName()+"."+stackTraceElement.getMethodName()+":"+stackTraceElement.getLineNumber());
            return R.fail("系统异常");
        }
    }

    @ApiOperation("审核通过/驳回")
    @RequestMapping(value = "wx/auditing", method = RequestMethod.POST)
    public R auditing(@RequestBody TTxRecord record) {
        log.info("wx端审核通过/驳回  开始：{}", LocalDateTime.now());
        try {
            return R.ok(recordService.auditing(record));
        } catch (ServiceException s) {
            log.error(s.getMessage());
            return R.fail(s.getMessage());
        } catch (Exception e) {
            StackTraceElement stackTraceElement= e.getStackTrace()[0];
            log.error("系统出错，错误信息:"+ e +" at "+stackTraceElement.getClassName()+"."+stackTraceElement.getMethodName()+":"+stackTraceElement.getLineNumber());
            return R.fail("系统异常");
        }
    }

    /**
     * pc端提现 手动输入：税率 扣除税费
     * @param record
     * @return
     */
    @ApiOperation("审核通过/驳回")
    @RequestMapping(value = "pc/auditing", method = RequestMethod.POST)
    public R pcAuditing(@RequestBody TTxRecord record) {
        log.info("pc端审核通过/驳回  开始：{}", LocalDateTime.now());
        try {
            return R.ok(recordService.auditing(record));
        } catch (ServiceException s) {
            log.error(s.getMessage());
            return R.fail(s.getMessage());
        } catch (Exception e) {
            StackTraceElement stackTraceElement= e.getStackTrace()[0];
            log.error("系统出错，错误信息:"+ e +" at "+stackTraceElement.getClassName()+"."+stackTraceElement.getMethodName()+":"+stackTraceElement.getLineNumber());
            return R.fail("系统异常");
        }
    }

    /**
     * 导出提现信息
     * @param response
     * @param page
     * @param record
     */
    @Log(title = "提现信息", businessType = BusinessType.EXPORT)
    @ApiOperation("导出")
    @PostMapping(value = "pc/export")
    public void export(HttpServletResponse response, Page<TTxRecord> page, TTxRecord record) {
        Page<TTxRecord> pageRecord = recordService.page(page, record, this.getDeptId());
        pageRecord.getRecords().forEach(r -> {
            if(r.getnStatus().compareTo(TTxRecordEnum.PASS_ING.getCode())==0){
                r.setnStatusShow(TTxRecordEnum.PASS_ING.getInfo());
            }
            if(r.getnStatus().compareTo(TTxRecordEnum.PASS.getCode())==0){
                r.setnStatusShow(TTxRecordEnum.PASS.getInfo());
            }
            if(r.getnStatus().compareTo(TTxRecordEnum.NO_PASS.getCode())==0){
                r.setnStatusShow(TTxRecordEnum.NO_PASS.getInfo());
            }

            //提现到账金额
            r.setrPrice(r.getdPrice().multiply(r.getPercent()).
                    setScale(2, RoundingMode.DOWN));
            //提现代扣税额
            r.setWPrice(r.getdPrice().subtract(r.getrPrice()).
                    setScale(2, RoundingMode.DOWN));
            r.setPercentShow(r.getPercent().multiply(new BigDecimal("100")).setScale(2, RoundingMode.DOWN).toPlainString()+"%");
        });
        ExcelUtil<TTxRecord> util = new ExcelUtil<>(TTxRecord.class);
        util.exportExcel(response, pageRecord.getRecords(), "提现信息");
    }

     /**
     * 管理员获取提现信息
     *
     * @return
     */
    @RequestMapping(value = "select", method = RequestMethod.GET)
    @ApiOperation("分页查询数据")
    public R<Page<TTxRecord>> select(Page<TTxRecord> page, TTxRecord txRecord) {
        // 获取页数
        LambdaQueryWrapper<TTxRecord> tTxRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tTxRecordLambdaQueryWrapper.eq(null != txRecord.getnStatus(), TTxRecord::getnStatus, txRecord.getnStatus()).
                eq(StringUtils.isNotBlank(txRecord.getcPhone()), TTxRecord::getcPhone, txRecord.getcPhone()).
                eq(StringUtils.isNotBlank(txRecord.getcName()), TTxRecord::getcName, txRecord.getcName()).
                eq(txRecord.getnStatus() != null, TTxRecord::getnStatus, txRecord.getnStatus()).
                eq(StringUtils.isNotBlank(txRecord.getcOpenId()), TTxRecord::getcOpenId, txRecord.getcOpenId()).
                ge(StringUtils.isNotBlank(txRecord.getStartTime()), TTxRecord::getDtCreateTime, txRecord.getStartTime()).
                le(StringUtils.isNotBlank(txRecord.getEndTime()), TTxRecord::getDtCreateTime, txRecord.getEndTime());

        tTxRecordLambdaQueryWrapper.orderByDesc(TTxRecord::getDtCreateTime);
        if(null != this.getDeptId() && this.getDeptId() != 100){
            tTxRecordLambdaQueryWrapper.eq(TTxRecord::getDeptId,this.getDeptId());
        }
        Page<TTxRecord> pageResult = recordService.page(page, txRecord, this.getDeptId());
        pageResult.getRecords().forEach(r -> {
            //提现到账金额
            r.setrPrice(r.getdPrice().multiply(r.getPercent()).
                    setScale(2, RoundingMode.DOWN));
            //提现代扣税额
            r.setWPrice(r.getdPrice().subtract(r.getrPrice()).
                    setScale(2, RoundingMode.DOWN));
            r.setPercentShow(r.getPercent().multiply(new BigDecimal("100")).setScale(2, RoundingMode.DOWN).toPlainString()+"%");
        });
        return R.ok(pageResult);
    }


    /**
     * 商家获取提现记录
     *
     * @return
     */
    @ApiOperation("商家获取提现记录")
    @RequestMapping(value = "wx/select", method = RequestMethod.GET)
    public R<List<Map<String, Object>>> wxSelect(TTxRecord txRecord) {
        log.info("商家获取提现记录,查询开始：{}", LocalDateTime.now());
        LambdaQueryWrapper<TTxRecord> tTxRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tTxRecordLambdaQueryWrapper.eq(com.ylx.common.utils.StringUtils.isNotBlank(txRecord.getcOpenId()), TTxRecord::getcOpenId, txRecord.getcOpenId()).
                eq(txRecord.getnStatus()!=null,TTxRecord::getnStatus,txRecord.getnStatus()).
                orderByDesc(TTxRecord::getDtCreateTime);
        List<TTxRecord> listRecord = recordService.list(tTxRecordLambdaQueryWrapper);
        Map<YearMonth, List<TTxRecord>> sortedMonthlyGroupedOrders = new HashMap<>();
        List<Map<String, Object>> listResult = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(listRecord)) {
            listRecord.forEach(record -> {
                //提现到账金额
                record.setrPrice(record.getdPrice().multiply(record.getPercent()).
                        setScale(2, RoundingMode.DOWN));
                //提现代扣税额
                record.setWPrice(record.getdPrice().subtract(record.getrPrice()).
                        setScale(2, RoundingMode.DOWN));
            });
            Map<YearMonth, List<TTxRecord>> map = listRecord.stream()
                    .collect(Collectors.groupingBy(
                            order -> YearMonth.from(order.getDtCreateTime()),
                            Collectors.collectingAndThen(
                                    Collectors.toList(),
                                    list -> list.stream()
                                            .sorted(Comparator.comparing(TTxRecord::getDtCreateTime).reversed())
                                            .collect(Collectors.toList())
                            )
                    ));
            sortedMonthlyGroupedOrders = new TreeMap<>(Comparator.reverseOrder());
            sortedMonthlyGroupedOrders.putAll(map);


            // 遍历原始Map，并为每个键生成新的键

            for (Map.Entry<YearMonth, List<TTxRecord>> entry : sortedMonthlyGroupedOrders.entrySet()) {
                YearMonth yearMonth = entry.getKey();
                List<TTxRecord> tTxRecordList = entry.getValue();
                Map<String, Object> newMap = new HashMap<>();
                // 将新键和对应的值放入新的Map中
                newMap.put("date", yearMonth);
                newMap.put("records", tTxRecordList);
                listResult.add(newMap);
            }
        }
        return R.ok(listResult);
    }
}
