package com.yuchen.saas.park.service.service.impl;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuchen.saas.manage.system.api.entity.NestOrgUserApply;
import com.yuchen.saas.manage.user.api.entity.UserDetail;
import com.yuchen.saas.manage.user.api.feign.IUserClient;
import com.yuchen.saas.park.api.entity.park.PmgBatParkInfo;
import com.yuchen.saas.park.api.entity.park.PmgBatParkSnapshotNewspaper;
import com.yuchen.saas.park.api.feign.service.ParkFeignService;
import com.yuchen.saas.park.api.vo.park.PmgBatParkSnapshotNewspaperExcel;
import com.yuchen.saas.park.api.vo.park.SnapshotNewspaperDealVo;
import com.yuchen.saas.park.api.vo.park.SnapshotNewspaperDetailVo;
import com.yuchen.saas.park.api.vo.park.SnapshotNewspaperPageVo;
import com.yuchen.saas.park.api.vo.request.PmgBatParkSnapshotNewspaperAddRequest;
import com.yuchen.saas.park.api.vo.request.PmgBatParkSnapshotNewspaperDealRequest;
import com.yuchen.saas.park.service.mapper.PmgBatParkSnapshotNewspaperMapper;
import com.yuchen.saas.park.service.service.IPmgBatParkSnapshotNewspaperService;
import com.yuchen.saas.parking.api.entity.PmgBatParkParking;
import com.yuchen.saas.parking.api.entity.VehicleOccupancyFeePayment;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.mp.support.Condition;
import org.nest.springwrap.core.mp.support.Query;
import org.nest.springwrap.core.secure.ContextUser;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.api.R;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 随手拍管理表 服务实现类
 * </p>
 *
 * @author cxj
 * @since 2023-07-20
 */
@Service
public class PmgBatParkSnapshotNewspaperServiceImpl extends BaseServiceImpl<PmgBatParkSnapshotNewspaperMapper, PmgBatParkSnapshotNewspaper> implements IPmgBatParkSnapshotNewspaperService {

    @Resource
    private IUserClient iUserClient;

    @Resource
    private ParkFeignService parkFeignService;

    @Override
    public Boolean submit(PmgBatParkSnapshotNewspaperAddRequest addRequest) {
        PmgBatParkSnapshotNewspaper dto = new PmgBatParkSnapshotNewspaper();
        if (Func.isEmpty(addRequest)) {
            return false;
        }
        if (Func.isNotEmpty(addRequest.getParkId()) || Func.isNotEmpty(addRequest.getParkingId()) || Func.isNotEmpty(addRequest.getStationId())) {
            BeanUtils.copyProperties(addRequest, dto);
            ContextUser user = AuthUtil.getUser();
            if (Func.isNotEmpty(user)) {
                dto.setUserDetailId(user.getUserDetailId());
            }
            return save(dto);

        } else {
            throw new ServiceException("请选择地址");
        }

    }

    @Override
    public IPage<PmgBatParkSnapshotNewspaper> pageByApp(Integer newspaperType, Integer handleState, String beginDate, String endDate, String openId, int current, int size) {

        ContextUser user = AuthUtil.getUser();
        LambdaQueryWrapper<PmgBatParkSnapshotNewspaper> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Func.isNotEmpty(newspaperType), PmgBatParkSnapshotNewspaper::getNewspaperType, newspaperType)
                .eq(Func.isNotEmpty(handleState), PmgBatParkSnapshotNewspaper::getHandleState, handleState)
                .le(Func.isNotEmpty(endDate), PmgBatParkSnapshotNewspaper::getCreateTime, endDate)
                .ge(Func.isNotEmpty(beginDate), PmgBatParkSnapshotNewspaper::getCreateTime, beginDate)
                .and(wrapper -> wrapper
                        .or(item -> item
                                .eq(PmgBatParkSnapshotNewspaper::getOpenId, openId))
                        .or((Func.isNotEmpty(user)&&Func.isNotEmpty(user.getUserDetailId())),item -> item
                                .eq(PmgBatParkSnapshotNewspaper::getUserDetailId, user.getUserDetailId())
                        )).orderByDesc(PmgBatParkSnapshotNewspaper::getCreateTime);
        Query query = new Query();
        query.setCurrent(current);
        query.setSize(size);
        return this.page(Condition.getPage(query), queryWrapper);
    }

    @Override
    public IPage<SnapshotNewspaperPageVo> queryPage(Integer type, Long code, Integer newspaperType, Integer handleState, String beginDate, String endDate, int current, int size) {

        LambdaQueryWrapper<PmgBatParkSnapshotNewspaper> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Func.isNotEmpty(newspaperType), PmgBatParkSnapshotNewspaper::getNewspaperType, newspaperType)
                .eq(Func.isNotEmpty(handleState), PmgBatParkSnapshotNewspaper::getHandleState, handleState)
                .le(Func.isNotEmpty(endDate), PmgBatParkSnapshotNewspaper::getCreateTime, endDate)
                .ge(Func.isNotEmpty(beginDate), PmgBatParkSnapshotNewspaper::getCreateTime, beginDate)
                .orderByDesc(PmgBatParkSnapshotNewspaper::getCreateTime);
        if (Func.isNotEmpty(type) && Func.isNotEmpty(code)) {
            if (type.equals(1)) {
                queryWrapper.eq(PmgBatParkSnapshotNewspaper::getParkId, code);
            } else if (type.equals(2)) {
                queryWrapper.eq(PmgBatParkSnapshotNewspaper::getParkingId, code);
            } else if (type.equals(3)) {
                queryWrapper.eq(PmgBatParkSnapshotNewspaper::getStationId, code);
            }
        }
        Query query = new Query();
        query.setCurrent(current);
        query.setSize(size);
        IPage<PmgBatParkSnapshotNewspaper> page=this.page(Condition.getPage(query), queryWrapper);
        IPage<SnapshotNewspaperPageVo> result=new Page<>();
        BeanUtils.copyProperties(page, result);
        List<PmgBatParkSnapshotNewspaper> pageList=page.getRecords();
        if(Func.isEmpty(pageList)){
            return result;
        }
        List<SnapshotNewspaperPageVo> resultList=new ArrayList<>();
        for (PmgBatParkSnapshotNewspaper item:pageList) {
            SnapshotNewspaperPageVo vo=new SnapshotNewspaperPageVo();
            BeanUtils.copyProperties(item,vo);
            R<UserDetail> userDetailR2 = iUserClient.userDetailById(item.getUserDetailId());
            if (userDetailR2.isSuccess() && Func.isNotEmpty(userDetailR2.getData()) && Func.isNotEmpty(userDetailR2.getData().getId())) {
                vo.setPhone(userDetailR2.getData().getPhone());
            }
            resultList.add(vo);
        }
        result.setRecords(resultList);
        return result;
    }

    @Override
    public SnapshotNewspaperDealVo deal(PmgBatParkSnapshotNewspaperDealRequest dealRequest) {
        if (Func.isEmpty(dealRequest.getIds())) {
            throw new ServiceException("请选择要处理的数据");
        }
        if(Func.isNotEmpty(dealRequest.getHandleTime())&&dealRequest.getHandleTime().getTime()>System.currentTimeMillis()){
            throw new ServiceException("处理时间不能超过当前时间");
        }

        //总数
        int totalSize = dealRequest.getIds().size();
        int failureSize = 0;
        List<PmgBatParkSnapshotNewspaper> list = new ArrayList<>();
        for (Long id : dealRequest.getIds()) {
            PmgBatParkSnapshotNewspaper dto = getById(id);
            if (Func.isEmpty(dto)) {
                failureSize++;
                continue;
            }
            if (dto.getHandleState() != 0) {
                failureSize++;
                continue;
            }
            dto.setHandleUserName(dealRequest.getHandleUserName());
            dto.setHandleRemark(dealRequest.getHandleRemark());
            dto.setHandleFile(dealRequest.getHandleFile());
            dto.setHandleType(dealRequest.getHandleType());
            dto.setHandleState(1);
            dto.setHandleTime(dealRequest.getHandleTime());
            list.add(dto);
        }
        updateBatchById(list);
        SnapshotNewspaperDealVo vo = new SnapshotNewspaperDealVo();
        vo.setSuccessSize(totalSize - failureSize);
        vo.setFailureSize(failureSize);
        return vo;
    }

    @Override
    public SnapshotNewspaperDetailVo getDetailById(Long id) {
        PmgBatParkSnapshotNewspaper dto = getById(id);
        if (Func.isEmpty(dto)) {
            throw new ServiceException("参数错误");
        }
        SnapshotNewspaperDetailVo vo = new SnapshotNewspaperDetailVo();
        BeanUtils.copyProperties(dto, vo);
        return vo;
    }

    @Override
    public void export(Integer type, Long code, Integer newspaperType, Integer handleState, String beginDate, String endDate, HttpServletResponse response) {
        LambdaQueryWrapper<PmgBatParkSnapshotNewspaper> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Func.isNotEmpty(newspaperType), PmgBatParkSnapshotNewspaper::getNewspaperType, newspaperType)
                .eq(Func.isNotEmpty(handleState), PmgBatParkSnapshotNewspaper::getHandleState, handleState)
                .le(Func.isNotEmpty(endDate), PmgBatParkSnapshotNewspaper::getCreateTime, endDate)
                .ge(Func.isNotEmpty(beginDate), PmgBatParkSnapshotNewspaper::getCreateTime, beginDate)
                .orderByDesc(PmgBatParkSnapshotNewspaper::getCreateTime);
        if (Func.isNotEmpty(type) && Func.isNotEmpty(code)) {
            if (type.equals(1)) {
                queryWrapper.eq(PmgBatParkSnapshotNewspaper::getParkId, code);
            } else if (type.equals(2)) {
                queryWrapper.eq(PmgBatParkSnapshotNewspaper::getParkingId, code);
            } else if (type.equals(3)) {
                queryWrapper.eq(PmgBatParkSnapshotNewspaper::getStationId, code);
            }

        }
        List<PmgBatParkSnapshotNewspaper> list = list(queryWrapper);
        List<PmgBatParkSnapshotNewspaperExcel>result=new ArrayList<>();
        R<List<PmgBatParkInfo>> parkingList = parkFeignService.getParkAll2();
        Map<Long,String> parkMap=new HashMap<>();
        if(parkingList.isSuccess()&&Func.isNotEmpty(parkingList)){
            parkMap=parkingList.getData().stream().collect(Collectors.toMap(PmgBatParkInfo::getId, PmgBatParkInfo::getParkName));
        }

        for (PmgBatParkSnapshotNewspaper item:list) {
            PmgBatParkSnapshotNewspaperExcel vo = new PmgBatParkSnapshotNewspaperExcel();
            BeanUtils.copyProperties(item,vo);
            if(Func.isNotEmpty(item.getUserDetailId())){
                R<UserDetail> userDetailR2 = iUserClient.userDetailById(item.getUserDetailId());
                if (userDetailR2.isSuccess() && Func.isNotEmpty(userDetailR2.getData()) && Func.isNotEmpty(userDetailR2.getData().getId())) {
                    vo.setPhone(userDetailR2.getData().getPhone());
                }
            }
            if(Func.isNotEmpty(item.getParkId())&&Func.isNotEmpty(parkMap)&&parkMap.containsKey(item.getParkId())){
                vo.setParkName(parkMap.get(item.getParkId()));
            }

            result.add(vo);

        }
        //导出
        try {
            String fileName = URLEncoder.encode("拍报导出", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), PmgBatParkSnapshotNewspaperExcel.class)
                    .sheet("拍报导出")
                    .doWrite(result); //最终处理好的数据结果集list
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}
