package com.jkcredit.invoice.task;

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.customer.CustomerCarRec;
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.SelfCarDueQueryVo;
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.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
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();
        }
    }

    /**
     * @Scheduled(cron = "0 0 23 * * ?", zone = "Asia/Shanghai")
     * @throws Exception
     */
    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.查询所有的etc卡
         * 2.按照etc卡号取最近两天的发票
         */
        List<CustomerCarRec> lst = customerCarRecMapper.selectAllBindEtcNoGetInvoice();

        lst.stream().forEach(customerCarRec -> {
            try {
                SelfCarDueQueryVo selfCarDueQueryVo = new SelfCarDueQueryVo();
                selfCarDueQueryVo.setCompanyName(customerCarRec.getCompanyName());
                selfCarDueQueryVo.setCardId(customerCarRec.getEtcNum());
                selfCarDueQueryVo.setCustomername(customerCarRec.getCustomerName());
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String curr = dateFormat.format(new Date());
                String befor = DateUtil.getDateAfterDays(curr, -7);
                String after = DateUtil.getDateAfterDays(curr, +1);
                selfCarDueQueryVo.setStartTime(befor + " 00:00:00");
                selfCarDueQueryVo.setEndTime(after + "00:00:00");
                //查询交易id
                //根据etc卡查询所有的交易id
                SelfCarTrade param = new SelfCarTrade();
                param.setStatus(2);
                param.setCardId(customerCarRec.getEtcNum());
                List<SelfCarTrade> selfCarTrades = sellCarTradeMapper.selectByCardIdByStatus(param);
                selfCarTradeService.updateTrades(selfCarTrades);
                selfCarService.getSelfCarInvoicesByTime(selfCarDueQueryVo, null);
            } catch (Exception e) {
                e.printStackTrace();
                log.info(customerCarRec.getEtcNum());
            }
        });
      /*  try {
            List<SelfCarAppl> selfCarAppls = selfCarApplMapper.selectAllNoRec();
            selfCarAppls.forEach(selfCarAppl -> {
                selfCarService.getSelfCarInvoicesByApplyIds(selfCarAppl);
            });
        }catch (Exception e){
            e.printStackTrace();
        }*/
    }
}
