package org.jeecg.ctop.finance.settlement.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.entity.SysUser;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.ctop.finance.policy.utils.Check;
import org.jeecg.ctop.finance.settlement.entity.pojo.CtopCwjsSettlementFileInfo;
import org.jeecg.ctop.finance.settlement.entity.vo.SettlementFileParamsVo;
import org.jeecg.ctop.finance.settlement.mapper.ReportSettlementMapper;
import org.jeecg.ctop.finance.settlement.mapper.SettlementFileInfoMapper;
import org.jeecg.ctop.finance.settlement.mapper.SettlementInfoMapper;
import org.jeecg.ctop.finance.settlement.service.IReportSettlementService;
import org.jeecg.ctop.finance.settlement.service.ISettlementFileInfoService;
import org.jeecg.ctop.finance.utils.SettlementUtil;
import org.jeecg.ctop.finance.utils.createExcelByTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.*;


@Slf4j
@Service
public class SettlementFileInfoServiceImpl extends ServiceImpl<SettlementFileInfoMapper, CtopCwjsSettlementFileInfo> implements ISettlementFileInfoService {

    @Resource
    private SettlementFileInfoMapper settlementFileInfoMapper;

    @Resource
    private SettlementInfoMapper settlementInfoMapper;


    /**
     *
     * @description: 查询 财务结算-结算单列表
     *
     * @param paramsVo
     * @param pageNo
     * @param pageSize
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
   /* @Override
    public Result<PageInfo<Map<String,String>>> getSettlementSheetList(SettlementFileParamsVo paramsVo, Integer pageNo, Integer pageSize) {
        Set accountSet = new HashSet();
        Set imageSet = new HashSet();
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String,String>> list = settlementFileInfoMapper.getSettlementSheetList(paramsVo);
        list.forEach(map -> {
            //账户数量
            QueryWrapper<ctopCwjsSettlementInfo> settlementAccountQw = new QueryWrapper<>();
            //广告主id
            settlementAccountQw.eq("advertiser_id",map.get("advertiserId"));
            //产品id
            settlementAccountQw.eq("product_id",map.get("productId"));
            //媒体类型 1-头条 2-快手 3-头条内广 4-快手内广
            settlementAccountQw.eq("media_id",map.get("mediaId"));
            //账户状态 0-开 1-关
            settlementAccountQw.eq("status",0);
            //（0，正常，1已删除）
            settlementAccountQw.eq("del_flag",0);
            List<ctopCwjsSettlementInfo> settlementAccountList =  settlementInfoMapper.selectList(settlementAccountQw);
            List<String>  advertiserList = settlementAccountList.stream().map(ctopCwjsSettlementInfo::getAccountId).collect(Collectors.toList());
            if (!Check.isNull(advertiserList)){
                accountSet.addAll(advertiserList);
            }
            //图片数量
            QueryWrapper<ctopCwjsSettlementFileInfo> settlementFileInfoQw = new QueryWrapper<>();
            //广告主id
            settlementFileInfoQw.eq("advertiser_id",map.get("advertiserId"));
            //产品id
            settlementFileInfoQw.eq("product_id",map.get("productId"));
            //媒体类型 1-头条 2-快手 3-头条内广 4-快手内广
            settlementFileInfoQw.eq("media_id",map.get("mediaId"));
            //上传人 （运营）
            settlementFileInfoQw.eq("create_user_id",map.get("operateUserId"));
            //（0，正常，1已删除）
            settlementFileInfoQw.eq("del_flag",0);
            List<ctopCwjsSettlementFileInfo> settlementFileList =  settlementFileInfoMapper.selectList(settlementFileInfoQw);
            List<String>  imageList = settlementFileList.stream().map(ctopCwjsSettlementFileInfo::getAccountId).collect(Collectors.toList());
            if (!Check.isNull(imageList)){
                imageSet.addAll(imageList);
            }
            map.put("accountCount", Check.isNull(settlementAccountList) ? "0" : String.valueOf(settlementAccountList.size()));
            map.put("imageCount",Check.isNull(settlementFileList) ? "0" : String.valueOf(settlementFileList.size()));
        });

        //当前页 账户、图片（去重）总计
        if (!Check.isNull(list)){
            list.get(0).put("accountTotal",Check.isNull(accountSet.size()) ? "0" : String.valueOf(accountSet.size()));
            list.get(0).put("imageTotal",Check.isNull(imageSet.size()) ? "0" : String.valueOf(imageSet.size()));
        }

        PageInfo<Map<String,String>> pageInfo = new PageInfo<>(list);
        return Result.successMsg("财务结算-结算单列表查询成功。", pageInfo);
    }
*/

    /**
     *
     * @description: 查询 财务结算-结算单列表
     *
     * @param paramsVo
     * @param pageNo
     * @param pageSize
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result<PageInfo<Map<String,String>>> getSettlementSheetList(SettlementFileParamsVo paramsVo, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String,String>> list = settlementFileInfoMapper.getSettlementSheetList(paramsVo);
        for (Map<String, String> map : list) {
            //图片数量
            QueryWrapper<CtopCwjsSettlementFileInfo> settlementFileInfoQw = new QueryWrapper<>();
            //广告主id
            settlementFileInfoQw.eq("advertiser_id",map.get("advertiserId"));
            //产品id
            settlementFileInfoQw.eq("product_id",map.get("productId"));
            settlementFileInfoQw.eq("account_id",map.get("accountId"));
            //媒体类型 1-头条 2-快手 3-头条内广 4-快手内广
            settlementFileInfoQw.eq("media_id",map.get("mediaId"));
            //上传人 （运营）
            settlementFileInfoQw.eq("create_user_id",map.get("operateUserId"));
            //（0，正常，1已删除）
            settlementFileInfoQw.eq("del_flag",0);
            List<CtopCwjsSettlementFileInfo> settlementFileList =  settlementFileInfoMapper.selectList(settlementFileInfoQw);
            map.put("imgNum",Check.isNull(settlementFileList) ? "0" : String.valueOf(settlementFileList.size()));
        }
        PageInfo<Map<String,String>> pageInfo = new PageInfo<>(list);
        return Result.successMsg("财务结算-结算单列表查询成功", pageInfo);
    }


    /**
     *
     * @description: 删除
     *
     * @param paramsVo
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result deleteSettlementFile(SettlementFileParamsVo paramsVo) {
        settlementFileInfoMapper.deleteSettlementFile(paramsVo);
        return Result.successMsg("删除成功",null);
    }


    /**
     * @description: 上传账户截图
     * @param settlementFileInfo
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    @Transactional
    public Result insertAccountImages(CtopCwjsSettlementFileInfo settlementFileInfo){
        try {
            for (CtopCwjsSettlementFileInfo settlement : settlementFileInfo.getSettlementList()) {
                settlement.setAccountId(SettlementUtil.subAccountName(settlement.getFileName()).replaceAll(" ",""));

                //TODO 上传图片判断 是否可以正常读取 width 和 high 如果不能读取 则上传失败 否则在下载结算单的时候会出错
                InputStream is = createExcelByTemplate.getInputStreamByUrl(settlement.getFileUrl());
                BufferedImage bufferImg = ImageIO.read(is);
                if (Check.isNull(bufferImg) || bufferImg.getWidth() < 0 || bufferImg.getHeight() < 0){
                    return Result.errorMsg("【"+settlement.getFileName()+"】该文件不符合规范，请上传正确的账户截图文件。");
                }
               /* Map<String,String> map = settlementFileInfoMapper.getSettlementAccount(settlement.getAccountId(),String.valueOf(settlementFileInfo.getMediaId()));
                if (Check.isNull(map)){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return Result.errorMsg("无法查询到账户【"+settlement.getAccountId()+"】信息，请到账户列表上传正确的账户信息");
                }*/

                BeanUtils.copyProperties(settlementFileInfo,settlement,SettlementUtil.getNullPropertyNames(settlementFileInfo));
                settlementFileInfoMapper.insert(settlement);
                //log.info("上传截图======{}====",settlement);
            }
            return Result.successMsg("账户截图上传成功",null);
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.errorMsg("上传失败。");
    }

    @Autowired
    private IReportSettlementService reportSettlementService;
    @Resource
    private ReportSettlementMapper reportSettlementMapper;

    /**
     * @description: 查询账户数量以及图片数量
     * @param paramsVo
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result getAccountNumAndImgNum(SettlementFileParamsVo paramsVo, SysUser user) {
        //查询图片数量
        Map<String,String> map =  settlementFileInfoMapper.getAccountNumAndImgNum(paramsVo);
        //查询账户数量
        List<String>accountIds = reportSettlementService.getAccountId(paramsVo,user);
        if (Check.isNull(accountIds)){
            map.put("accountNum","0");
        }else {
            //过滤消耗为0 的账户 1-头条 2-快手
            if (paramsVo.getMediaId().equals(1)){
                accountIds = reportSettlementMapper.getAccountIdBytedanceRepeat(accountIds,paramsVo.getStartTime(),paramsVo.getEndTime());
            }else if (paramsVo.getMediaId().equals(2)){
                accountIds = reportSettlementMapper.getAccountIdKuaiShouRepeat(accountIds,paramsVo.getStartTime(),paramsVo.getEndTime());
            }
            map.put("accountNum",accountIds.size()+"");
        }
        return Result.successMsg("查询账户数量以及图片数量成功",map);
    }


}
