package com.jkcredit.invoice.controller.localBussiness;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.com.taiji.sdk.model.comm.protocol.tts.invoice.server.B2BInvoiceListModel;
import cn.com.taiji.sdk.model.comm.protocol.tts.trade.service.CardTradeModel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jkcredit.invoice.annotation.LoginRequired;
import com.jkcredit.invoice.model.entity.Calculate.SelfCarCalculateInfor;
import com.jkcredit.invoice.model.entity.customer.CustomerCarRec;
import com.jkcredit.invoice.model.entity.invoice.BillInvoice;
import com.jkcredit.invoice.model.entity.invoice.SelfCarInvoice;
import com.jkcredit.invoice.model.entity.waybill.NoCarWayBill;
import com.jkcredit.invoice.model.entity.waybill.SelfCarTrade;
import com.jkcredit.invoice.service.CalculateInfor.SelfCarCalculateInfoService;
import com.jkcredit.invoice.service.lowerService.SelfCarServiceL;
import com.jkcredit.invoice.service.lowerService.vo.*;
import com.jkcredit.invoice.service.selfCar.SelfCarInvoiceService;
import com.jkcredit.invoice.service.selfCar.SelfCarService;
import com.jkcredit.invoice.service.selfCar.SelfCarTradeService;
import com.jkcredit.invoice.util.RespR;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "自有车操作")
@RestController
@RequestMapping(value = {"/selfCar"})
public class SelfCarController {
    @Autowired
    SelfCarService selfCarService;
    @Autowired
    SelfCarServiceL selfCarServicel;
    @Autowired
    SelfCarTradeService selfCarTradeService;
    @Autowired
    SelfCarInvoiceService selfCarInvoiceService;
    @Autowired
    SelfCarCalculateInfoService selfCarCalculateInfoService;
    /**
     * 解绑etc卡
     * @param etcNum    参数集
     * @return 用户集合
     */
    @PostMapping("/selfCarUnBind")
    @ApiOperation(value="解绑etc卡", notes="解绑etc卡")
    @LoginRequired
    public RespR selfCarUnBind(String etcNum) {
        try {
            RespR respR = selfCarService.selfCarUnBind(etcNum);
            return respR;
        }catch (Exception e){
            e.printStackTrace();
            return new RespR(false,e.getMessage());
        }
    }

    /**
     * 分页查询自有车交易信息
     *
     * @param page    参数集
     * @return 交易信息
     */
    @PostMapping("/findTrades")
    @ApiOperation(value="分页查询自有车交易信息", notes="分页查询自有车交易信息")
    @LoginRequired
    public RespR findTrades(Page page, SelfCarTrade selfCarTrade) {
        try {
            setTimeDue(selfCarTrade);
            RespR respR = new RespR(selfCarTradeService.findByPageAndTrade(page, selfCarTrade));
            return respR;
        }catch (Exception e){
            e.printStackTrace();
            return new RespR(false,e.getMessage());
        }
    }
    /**
     * 分页查询自有车交易信息
     *
     * @param selfCarTrades    参数集
     * @return 交易信息
     */
    @PostMapping("/updateTrades")
    @ApiOperation(value="更新交易id状态", notes="更新交易id状态")
    @LoginRequired
    public void updateTrades( String selfCarTradesStr) {
        try {
            List<SelfCarTrade>  selfCarTrades = JSON.parseArray(selfCarTradesStr,SelfCarTrade.class);
            selfCarTradeService.updateTrades(selfCarTrades);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void setTimeDue(SelfCarTrade selfCarTrade){
        if(!StringUtils.isEmpty(selfCarTrade.getAclTimeBegin()) && !"null".equals(selfCarTrade.getAclTimeBegin())){
            String [] res = selfCarTrade.getAclTimeBegin().split(",");
            selfCarTrade.setAclTimeBegin(res[0]);
            selfCarTrade.setAclTimeEnd(res[1].replace("00:00:00","23:59:59"));
        }else{
            selfCarTrade.setAclTimeBegin(null);
        }
        if(!StringUtils.isEmpty(selfCarTrade.getExTimeBegin()) && !"null".equals(selfCarTrade.getExTimeBegin())){
            String [] res = selfCarTrade.getExTimeBegin().split(",");
            selfCarTrade.setExTimeBegin(res[0]);
            selfCarTrade.setExTimeEnd(res[1].replace("00:00:00","23:59:59"));
        }else{
            selfCarTrade.setExTimeBegin(null);
        }
    }
    /**
     * 分页查询所有发票信息
     *
     * @param page    参数集
     * @return 交易信息
     */
    @PostMapping("/findSelfCarInvoices")
    @ApiOperation(value="分页查询自有车发票信息", notes="分页查询自有车发票信息")
    @LoginRequired
    public RespR findSelfCarInvoices(Page page, SelfCarInvoice selfCarInvoice) {
        try {
            if(!StringUtils.isEmpty(selfCarInvoice.getInvoiceMakeTime()) && !"null".equals(selfCarInvoice.getInvoiceMakeTime())){
                String [] res =selfCarInvoice.getInvoiceMakeTime().split(",");
                selfCarInvoice.setInvoiceMakeStart(res[0]);
                selfCarInvoice.setInvoiceMakeEnd(res[1].replace("00:00:00","23:59:59"));
            }
            RespR respR = new RespR(selfCarInvoiceService.findByPageAndInvoice(page, selfCarInvoice));
            return respR;
        }catch (Exception e){
            e.printStackTrace();
            return new RespR(false,e.getMessage());
        }
    }

    /**
     * 分页查询自有车计费信息
     *
     * @param page    参数集
     * @return 用户集合
     */
    @PostMapping("/findSelfcarCalculateInfo")
    @ApiOperation(value="分页查询自有车计费信息", notes="分页查询自有车计费信息")
    @LoginRequired
    public RespR findSelfcarCalculateInfo(Page page, SelfCarCalculateInfor carCalculateInfor) {
        try {
            if(!StringUtils.isEmpty(carCalculateInfor.getCalTime()) && !"null".equals(carCalculateInfor.getCalTime())){
                String [] res =carCalculateInfor.getCalTime().split(",");
                carCalculateInfor.setCalTimeStart(res[0]);
                carCalculateInfor.setCalTimeEnd(res[1]);
            }
            RespR respR = new RespR(selfCarCalculateInfoService.findByPageAndCalculateInfor(page, carCalculateInfor));
            return respR;
        }catch (Exception e){
            e.printStackTrace();
            return new RespR(false,e.getMessage());
        }
    }
    /**
     * 分页查询自有车计费信息
     *
     * @param carCalculateInfor
     * @return 用户集合
     */
    @PostMapping("/findSelfcarCalculateInfoSta")
    @ApiOperation(value="自有车计费统计信息", notes="自有车计费统计信息")
    @LoginRequired
    public RespR findSelfcarCalculateInfoSta(SelfCarCalculateInfor carCalculateInfor) {
        try {
            if(!StringUtils.isEmpty(carCalculateInfor.getCalTime()) && !"null".equals(carCalculateInfor.getCalTime())){
                String [] res =carCalculateInfor.getCalTime().split(",");
                carCalculateInfor.setCalTimeStart(res[0]);
                carCalculateInfor.setCalTimeEnd(res[1]);
            }
            RespR respR = new RespR(selfCarCalculateInfoService.findSelfcarCalculateInfoSta(carCalculateInfor));
            return respR;
        }catch (Exception e){
            e.printStackTrace();
            return new RespR(false,e.getMessage());
        }
    }
    /**
     * @param tradeRequestCarNumVo
     * @return
     */
    @PostMapping("/getTradeList")
    @ApiOperation(value="获取需要开票的交易Id列表", notes="获取需要开票的交易Id列表")
    @LoginRequired
    public RespR getTradeList(@RequestBody TradeRequestCarNumVo tradeRequestCarNumVo){
        //通过车牌号查询所有的Etc卡号
        List<CustomerCarRec> customerCarRecs = selfCarService.getEtcsByCarNum(tradeRequestCarNumVo.getCarNum());
        if(customerCarRecs == null || customerCarRecs.size()<=0){
            return new RespR(false,"请输入有绑定ETC卡号的车牌");
        }
        //合并展示
        List<CardTradeModel> cardTradeModels = new ArrayList<>();
        customerCarRecs.forEach(customerCarRec -> {
            TradeRequestVo tradeRequestVo = new TradeRequestVo();
            tradeRequestVo.setCompanyName(tradeRequestCarNumVo.getCompanyName());
            tradeRequestVo.setCustomerName(tradeRequestCarNumVo.getCustomerName());
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            tradeRequestVo.setStartTime(format.format(new Date(Long.parseLong(tradeRequestCarNumVo.getStartTime()))));
            tradeRequestVo.setEndTime(format.format(new Date(Long.parseLong(tradeRequestCarNumVo.getEndTime()))));
            tradeRequestVo.setTradeStatus(1);
            tradeRequestVo.setEtcId(customerCarRec.getEtcNum());
            RespR<List<CardTradeModel>> respRbefore = selfCarServicel.getTradeList(tradeRequestVo);
            if(respRbefore.getCode() == 0){
                cardTradeModels.addAll(respRbefore.getData());
            }
        });
        return new RespR(cardTradeModels);
    }
    /**
     * @param tradeRequestCarNumVo
     * @return
     */
    @PostMapping("/applTradeList")
    @ApiOperation(value="根据车牌号进行开票操作", notes="根据车牌号进行开票操作")
    @LoginRequired
    public RespR applTradeList(@RequestBody TradeRequestCarNumVo tradeRequestCarNumVo){
        String [] cardAndTrades = tradeRequestCarNumVo.getCarIdStr().split(",");
        Map<String,InvoiceApplVo> map = new HashMap<>();
        for(int i = 0;i<cardAndTrades.length;i++){
            if(!StringUtils.isEmpty(cardAndTrades[i])){
                String [] cardAndTrade = cardAndTrades[i].split("#");
                InvoiceApplVo invoiceApplVo = map.get(cardAndTrade[0]);
                if(invoiceApplVo == null){
                    invoiceApplVo.setCompanyName(tradeRequestCarNumVo.getCompanyName());
                    invoiceApplVo.setCustomerName(tradeRequestCarNumVo.getCustomerName());
                    invoiceApplVo.setCardId(cardAndTrade[0]);
                    invoiceApplVo.setTradeIds(new ArrayList<String>());
                    invoiceApplVo.getTradeIds().add(cardAndTrade[1]);
                    map.put(cardAndTrade[0],invoiceApplVo);
                }else{
                    invoiceApplVo.getTradeIds().add(cardAndTrade[1]);
                }
            }
        }
        //通过车牌号查询所有的Etc卡号
        /*List<CustomerCarRec> customerCarRecs = selfCarService.getEtcsByCarNum(tradeRequestCarNumVo.getCarNum());
        if(customerCarRecs == null || customerCarRecs.size()<=0){
            return new RespR(false,"请输入有绑定ETC卡号的车牌");
        }*/
        StringBuffer stringBuffer = new StringBuffer();
        for(Map.Entry<String,InvoiceApplVo> elm:map.entrySet()){
            InvoiceApplVo invoiceApplVo = elm.getValue();
            RespR respR = selfCarServicel.applInvoice(invoiceApplVo);
            if(respR.getCode() == 1){
                stringBuffer.append(invoiceApplVo.getCardId()+"开票申请失败原因:"+respR.getMsg()+"#");
            }
        }
/*        customerCarRecs.forEach(customerCarRec -> {
            TradeRequestVo tradeRequestVo = new TradeRequestVo();
            tradeRequestVo.setCompanyName(tradeRequestCarNumVo.getCompanyName());
            tradeRequestVo.setCustomerName(tradeRequestCarNumVo.getCustomerName());
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            tradeRequestVo.setStartTime(format.format(new Date(Long.parseLong(tradeRequestCarNumVo.getStartTime()))));
            tradeRequestVo.setEndTime(format.format(new Date(Long.parseLong(tradeRequestCarNumVo.getEndTime()))));
            tradeRequestVo.setTradeStatus(1);
            tradeRequestVo.setEtcId(customerCarRec.getEtcNum());
            RespR<List<CardTradeModel>> respRbefore = selfCarServicel.getTradeList(tradeRequestVo);
            if(respRbefore.getCode() == 0){
                if(respRbefore.getData()!=null && respRbefore.getData().size()>0){
                    //进行开票申请
                    InvoiceApplVo invoiceApplVo = new InvoiceApplVo();
                    invoiceApplVo.setCompanyName(tradeRequestCarNumVo.getCompanyName());
                    invoiceApplVo.setCustomerName(tradeRequestCarNumVo.getCustomerName());
                    invoiceApplVo.setCardId(customerCarRec.getEtcNum());
                    invoiceApplVo.setTradeIds(new ArrayList<String>());
                    respRbefore.getData().forEach(cardTradeModel -> {
                        invoiceApplVo.getTradeIds().add(cardTradeModel.getTradeId());
                    });
                    RespR respR = selfCarServicel.applInvoice(invoiceApplVo);
                    if(respR.getCode() == 1){
                        stringBuffer.append(customerCarRec.getEtcNum()+"开票申请失败原因:"+respRbefore.getMsg()+"#");
                    }

                }
            }else {
                stringBuffer.append(customerCarRec.getEtcNum()+"开票申请失败原因:"+respRbefore.getMsg()+"#");
            }
        });*/
        if(StringUtils.isEmpty(stringBuffer.toString())){
            return new RespR(true);
        }else{
            return new RespR(false,stringBuffer.toString());
        }

    }
    /**
     * 查询已经开票信息
     *
     * @param
     * @return
     */
    @PostMapping("/findSelfcarInvoiceByTime")
    @ApiOperation(value="通过时间，车牌号查询开票信息", notes="通过时间，车牌号查询开票信息")
    @LoginRequired
    public RespR findSelfcarInvoiceByTime(@RequestBody  SelfcarInvoiceByTimeVo selfcarInvoiceByTimeVo) {
        try {
            //通过车牌号查询所有的Etc卡号
            List<CustomerCarRec> customerCarRecs = selfCarService.getEtcsByCarNum(selfcarInvoiceByTimeVo.getCarNum());
            if(customerCarRecs == null || customerCarRecs.size()<=0){
                return new RespR(false,"请输入有绑定ETC卡号的车牌");
            }
            List<B2BInvoiceListModel>  allSelfInvocies = new ArrayList<>();
            customerCarRecs.forEach(customerCarRec -> {
                SelfCarDueQueryVo selfCarDueQueryVo = new SelfCarDueQueryVo();
                selfCarDueQueryVo.setCustomername(selfcarInvoiceByTimeVo.getCustomerName());
                selfCarDueQueryVo.setCompanyName(selfcarInvoiceByTimeVo.getCompanyName());
                selfCarDueQueryVo.setStartTime(selfcarInvoiceByTimeVo.getStartTime());
                selfCarDueQueryVo.setEndTime(selfcarInvoiceByTimeVo.getEndTime());
                selfCarDueQueryVo.setCardId(customerCarRec.getEtcNum());
                RespR<List<B2BInvoiceListModel>> respR = selfCarServicel.getSelfCarInvoicesByTime(selfCarDueQueryVo);
                if(respR.getCode() == 0){
                    allSelfInvocies.addAll(respR.getData());
                }
            });
           return new RespR(allSelfInvocies);
        }catch (Exception e){
            e.printStackTrace();
            return new RespR(false,e.getMessage());
        }
    }



    /**
     * 批量查询自有车交易信息
     *
     * @param file    参数集
     * @return
     */
    @PostMapping("/batchImportSelfcarTrades")
    @ApiOperation(value="批量查询自有车交易信息", notes="批量查询自有车交易信息")
    @LoginRequired
    public RespR batchImportSelfcarTrades(@RequestParam("file") MultipartFile file) {
        try {
            ImportParams params = new ImportParams();
            params.setTitleRows(1);
            params.setHeadRows(1);
            // params.setKeyIndex(2);
            List<SelfCarTrade> list = ExcelImportUtil.importExcel(file.getInputStream(), SelfCarTrade.class,params) ;
            RespR respR = selfCarTradeService.batchImportSelfcarTrades(list);
            return respR;
        }catch (Exception e){
            e.printStackTrace();
            return new RespR(false,e.getMessage());
        }
    }



    /**
     * 批量查询自有车发票信息
     *
     * @param file    参数集
     * @return
     */
    @PostMapping("/batchImportSelfcarInvoices")
    @ApiOperation(value="批量查询自有车发票信息", notes="批量查询自有车发票信息")
    @LoginRequired
    public RespR batchImportSelfcarInvoices(@RequestParam("file") MultipartFile file) {
        try {
            ImportParams params = new ImportParams();
            params.setTitleRows(1);
            params.setHeadRows(1);
            // params.setKeyIndex(2);
            List<SelfCarInvoice> list = ExcelImportUtil.importExcel(file.getInputStream(), SelfCarInvoice.class,params) ;
            RespR respR = selfCarInvoiceService.findImportSelfcarInvoices(list);
            return respR;
        }catch (Exception e){
            e.printStackTrace();
            return new RespR(false,e.getMessage());
        }
    }


}
