package com.jkcredit.invoice.task;

import cn.com.taiji.sdk.model.comm.protocol.tts.trade.service.TradeApplyQueryRequest;
import cn.com.taiji.sdk.model.comm.protocol.tts.trade.service.TradeApplyQueryResponse;
import com.jkcredit.invoice.mapper.binvoce.SelfCarApplMapper;
import com.jkcredit.invoice.mapper.customer.CustomerCarRecMapper;
import com.jkcredit.invoice.mapper.waybill.NoCarWaybillMapper;
import com.jkcredit.invoice.mapper.waybill.SellCarTradeMapper;
import com.jkcredit.invoice.model.entity.waybill.NoCarWayBill;
import com.jkcredit.invoice.model.entity.waybill.SelfCarTrade;
import com.jkcredit.invoice.service.lowerservice.NoCarService;
import com.jkcredit.invoice.service.lowerservice.SelfCarCustService;
import com.jkcredit.invoice.service.lowerservice.vo.ApplQueryInvVo;
import com.jkcredit.invoice.service.manager.ParamService;
import com.jkcredit.invoice.service.selfcar.SelfCarTradeService;
import com.jkcredit.invoice.service.thead.ThreadPoolFactory;
import com.jkcredit.invoice.service.upservice.SelfCarInterface;
import com.jkcredit.invoice.util.DateUtil;
import com.jkcredit.invoice.util.RespR;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;

/**
 * @description:
 * @author: sunzhaoning
 * @create: 2019-06-27 16:36
 * @version: V1.0
 **/
@Component
@Slf4j
public class ScheduledBillTask {
    
    ExecutorService executorService = ThreadPoolFactory.getThreadPool("qupaioxiancheng",20,50);
    @Autowired
    NoCarWaybillMapper noCarWaybillMapper;

    @Autowired
    SelfCarApplMapper selfCarApplMapper;

    @Autowired
    SellCarTradeMapper sellCarTradeMapper;

    @Autowired
    NoCarService noCarService;

    @Autowired
    SelfCarCustService selfCarService;

    @Autowired
    CustomerCarRecMapper customerCarRecMapper;

    @Autowired
    ParamService paramService;
    @Autowired
    SelfCarTradeService selfCarTradeService;

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15);
        int total = list.size();
        int pageSize = 3;
        //分四个线程去取
        for (int page = 0; page <= total / pageSize; page++) {
            List<Integer> noCarWayBillsMdEndi = list.subList(page * pageSize, (page + 1) * pageSize > total ? total : (page + 1) * pageSize);
            System.out.print(noCarWayBillsMdEndi.toString() + "\n");
        }

    }

    /**
     * 实时运单开票（每三小时开始）
     */
    @Scheduled(cron = "0 0 0/3 * * ?", zone = "Asia/Shanghai")
    public void updateNocarBillInfo() throws Exception {
        InetAddress addr = InetAddress.getLocalHost();
        String ip = paramService.getParamsByParamName("CURR_SELF_IP").getParamValue();

        log.info("CURR_SELF_IP" + ip + ",address:" + addr);
        if (!addr.getHostAddress().equals(ip)) {
            log.info("！bengjiqikaipao");
            return;
        } else {
            log.info("bengjiqikaipao");
        }
        try {
            delGetInvoce(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void delGetInvoce(Integer historyFlag) {
        NoCarWayBill carWayBill = new NoCarWayBill();
        carWayBill.setHisFlag(historyFlag);
        carWayBill.setBillwayStatus(2);
        List<NoCarWayBill> noCarWayBillsMdEnd = noCarWaybillMapper.selectByHisFlagAndBillStatus(carWayBill);
        if (noCarWayBillsMdEnd != null && noCarWayBillsMdEnd.size() > 0) {
            int total = noCarWayBillsMdEnd.size();
            log.info("实时取票数量" + total);
            int pageSize = 5000;
            //线程去取
            for (int page = 0; page <= total / pageSize; page++) {
                List<NoCarWayBill> noCarWayBillsMdEndi = noCarWayBillsMdEnd.subList(page * pageSize, (page + 1) * pageSize > total ? total : (page + 1) * pageSize);
                if (noCarWayBillsMdEndi == null || noCarWayBillsMdEndi.size() == 0) {
                    continue;
                }
                executorService.execute(() -> {
                    log.info("qupiaoshumu" + noCarWayBillsMdEndi.size());
                    for (NoCarWayBill noCarWayBill : noCarWayBillsMdEndi) {
                        log.info("实时取票运单" + noCarWayBill.getBillNum());
                        try {
                            noCarService.getInvoiceByWayBillNumReal(noCarWayBill, false);
                        } catch (Exception e) {
                            log.debug("取票失败" + noCarWayBill.getBillNum() + e.getMessage());
                        }
                    }
                    log.info("qupiaoshumujiesu" + noCarWayBillsMdEndi.size());
                });
            }

            log.info("实时取票数量" + noCarWayBillsMdEnd.size() + "jiesula");
        }
    }

    /**
     * 历史运单开票（每天整点点开始） todo 改成动态设置
     */
    @Scheduled(cron = "0 0 0/1 * * ?", zone = "Asia/Shanghai")
    public void updateHistoryNocarBillInfo() throws Exception {
        InetAddress addr = InetAddress.getLocalHost();
        String ip = paramService.getParamsByParamName("HISTORY_IP").getParamValue();

        log.info("HISTORY_IP" + ip + ",address:" + addr);
        if (!addr.getHostAddress().equals(ip)) {
            log.info("！bengjiqikaipao");
            return;
        } else {
            log.info("bengjiqikaipao");
        }
        try {
            delGetInvoce(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Autowired
    com.jkcredit.invoice.mapper.waybill.WayBillFileMapper wayBillFileMapper;
    @Scheduled(cron = "0 0 1 * * ?", zone = "Asia/Shanghai")
    public void deleteFile()throws Exception{
        InetAddress addr = InetAddress.getLocalHost();
        String ip = paramService.getParamsByParamName("CURR_SELF_IP").getParamValue();

        log.info("CURR_SELF_IP" + ip + ",address:" + addr);
        if (!addr.getHostAddress().equals(ip)) {
            log.info("！shanchufile");
            return;
        } else {
            log.info("shanchufile");
        }
        String yesdate = DateUtil.getDateAfterDayTime(DateUtil.getCurrentDateStr(),-3);
        wayBillFileMapper.deleteFileByTime(yesdate);
    }
    @Autowired
    SelfCarInterface selfCarInterface;


    /*@Scheduled(cron = "0 40 22 4 * ?", zone = "Asia/Shanghai")
    public void  test()throws Exception{
        getSefCarInvoice();
    }*/
    /**
     * @Scheduled(cron = "0 0 23 * * ?", zone = "Asia/Shanghai")
     * @throws Exception
     */
    @Scheduled(cron = "0 58 23 * * ?", zone = "Asia/Shanghai")
    public void getSefCarInvoice() throws Exception {
        InetAddress addr = InetAddress.getLocalHost();
        String ip = paramService.getParamsByParamName("CURR_SELF_IP").getParamValue();

        log.info("CURR_SELF_IP" + ip + ",address:" + addr);
        if (!addr.getHostAddress().equals(ip)) {
            log.info("！bengjiqikaipao");
            return;
        } else {
            log.info("bengjiqikaipao");
        }
        /**
         * 1.交易id中所有待开票的etc卡号，和当天的开票完成的交易id
         * 更新交易状态
         */
        List<SelfCarTrade> lst = sellCarTradeMapper.selectNeedGetTrades();
        log.info("getSefCarInvoice处理条数{}",lst.size());
        /**
         * 开始取票 取票可以通过 申请id 进行取票
         */
        Map<String,ApplQueryInvVo> map = new HashMap<>();
        lst.stream().forEach(selfCarTrade -> {
            ApplQueryInvVo applQueryInvVo = new ApplQueryInvVo();
            applQueryInvVo.setCompanyNum(selfCarTrade.getCompanyNum());
            applQueryInvVo.setEtcNum(selfCarTrade.getCardId());
            applQueryInvVo.setCompanyName(selfCarTrade.getCompanyName());
            applQueryInvVo.setCustomerName(selfCarTrade.getCustomId());
            applQueryInvVo.setCompanyReferencenum(selfCarTrade.getCompanyReferencenum());
            if(StringUtils.isEmpty(selfCarTrade.getApplId())){
                //1.获取到交易id
                TradeApplyQueryRequest tradeApplyQueryRequest = new TradeApplyQueryRequest();
                tradeApplyQueryRequest.setCompanyNum(selfCarTrade.getCompanyNum());
                tradeApplyQueryRequest.setCardId(selfCarTrade.getCardId());
                tradeApplyQueryRequest.setTradeId(selfCarTrade.getTradeId());
                RespR<TradeApplyQueryResponse> respR = selfCarInterface.queryApplyQueryByTradeId(tradeApplyQueryRequest);
                if(respR.getCode()!=1){
                    selfCarTrade.setApplId(respR.getData().getApplyId());
                    selfCarTrade.setAclTime(DateUtil.getCurrentDateStr());
                }
            }
            applQueryInvVo.setApplId(selfCarTrade.getApplId());
            map.put(selfCarTrade.getApplId(),applQueryInvVo);
        });
        for(Map.Entry<String,ApplQueryInvVo> entry:map.entrySet()){
            ApplQueryInvVo applQueryInvVo  = entry.getValue();
            try {
                selfCarService.getSelfCarInvoicesByApplyIdsDb(applQueryInvVo);
            }catch (Exception e){
                log.error("self-poll-err:{}",e);
                log.error("{}处理取票失败，失败原因{}",applQueryInvVo.getEtcNum()+"#"+applQueryInvVo.getApplId(),e.getMessage());
                try {
                    selfCarService.getSelfCarInvoicesByApplyIdsDb(applQueryInvVo);
                }catch (Exception e1){
                    log.error("{}处理取票失败1，失败原因{}",applQueryInvVo.getEtcNum()+"#"+applQueryInvVo.getApplId(),e.getMessage());
                    log.error("self-poll-err1:{}",e);
                }
            }

        }
        selfCarTradeService.updateTradesDb(lst);
        log.info("getSefCarInvoice处理完成");
    }
}