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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.enums.BusRole;
import org.dromara.common.core.service.BaseService;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.file.FileUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.payment.api.worker.RemoteUserWokerService;
import org.dromara.payment.api.worker.domain.RemoteUserWorkerZipVo;
import org.dromara.payment.bill.domain.vo.MerBillDetailVo;
import org.dromara.payment.bill.mapper.MerBillDetailMapper;
import org.dromara.payment.invoice.domain.vo.MerInvoiceDetailVo;
import org.dromara.payment.task.domain.MerTaskEnroll;
import org.dromara.payment.task.domain.vo.MerTaskEnrollVo;
import org.dromara.payment.task.mapper.MerTaskEnrollMapper;
import org.dromara.payment.task.service.IMerTaskEnrollService;
import org.dromara.payment.taxRecords.domain.MerTaxRecords;
import org.dromara.payment.taxRecords.domain.MerTaxRecordsDetail;
import org.dromara.payment.taxRecords.domain.bo.SwMonitorBo;
import org.dromara.payment.taxRecords.domain.vo.MerTaxRecordsVo;
import org.dromara.payment.taxRecords.domain.vo.SwMonitorVo;
import org.dromara.payment.taxRecords.mapper.MerTaxRecordsDetailMapper;
import org.dromara.payment.taxRecords.mapper.MerTaxRecordsMapper;
import org.dromara.payment.taxRecords.mapper.SwMonitorMapper;
import org.dromara.payment.taxRecords.service.ISwMonitorService;
import org.dromara.payment.worker.domain.vo.UserWorkerBusinessVo;
import org.dromara.payment.worker.domain.vo.UserWorkerVo;
import org.dromara.payment.worker.mapper.UserWorkerBusinessMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author sunzexing
 * @version 1.0
 * @title SwMonitorServiceImpl
 * @description
 * @create 2024-06-24 10:42
 */

@Service
public class SwMonitorServiceImpl extends BaseService implements ISwMonitorService {


    @Resource
    private SwMonitorMapper baseMapper;

    @Resource
    private MerTaskEnrollMapper merTaskEnrollMapper;

    @Resource
    private MerBillDetailMapper billDetailMapper;

    @Resource
    private UserWorkerBusinessMapper userWorkerBusinessMapper;

    @Resource
    private MerTaxRecordsMapper  merTaxRecordsMapper;


    @Resource
    private MerTaxRecordsDetailMapper merTaxRecordsDetailMapper;
    @DubboReference
    private RemoteUserWokerService remoteUserWokerService;



    @Override
    public TableDataInfo<SwMonitorVo> queryPageList(SwMonitorBo bo, PageQuery pageQuery) {
        QueryWrapper<SwMonitorBo> lqw = new QueryWrapper<>();
        lqw.between(bo.getStartTime() != null,"t.create_time",bo.getStartTime(),bo.getEndTime());
        lqw.like(StringUtils.isNotEmpty(bo.getProNo()),"t4.no",bo.getProNo());
        lqw.like(StringUtils.isNotEmpty(bo.getProSubNo()),"t.cno",bo.getProSubNo());
        lqw.like(StringUtils.isNotEmpty(bo.getWorkName()),"t.worker_name",bo.getWorkName());
        lqw.like(StringUtils.isNotEmpty(bo.getMerName()),"t1.name",bo.getMerName());
        lqw.like(StringUtils.isNotEmpty(bo.getSydName()),"t2.gsmc",bo.getSydName());
        lqw.eq("t.pay_status",1);
        lqw.eq(bo.getBusType() !=null,"t.bus_type",bo.getBusType());
        int  busRole = LoginHelper.getBusRole();
        if(busRole != BusRole.PLATFORM.getId()){
       //     lqw.eq("t.op_id",LoginHelper.getBusId());
            lqw.eq("t1.id",LoginHelper.getBusId ());
        }

        lqw.orderByDesc("t.create_time");
        Page<SwMonitorVo> result = baseMapper.selSwMonitorList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }



    @Override
    public MerTaskEnrollVo getTaskEnrollVo(String proSubNo){
        return this.baseMapper.selTaskEnRollBySubBo(proSubNo);
    }


    /***
     * @param tailId  账单明细ID
     * @param tailNo 账单号
     * @param subNo  子项目编码
     * @param type 类型
     * @return
     */
    @Override
    public String getFileUrl(Long tailId, String tailNo, String subNo, Integer type,Long workId,Integer busType,Long syId,Long merId) {
        switch(type){
            case 1:
                //b2c凭证
                MerBillDetailVo vo = this.billDetailMapper.selectVoById(tailId);
                return vo.getPayReceipt();
            case 2:
                //b2b凭证
                 vo = this.billDetailMapper.selectVoById(tailId);
                return vo.getPayReceiptB2b();
            case 3:
//                //发票
                List<MerInvoiceDetailVo> list = this.baseMapper.selInvoceInfoByBillNo(tailNo);
                String result = "-1";
                for(MerInvoiceDetailVo vo1 : list){
                    if(StringUtils.isNotEmpty(vo1.getInvPic())){
                        result = "1";
                        break;
                    }
                }
                return result;
            case 4:
                //完税证明
                QueryWrapper qw1 = Wrappers.query();
                  qw1.likeRight("bill_nos",tailNo+",");
//                qw.apply("FIND_IN_SET(bill_nos,#{billNo}) > 0",tailNo);
                MerTaxRecordsVo mtrv = this.merTaxRecordsMapper.selectVoOne(qw1);
                if(mtrv == null){
                    return null;
                }else{
                    return mtrv.getTaxFile();
                }
            case 5:
                //查看个人合同
                QueryWrapper qw = Wrappers.query();
                qw.eq("bus_type",busType);
                qw.eq("work_id",workId);
                qw.eq("mer_id",merId);
                qw.eq("syd_id",syId);
                qw.eq("sign_status",1);
                UserWorkerBusinessVo uwb = this.userWorkerBusinessMapper.selectVoOne(qw);
                if(uwb == null){
                    return null;
                }else{
                    return uwb.getSignFileUrl();
                }
        }
        return null;
    }

    @Override
    public void exportInv(String bo, HttpServletResponse response) throws Exception {

        List<MerInvoiceDetailVo> invList = this.baseMapper.selInvoceInfoByBillNo(bo);
        List<RemoteUserWorkerZipVo> zipList = new ArrayList();
        if(invList != null && !invList.isEmpty()){
            for(MerInvoiceDetailVo vo : invList){
                if(StringUtils.isNotEmpty(vo.getInvPic())){
                    RemoteUserWorkerZipVo zipVo = new RemoteUserWorkerZipVo();
                    zipVo.setInvNo(vo.getInvNo());
                    zipVo.setInvPic(vo.getInvPic());
                    zipList.add(zipVo);
                }
            }
        }

        if(zipList.isEmpty()){
            this.invalidationParamsException("未上传发票");
        }
        byte[] zipByte = this.remoteUserWokerService.downLoadInvZip(zipList);
        response.reset();
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.addHeader("Content-Length", "" + zipByte.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        FileUtils.setAttachmentResponseHeader(response,"发票信息.zip");
        IoUtil.write(response.getOutputStream(), false, zipByte);

    }


    /***
     * 生成完税证明数据
     * @param createDate
     */
    @Override
    @Transactional
    public void createSwRecords(Date createDate) {


        String month = DateUtil.format(createDate,"yyyy-MM");
        Date firstDay = DateUtil.beginOfMonth(createDate);
        Date lastDay = DateUtil.endOfMonth(createDate);

        Map paraMap = new HashMap();
        paraMap.put("startTime",firstDay);
        paraMap.put("endtime",lastDay);

        List<MerTaxRecords> recordsList = this.merTaxRecordsMapper.selectCreateTxRecords(paraMap);
        List<MerTaxRecordsDetail> detailList = this.merTaxRecordsDetailMapper.selectCreateTxRecordDetails(paraMap);

        for(MerTaxRecords records : recordsList){
            Long id = IdUtil.getSnowflakeNextId();
            records.setId(id);
            records.setMonth(month);
            records.setCreateTime(new Date());

            for(MerTaxRecordsDetail detail: detailList){
                 detail.setMonth(month);
                if(records.getBillIds().contains(detail.getBillId()+"")){
                    detail.setTrId(records.getId());
                }
            }
        }

        this.merTaxRecordsMapper.insertBatch(recordsList);
        this.merTaxRecordsDetailMapper.insertBatch(detailList);
    }

}
