package com.yiqi.admin.controller.recharge;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yiqi.common.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiqi.app.service.IAppUserService;
import com.yiqi.common.constant.UrlConstants;
import com.yiqi.common.core.controller.BaseController;
import com.yiqi.common.core.domain.AuthHolder;
import com.yiqi.common.core.domain.BaseEntity;
import com.yiqi.common.core.domain.R;
import com.yiqi.common.enums.DeleteStatus;
import com.yiqi.common.utils.DateUtils;
import com.yiqi.common.utils.StringUtils;
import com.yiqi.common.utils.poi.ExcelUtil;
import com.yiqi.recharge.domain.RechargeCardBatchRecord;
import com.yiqi.recharge.domain.RechargePasswordCard;
import com.yiqi.recharge.domain.dto.*;
import com.yiqi.recharge.domain.vo.RechargeBatchCardDetailListQueryVO;
import com.yiqi.recharge.domain.vo.RechargeBatchUseRecordListQueryVO;
import com.yiqi.recharge.domain.vo.RechargeCardBatchRecordInfoVO;
import com.yiqi.recharge.service.IRechargeCardBatchRecordService;
import com.yiqi.recharge.service.IRechargePasswordCardService;
import com.yiqi.system.service.ISysOrgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;

/**
 * @author xiaohei
 * @date 2024/1/6
 */
@Api("充值卡生成批次")
@RestController
@RequestMapping(value = UrlConstants.managerApi + "/recharge/card/batchRecord")
public class RechargeCardBatchRecordController extends BaseController {
    @Autowired
    private IRechargeCardBatchRecordService rechargeCardBatchRecordService;
    @Autowired
    private IRechargePasswordCardService rechargePasswordCardService;
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private ISysOrgService sysOrgService;

    @ApiOperation("分页查询充值卡生成批次记录")
    @GetMapping(value = "findPage")
    public R<Page<RechargeCardBatchRecord>> findPage(@Valid RechargeCardBatchRecordQueryDTO rechargeCardBatchRecordQueryDTO) throws Exception {
        LambdaQueryWrapper<RechargeCardBatchRecord> queryWrapper = new QueryWrapper<RechargeCardBatchRecord>().lambda()
                .orderByDesc(BaseEntity::getCreateTime);
        if (StringUtils.isNotEmpty(rechargeCardBatchRecordQueryDTO.getBatchNo())) {
            queryWrapper.like(RechargeCardBatchRecord::getBatchNo, rechargeCardBatchRecordQueryDTO.getBatchNo());
        }
        if (StringUtils.isNotEmpty(rechargeCardBatchRecordQueryDTO.getBatchName())) {
            queryWrapper.like(RechargeCardBatchRecord::getBatchName, rechargeCardBatchRecordQueryDTO.getBatchName());
        }
        if (StringUtils.isNotEmpty(rechargeCardBatchRecordQueryDTO.getCompanyName())) {
            queryWrapper.like(RechargeCardBatchRecord::getCompanyName, rechargeCardBatchRecordQueryDTO.getCompanyName());
        }
        if (rechargeCardBatchRecordQueryDTO.getBeginLastExpireTime() != null) {
            queryWrapper.ge(RechargeCardBatchRecord::getLastExpireTime, rechargeCardBatchRecordQueryDTO.getBeginLastExpireTime());
        }
        if (rechargeCardBatchRecordQueryDTO.getEndLastExpireTime() != null) {
            queryWrapper.lt(RechargeCardBatchRecord::getLastExpireTime, DateUtils.addDays(rechargeCardBatchRecordQueryDTO.getEndLastExpireTime(), 1));
        }
        if (rechargeCardBatchRecordQueryDTO.getLastUseLevel() != null) {
            queryWrapper.eq(RechargeCardBatchRecord::getLastUseLevel, rechargeCardBatchRecordQueryDTO.getLastUseLevel());
        }
        Page page = rechargeCardBatchRecordService.page(new Page<RechargeCardBatchRecord>(rechargeCardBatchRecordQueryDTO.getPageNum()
                , rechargeCardBatchRecordQueryDTO.getPageSize()), queryWrapper);
        return R.page(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("修改批次下充值卡到期时间")
    @PostMapping(value = "updateExpireTimeByBatchNo")
    public R updateExpireTimeByBatchNo(@RequestBody @Valid UpdateRechargeBatchExpireTimeDTO updateRechargeBatchExpireTimeDTO)
            throws Exception {
        RechargeCardBatchRecord rechargeCardBatchRecord = rechargeCardBatchRecordService
                .getOne(new QueryWrapper<RechargeCardBatchRecord>().lambda()
                        .eq(RechargeCardBatchRecord::getBatchNo, updateRechargeBatchExpireTimeDTO.getBatchNo()));
        if (rechargeCardBatchRecord == null) {
            throw new ServiceException("未查询到批次信息");
        }
        rechargeCardBatchRecord.setLastExpireTime(updateRechargeBatchExpireTimeDTO.getExpireTime());
        rechargeCardBatchRecord.buildUpdateData();
        rechargeCardBatchRecordService.updateById(rechargeCardBatchRecord);

        rechargePasswordCardService.update(new UpdateWrapper<RechargePasswordCard>().lambda()
                .eq(RechargePasswordCard::getBatchNo, updateRechargeBatchExpireTimeDTO.getBatchNo())
//                .set(RechargePasswordCard::getExpireTime, updateRechargeBatchExpireTimeDTO.getExpireTime())
                .set(RechargePasswordCard::getIsSupportCar, updateRechargeBatchExpireTimeDTO.getIsSupportCar())
                .set(RechargePasswordCard::getIsSupportGoods, updateRechargeBatchExpireTimeDTO.getIsSupportGoods())
                .set(RechargePasswordCard::getIsSupportCloth, updateRechargeBatchExpireTimeDTO.getIsSupportCloth())
                .set(RechargePasswordCard::getIsSupportLife, updateRechargeBatchExpireTimeDTO.getIsSupportLife())
                .set(BaseEntity::getUpdateById, AuthHolder.userId()).set(BaseEntity::getUpdateBy, AuthHolder.nickName())
                .set(BaseEntity::getUpdateTime, DateUtils.getNowDate()));
        return R.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("修改批次下充值卡优先支付")
    @PostMapping(value = "updateUseLevelByBatchNo")
    public R updateUseLevelByBatchNo(@RequestBody @Valid UpdateRechargeBatchUseLevelDTO updateRechargeBatchUseLevelDTO)
            throws Exception {
        RechargeCardBatchRecord rechargeCardBatchRecord = rechargeCardBatchRecordService
                .getOne(new QueryWrapper<RechargeCardBatchRecord>().lambda()
                        .eq(RechargeCardBatchRecord::getBatchNo, updateRechargeBatchUseLevelDTO.getBatchNo()));
        if (rechargeCardBatchRecord == null) {
            throw new ServiceException("未查询到批次信息");
        }
        rechargeCardBatchRecord.setLastUseLevel(updateRechargeBatchUseLevelDTO.getUseLevel());
        rechargeCardBatchRecord.buildUpdateData();
        rechargeCardBatchRecordService.updateById(rechargeCardBatchRecord);

        rechargePasswordCardService.update(new UpdateWrapper<RechargePasswordCard>().lambda()
                .eq(RechargePasswordCard::getBatchNo, updateRechargeBatchUseLevelDTO.getBatchNo())
                .set(RechargePasswordCard::getUseLevel, updateRechargeBatchUseLevelDTO.getUseLevel())
                .set(BaseEntity::getUpdateById, AuthHolder.userId()).set(BaseEntity::getUpdateBy, AuthHolder.nickName())
                .set(BaseEntity::getUpdateTime, DateUtils.getNowDate()));
        return R.ok();
    }

    @ApiOperation("查询批次号信息")
    @GetMapping(value = "/getOneByBatchNo")
    public R getOneByBatchNo(@RequestParam("batchNo") String batchNo)
            throws Exception {
        RechargeCardBatchRecord rechargeCardBatchRecord = rechargeCardBatchRecordService
                .getOne(new QueryWrapper<RechargeCardBatchRecord>().lambda()
                        .eq(RechargeCardBatchRecord::getBatchNo, batchNo));
        if (rechargeCardBatchRecord == null) {
            throw new ServiceException("未查询到批次信息");
        }
        RechargeCardBatchRecordInfoVO batchRecordInfoVO = new RechargeCardBatchRecordInfoVO();
        BeanUtils.copyProperties(rechargeCardBatchRecord, batchRecordInfoVO);
        RechargePasswordCard rechargePasswordCard = rechargePasswordCardService.getOne(new QueryWrapper<RechargePasswordCard>().lambda()
                .eq(RechargePasswordCard::getBatchNo, batchNo)
                .eq(RechargePasswordCard::getDelFlag, DeleteStatus.OK.getCode()), false);
        if (rechargePasswordCard != null) {
            batchRecordInfoVO.setIsSupportCar(rechargePasswordCard.getIsSupportCar());
            batchRecordInfoVO.setIsSupportGoods(rechargePasswordCard.getIsSupportGoods());
            batchRecordInfoVO.setIsSupportCloth(rechargePasswordCard.getIsSupportCloth());
            batchRecordInfoVO.setIsSupportLife(rechargePasswordCard.getIsSupportLife());
        }
        return R.ok(batchRecordInfoVO);
    }

    @ApiOperation("导出同批次充值卡明细")
    @PostMapping(value = "/exportCardDetailByBatchNo")
    public void exportCardDetailByBatchNo(HttpServletResponse response, @RequestBody @Valid RechargeBatchCardDetailListQueryDTO rechargeBatchCardDetailListQueryDTO) {
        int count = rechargeCardBatchRecordService.countCardDetailByBatchNo(rechargeBatchCardDetailListQueryDTO);
        if (count == 0) {
            ExcelUtil<RechargeBatchCardDetailListQueryVO> util = new ExcelUtil<>(RechargeBatchCardDetailListQueryVO.class);
            util.exportExcel(response, new ArrayList<>(), "导出同批次充值卡明细");
            return;
        }
        List<RechargeBatchCardDetailListQueryVO> list = rechargeCardBatchRecordService.listCardDetailByBatchNo(rechargeBatchCardDetailListQueryDTO);
//        List<SysOrg> sysOrgs = sysOrgService.list(new QueryWrapper<SysOrg>().lambda().eq(SysOrg::getStatus, StatusType.OK.getCode())
//                .orderByAsc(SysOrg::getSourceType));
//        if (CollUtil.isNotEmpty(list) && CollUtil.isNotEmpty(sysOrgs)){
//            for (RechargeBatchCardDetailListQueryVO vo : list) {
//                if(StrUtil.isEmpty(vo.getRechargeSourceType())){
//                    vo.setRechargeStoreName(SourceType.MANAGER.getInfo());
//                }
//                if ()
//
//            }
//        }
        ExcelUtil<RechargeBatchCardDetailListQueryVO> util = new ExcelUtil<>(RechargeBatchCardDetailListQueryVO.class);
        util.exportExcel(response, list, "导出同批次充值卡明细");
    }

    @ApiOperation("同批次充值卡明细列表")
    @PostMapping(value = "/listCardDetailByBatchNo")
    public R<Page<RechargeBatchCardDetailListQueryVO>> listCardDetailByBatchNo(@RequestBody @Valid RechargeBatchCardDetailListQueryDTO rechargeBatchCardDetailListQueryDTO) {
        Page<RechargeBatchCardDetailListQueryVO> page = new Page<>();
        int count = rechargeCardBatchRecordService.countCardDetailByBatchNo(rechargeBatchCardDetailListQueryDTO);
        if (count == 0) {
            return R.ok(page);
        }
        List<RechargeBatchCardDetailListQueryVO> list = rechargeCardBatchRecordService.listCardDetailByBatchNo(rechargeBatchCardDetailListQueryDTO);
        page.setRecords(list);
        page.setTotal(count);
        return R.ok(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("批次号明细详情-充值卡删除")
    @GetMapping(value = "/deleteCardByCardId")
    public R deleteCardByCardId(@RequestParam("rechargeCardId") Long rechargeCardId) {
        rechargeCardBatchRecordService.deleteCardByCardId(rechargeCardId);
        return R.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("批次号明细详情-充值卡新增")
    @PostMapping(value = "/addOneCard")
    public R addOneCard(@RequestBody @Valid RechargeBatchCardOneAddDTO rechargeBatchCardOneAddDTO) {
        RechargeCardBatchRecord rechargeCardBatchRecord = rechargeCardBatchRecordService.getOne(new QueryWrapper<RechargeCardBatchRecord>().lambda()
                .eq(RechargeCardBatchRecord::getBatchNo, rechargeBatchCardOneAddDTO.getBatchNo()), Boolean.FALSE);
        if (rechargeCardBatchRecord == null) {
            throw new ServiceException("未查询到该批次号,无法新增");
        }
        if (StrUtil.isNotEmpty(rechargeBatchCardOneAddDTO.getAppUserPhoneNumber())) {
            RechargeBatchDirectCardAddDTO rechargeBatchDirectCardAddDTO = new RechargeBatchDirectCardAddDTO();
            BeanUtils.copyProperties(rechargeBatchCardOneAddDTO, rechargeBatchDirectCardAddDTO);
            rechargeCardBatchRecordService.addOneCardByDirect(rechargeBatchDirectCardAddDTO, rechargeCardBatchRecord);
        } else {
            RechargeBatchCommonCardAddDTO rechargeBatchCommonCardAddDTO = new RechargeBatchCommonCardAddDTO();
            BeanUtils.copyProperties(rechargeBatchCardOneAddDTO, rechargeBatchCommonCardAddDTO);
            rechargeCardBatchRecordService.addOneCardByCommon(rechargeBatchCommonCardAddDTO, rechargeCardBatchRecord);
        }
        return R.ok();
    }

    @ApiOperation("导出同批次充值卡消费记录")
    @PostMapping(value = "/exportCardUseRecordByBatchNo")
    public void exportCardUseRecordByBatchNo(HttpServletResponse response, @RequestBody @Valid RechargeBatchUseRecordListQueryDTO rechargeBatchUseRecordListQueryDTO) {
        List<RechargeBatchUseRecordListQueryVO> list = rechargeCardBatchRecordService.listCardUseRecordByBatchNo(rechargeBatchUseRecordListQueryDTO);
        ExcelUtil<RechargeBatchUseRecordListQueryVO> util = new ExcelUtil<>(RechargeBatchUseRecordListQueryVO.class);
        util.exportExcel(response, list, "导出同批次充值卡消费记录");
    }

    @ApiOperation("同批次充值卡的消费记录列表")
    @GetMapping(value = "/listCardUseRecordByBatchNo")
    public R listCardUseRecordByBatchNo(@Valid RechargeBatchUseRecordListQueryDTO rechargeBatchUseRecordListQueryDTO) {
        Page<RechargeBatchUseRecordListQueryVO> page = new Page<>();
        int count = rechargeCardBatchRecordService.countCardUseRecordByBatchNo(rechargeBatchUseRecordListQueryDTO);
        if (count == 0) {
            return R.ok(page);
        }
        List<RechargeBatchUseRecordListQueryVO> list = rechargeCardBatchRecordService.listCardUseRecordByBatchNo(rechargeBatchUseRecordListQueryDTO);
        return R.page(list, Long.valueOf(count));
    }
}
