package com.jkcredit.invoice.controller.business;
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.mapper.customer.CustomerRecMapper;
import com.jkcredit.invoice.mapper.waybill.SellCarTradeMapper;
import com.jkcredit.invoice.model.entity.calculate.SelfCarCalculateInfor;
import com.jkcredit.invoice.model.entity.customer.CustomerCarRec;
import com.jkcredit.invoice.model.entity.customer.CustomerRec;
import com.jkcredit.invoice.model.entity.invoice.SelfCarInvoice;
import com.jkcredit.invoice.model.entity.waybill.SelfCarTrade;
import com.jkcredit.invoice.service.calculateinfor.SelfCarCalculateInfoService;
import com.jkcredit.invoice.service.customer.CustomerService;
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"})
/**
* @Description 自有车操作
* @Author  mashengyi
* @Date   2022/2/8 18:18
* @Param
* @Return
* @Exception
*
*/
public class SelfCarController {
    @Autowired
    SelfCarServiceL selfCarServiceL;
    @Autowired
    SelfCarService selfCarService;
    @Autowired
    SelfCarServiceL selfCarServicel;
    @Autowired
    SelfCarTradeService selfCarTradeService;
    @Autowired
    SelfCarInvoiceService selfCarInvoiceService;
    @Autowired
    SelfCarCalculateInfoService selfCarCalculateInfoService;
    @Autowired
    SellCarTradeMapper sellCarTradeMapper;
    @Autowired
    CustomerService customerService;
    /**
     * 解绑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 page    参数集
     * @return 交易信息
     */
    @PostMapping("/findTradesUpper")
    @ApiOperation(value="分页查询自有车交易信息", notes="分页查询自有车交易信息")
    @LoginRequired
    public RespR findTradesUpper(Page page, SelfCarTrade selfCarTrade) {
        try {
            setTimeDue(selfCarTrade);
            if(StringUtils.isEmpty(selfCarTrade.getCompanyName())){
                return new RespR(false,"需要输入公司名称");
            }
            if(StringUtils.isEmpty(selfCarTrade.getCardId())){
                return new RespR(false,"需要输入etc卡号");
            }
            if(StringUtils.isEmpty(selfCarTrade.getExTimeBegin())){
                return new RespR(false,"需要交易开始时间");
            }
            if(StringUtils.isEmpty(selfCarTrade.getExTimeEnd())){
                return new RespR(false,"需要输入交易结束时间");
            }
            //先更新查询信息
            TradeRequestVo tradeRequestVo  = new TradeRequestVo();
            tradeRequestVo.setCustomerName(selfCarTrade.getCustomId());
            tradeRequestVo.setCompanyName(selfCarTrade.getCompanyName());
            tradeRequestVo.setStartTime(selfCarTrade.getExTimeBegin());
            tradeRequestVo.setEndTime(selfCarTrade.getExTimeEnd());
            tradeRequestVo.setEtcId(selfCarTrade.getCardId());
            tradeRequestVo.setTradeStatus(selfCarTrade.getStatus());
            tradeRequestVo.setInterType(1);//0 接口

            if(tradeRequestVo.getTradeStatus() ==null){
                tradeRequestVo.setTradeStatus(1);
                selfCarServiceL.getTradeList(tradeRequestVo);
                tradeRequestVo.setTradeStatus(2);
                selfCarServiceL.getTradeList(tradeRequestVo);
                tradeRequestVo.setTradeStatus(3);
                selfCarServiceL.getTradeList(tradeRequestVo);
            }else{
                selfCarServiceL.getTradeList(tradeRequestVo);
            }
            RespR respR = new RespR(selfCarTradeService.findByPageAndTrade(page, selfCarTrade));
            return respR;
        }catch (Exception e){
            e.printStackTrace();
            return new RespR(false,e.getMessage());
        }
    }

    /**
     * 分页查询自有车交易信息
     *
     * @param  selfCarTradesStr
     * @return 交易信息
     */
    @PostMapping("/updateTrades")
    @ApiOperation(value="更新交易id状态", notes="更新交易id状态")
    @LoginRequired
    public void updateTrades( String selfCarTradesStr,String companyName) {
        try {

            List<SelfCarTrade>  selfCarTrades = JSON.parseArray(selfCarTradesStr,SelfCarTrade.class);
            if(selfCarTrades== null || selfCarTrades.size()==0){
                selfCarTrades = sellCarTradeMapper.selectByStatus("2",companyName);

            }
            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]);
                }
            }
        }
        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()+"#");
            }
        }
        if(StringUtils.isEmpty(stringBuffer.toString())){
            return new RespR(true);
        }else{
            return new RespR(false,stringBuffer.toString());
        }

    }
    @Autowired
    CustomerRecMapper customerRecMapper;
    /**
     * 查询已经开票信息
     *
     * @param
     * @return
     */
    @PostMapping("/findSelfcarInvoiceByTime")
    @ApiOperation(value="通过时间，车牌号查询开票信息", notes="通过时间，车牌号查询开票信息")
    @LoginRequired
    public RespR findSelfcarInvoiceByTime(@RequestBody  SelfcarInvoiceByTimeVo selfcarInvoiceByTimeVo) {
        try {

            if(!customerService.checkMoneyEnough(selfcarInvoiceByTimeVo.getCustomerName())){
                return new RespR(false,"余额不足");
            }
            //通过车牌号查询所有的Etc卡号
            List<CustomerCarRec> customerCarRecs = selfCarService.getEtcsByCarNum(selfcarInvoiceByTimeVo.getCarNum());
            if(customerCarRecs == null || customerCarRecs.size()<=0){
                return new RespR(false,"请输入有绑定ETC卡号的车牌");
            }
            CustomerRec customerRec = new CustomerRec();
            customerRec.setCustomerName(selfcarInvoiceByTimeVo.getCustomerName());
            customerRec.setCompanyName(selfcarInvoiceByTimeVo.getCompanyName());
            CustomerRec customerRec1 = customerRecMapper.selectByCustomerNameAndCompany(customerRec);
            if(customerRec1 == null || customerRec1.getRecStatus().intValue() !=1 ){
                return new RespR(false,"客户未备案");
            }
            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,customerRec1);
                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);
            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);
            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());
        }
    }


}
