package org.dromara.payment.taxRecords.service.impl;

import org.dromara.common.core.enums.BusRole;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.payment.bill.domain.vo.MerBillDetailVo;
import org.dromara.payment.bill.domain.vo.MerBillVo;
import org.dromara.payment.common.domain.CommonSelConditionEntity;
import org.dromara.payment.merchant.domain.BusMerchant;
import org.dromara.payment.merchant.mapper.BusMerchantMapper;
import org.dromara.payment.sys.domain.SysSyd;
import org.dromara.payment.sys.mapper.SysSydMapper;
import org.dromara.payment.thirdPlatform.base.domain.SysThirdPlatform;
import org.dromara.payment.thirdPlatform.base.mapper.SysThirdPlatformMapper;
import org.dromara.payment.thirdPlatform.xinyujian.service.IXyjService;
import org.springframework.stereotype.Service;
import org.dromara.payment.taxRecords.domain.bo.MerTaxRecordsBo;
import org.dromara.payment.taxRecords.domain.vo.MerTaxRecordsVo;
import org.dromara.payment.taxRecords.domain.MerTaxRecords;
import org.dromara.payment.taxRecords.mapper.MerTaxRecordsMapper;
import org.dromara.payment.taxRecords.service.IMerTaxRecordsService;

import javax.annotation.Resource;
import java.util.*;

/**
 * 完税证明Service业务层处理
 *
 * @author LionLi
 * @date 2024-05-06
 */
@RequiredArgsConstructor
@Service
public class MerTaxRecordsServiceImpl implements IMerTaxRecordsService {

    private final MerTaxRecordsMapper baseMapper;


    @Resource
    private AsyncTaxRecordsService  asyncTaxRecordsService;
    @Resource
    private  SysSydMapper sydMapper;
    @Resource
    private  IXyjService xyjService;
    @Resource
    private  BusMerchantMapper merchantMapper;

    @Resource
    private SysThirdPlatformMapper sysThirdPlatformMapper;

    /**
     * 查询完税证明
     */
    @Override
    public MerTaxRecordsVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询完税证明列表
     */
    @Override
    public TableDataInfo<MerTaxRecordsVo> queryPageList(CommonSelConditionEntity bo, PageQuery pageQuery) {
        QueryWrapper<MerTaxRecords> lqw = new QueryWrapper<>();
        lqw.between(bo.getStartTime() != null,"t.create_time",bo.getStartTime(),bo.getEndTime());
        lqw.like(StringUtils.isNotEmpty(bo.getBusMerName()),"t1.name",bo.getBusMerName());
        lqw.like(StringUtils.isNotEmpty(bo.getSynName()),"t2.gsmc",bo.getSynName());
        lqw.eq(bo.getWsZmStatus() != null,"t.tax_status",bo.getWsZmStatus());
        if(LoginHelper.getBusRole() == BusRole.SERVICE.getId()){
            lqw.eq("t.syd_id",LoginHelper.getBusId());
        }else if(LoginHelper.getBusRole() == BusRole.AGENT.getId()){
            lqw.likeRight("t.channel_no",LoginHelper.getNo());
        }else if(LoginHelper.getBusRole() == BusRole.OPERATOR.getId()){
            lqw.eq("t.op_id",LoginHelper.getBusId());
        }
        lqw.orderByDesc("t.create_time");
        Page<MerTaxRecordsVo> result = baseMapper.selTaxRecordsList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询完税证明列表
     */
    @Override
    public List<MerTaxRecordsVo> queryList(MerTaxRecordsBo bo) {
        QueryWrapper<MerTaxRecords> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private QueryWrapper<MerTaxRecords> buildQueryWrapper(MerTaxRecordsBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<MerTaxRecords> lqw = new QueryWrapper<>();
        lqw.eq(bo.getSydId() != null, "syd_id", bo.getSydId());
        lqw.eq(StringUtils.isNotBlank(bo.getSydNo()), "syd_no", bo.getSydNo());
        lqw.eq(StringUtils.isNotBlank(bo.getOpNo()), "op_no", bo.getOpNo());
        lqw.eq(bo.getOpId() != null, "op_id", bo.getOpId());
        lqw.eq(bo.getChannelId() != null, "channel_id", bo.getChannelId());
        lqw.eq(StringUtils.isNotBlank(bo.getChannelNo()), "channel_no", bo.getChannelNo());
        lqw.eq(StringUtils.isNotBlank(bo.getChannelCode()), "channel_code", bo.getChannelCode());
        lqw.eq(bo.getMerId() != null, "mer_id", bo.getMerId());
        lqw.eq(StringUtils.isNotBlank(bo.getMerNo()), "mer_no", bo.getMerNo());
        lqw.eq(StringUtils.isNotBlank(bo.getMonth()), "month", bo.getMonth());
        lqw.eq(StringUtils.isNotBlank(bo.getInvoiceNos()), "invoice_nos", bo.getInvoiceNos());
        lqw.eq(StringUtils.isNotBlank(bo.getBillNos()), "bill_nos", bo.getBillNos());
        lqw.eq(StringUtils.isNotBlank(bo.getBillIds()), "bill_ids", bo.getBillIds());
        lqw.eq(bo.getTaxStatus() != null, "tax_status", bo.getTaxStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getTaxFile()), "tax_file", bo.getTaxFile());
        lqw.eq(StringUtils.isNotBlank(bo.getTaxRemark()), "tax_remark", bo.getTaxRemark());
        return lqw;
    }

    /**
     * 新增完税证明
     */
    @Override
    public Boolean insertByBo(MerTaxRecordsBo bo) {
        MerTaxRecords add = MapstructUtils.convert(bo, MerTaxRecords.class);
        validEntityBeforeSave(add);
        SysSyd sysSyd = sydMapper.selectSysSydById(add.getSydId());
        BusMerchant busMerchant = merchantMapper.selectById(add.getMerId());
        boolean flag;
        SysThirdPlatform sysThirdPlatform = sysThirdPlatformMapper.selectThirdAppInfo(sysSyd.getThreeId());
        if(Objects.nonNull(sysThirdPlatform) && sysThirdPlatform.getPlatformName().equals("薪遇见")){
            flag = xyjService.taxpayDownLoad(busMerchant,sysSyd,bo.getMonth());
        }else {
            flag = baseMapper.insert(add) > 0;
        }
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改完税证明
     */
    @Override
    public Boolean updateByBo(MerTaxRecordsBo bo) {
        MerTaxRecords update = MapstructUtils.convert(bo, MerTaxRecords.class);
        update.setTaxStatus(1);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MerTaxRecords entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除完税证明
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }



    @Override
    public Map downLoadUserworkSfz(Long trId)throws Exception {
        Map resultMap = new HashMap();
        MerTaxRecordsVo  records = this.baseMapper.selectVoById(trId);
        resultMap.put("isUrl",2);
        if(records != null && StringUtils.isNotEmpty(records.getSfzZip())){
            resultMap.put("isUrl",1);
            resultMap.put("url",records.getSfzZip());
        }else{
            resultMap.put("msg","正在生成中,请稍后下载");
            this.asyncTaxRecordsService.getSfzZip(trId);
        }
        return resultMap;
    }

    @Override
    public Map downLoadUserworkHt(Long trId) throws Exception {
        Map resultMap = new HashMap();
        MerTaxRecordsVo  records = this.baseMapper.selectVoById(trId);
        resultMap.put("isUrl",2);
        if(records != null && StringUtils.isNotEmpty(records.getHTzip())){
            resultMap.put("isUrl",1);
            resultMap.put("url",records.getHTzip());
        }else{
            resultMap.put("msg","正在生成中,请稍后下载");
            this.asyncTaxRecordsService.getHtZip(trId);
        }
        return resultMap;
    }

    @Override
    public Map downLoadUserworkPayCer(Long trId) throws Exception {
        Map resultMap = new HashMap();
        MerTaxRecordsVo  records = this.baseMapper.selectVoById(trId);
        resultMap.put("isUrl",2);
        if(records != null && StringUtils.isNotEmpty(records.getPayZip())){
            resultMap.put("isUrl",1);
            resultMap.put("url",records.getPayZip());
        }else{
            resultMap.put("msg","正在生成中,请稍后下载");
            this.asyncTaxRecordsService.getPayCerZip(trId);
        }
        return resultMap;
    }





    @Override
    public MerBillVo getMerBillInfo(String billNo) {
        return null;
    }

    @Override
    public TableDataInfo<MerBillDetailVo> getMerBillDetailList(String billNo, PageQuery pageQuery) {
        return null;
    }

    @Override
    public TableDataInfo getInvDetailList(String invNo, PageQuery pageQuery) {
        return null;
    }

    @Override
    public String getInvInfo(String invNo) {
        return null;
    }


}
