package com.tax.file.service.impl;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.tax.file.mapper.FinCuspayDetailMapper;
import com.tax.file.mapper.FinCuspayMapper;
import com.tax.file.mapper.FinInvoiceDetailMapper;
import com.tax.file.mapper.FinInvoiceMapper;
import com.tax.file.mapper.FinOldcarMapper;
import com.tax.file.mapper.FinVehicleMapper;
import com.tax.file.model.FinCuspay;
import com.tax.file.model.FinCuspayDetail;
import com.tax.file.model.FinInvoice;
import com.tax.file.model.FinInvoiceDetail;
import com.tax.file.model.FinInvoiceExample;
import com.tax.file.model.FinOldcar;
import com.tax.file.model.FinVehicle;
import com.tax.file.service.api.FinInvoiceService;
import com.yxcheng.token.common.service.AbstractService;
import com.yxcheng.token.utils.MyBeanUtils;
import com.yxcheng.token.utils.StringUtil;

import lombok.extern.slf4j.Slf4j;


@Transactional(isolation=Isolation.READ_COMMITTED)//为了解决先删除后插入的锁并发问题
@Component
@ComponentScan(basePackages = {"com.tax.file.dao", "com.tax.file.integration"})
@Slf4j
public class FinInvoiceServiceImpl extends AbstractService<FinInvoiceMapper,FinInvoiceExample,FinInvoice> implements FinInvoiceService {

	
    @Autowired
    FinInvoiceMapper finInvoiceMapper;
    @Autowired
    FinVehicleMapper finVehicleMapper;
    @Autowired
    FinOldcarMapper finOldcarMapper;
    @Autowired
    FinInvoiceDetailMapper finInvoiceDetailMapper;
    
    @Autowired
    FinCuspayMapper finCuspayMapper;
    @Autowired
    FinCuspayDetailMapper finCuspayDetailMapper;
	
	 /**
   	 * 读取单个excel入库
   	 * 		1.根据代码号码查询发票数据，如果存在则需要更新，否则需要插入，分为两个list，一个插入list，一个更新list
   	 * 		2.对于明细，根据上面代码号码查询的发票是否存在的结果，分为两个list，一个删除list，一个插入list
   	 *
   	 * @param map
   	 * @param invType 发票类型
   	 * @return
   	 */
	@Override
	public void insertInvoiceBatch(Map<String,List> map,String invType) throws Exception{
		List<FinInvoice> invoiceList = map.get("invoiceList");
		List<FinVehicle> vehicleList = map.get("vehicleList");
		List<FinOldcar> oldCarList = map.get("oldCarList");
		List<FinCuspay> cuspayList = map.get("cuspayList");
        List<FinInvoiceDetail> invoiceDetailList = map.get("invoiceDetailList");
        List<FinCuspayDetail> cuspayDetailList = map.get("cuspayDetailList");
        
       
        if("03".equals(invType)){
        	dealVehicle(vehicleList); //处理机动车
        }else if("15".equals(invType)){
        	dealOldcar(oldCarList);//处理二手车发票
        }else if("17".equals(invType)){//处理海关缴款书发票
        	List<String> detailDeleteList = dealCuspay(cuspayList);
        	//处理明细
            //dealCuspayDetail(cuspayDetailList,detailDeleteList);
        }else{//处理其他发票，上面的发票都是单独建表存储，所以需要单独处理
        	List<String> detailDeleteList = dealInvoice(invoiceList);
        	//处理明细
           // dealInvoiceDetail(invoiceDetailList,detailDeleteList);
        }
	}
	/**
   	 * 读取单个excel入库,处理机动车发票
   	 *
   	 * @param vehicleList
   	 * @return
   	 */
	public void dealVehicle(List<FinVehicle> vehicleList) throws Exception{
		if(vehicleList == null || vehicleList.size() == 0){
    		return;
    	}
    	
    	List<FinVehicle> vehicleInsertList = new ArrayList<FinVehicle>();
    	List<FinVehicle> vehicleUpdateList = new ArrayList<FinVehicle>();
    	Iterator<FinVehicle> iter = vehicleList.iterator();
    	while(iter.hasNext()){
    		FinVehicle vehicle = iter.next();
    		
    		vehicle.setInvSum((vehicle.getInvCost() == null?0.0:vehicle.getInvCost()) + (vehicle.getInvVat()==null?0.0:vehicle.getInvVat()));
    		FinVehicle vehicleLib = finVehicleMapper.queryByInvkindAndInvnum(vehicle);
    		if(vehicleLib == null){//未查到
    			vehicleInsertList.add(vehicle);
    		}else{
    			MyBeanUtils.copyBeanNotNull2Bean(vehicle, vehicleLib);
    			vehicleLib.setUpdateBy("systemauto");
    			vehicleLib.setUpdateDate(new Date());
    			vehicleUpdateList.add(vehicleLib);
    		}
    	}
    	
    	if(vehicleInsertList != null && vehicleInsertList.size() > 0){
    		finVehicleMapper.insertForeach(vehicleInsertList);
    	}
    	
    	if(vehicleUpdateList != null && vehicleUpdateList.size() > 0){
    		finVehicleMapper.updateBatch(vehicleUpdateList);
    	}
	}
	
	/**
   	 * 读取单个excel入库,处理二手车发票
   	 *
   	 * @param vehicleList
   	 * @return
   	 */
	public void dealOldcar(List<FinOldcar> oldCarList) throws Exception{
		if(oldCarList == null || oldCarList.size() == 0){
    		return;
    	}
    	
    	List<FinOldcar> oldCarInsertList = new ArrayList<FinOldcar>();
    	List<FinOldcar>  oldCarUpdateList = new ArrayList<FinOldcar>();
    	Iterator<FinOldcar> iter = oldCarList.iterator();
    	while(iter.hasNext()){
    		FinOldcar oldcar = iter.next();
    		FinOldcar oldcarLib = finOldcarMapper.queryByInvkindAndInvnum(oldcar);
    		if(oldcarLib == null){//未查到
    			oldCarInsertList.add(oldcar);
    		}else{
    			MyBeanUtils.copyBeanNotNull2Bean(oldcar, oldcarLib);
    			oldcarLib.setUpdateBy("systemauto");
    			oldcarLib.setUpdateDate(new Date());
    			oldCarUpdateList.add(oldcarLib);
    		}
    	}
    	
    	if(oldCarInsertList != null && oldCarInsertList.size() > 0){
    		finOldcarMapper.insertForeach(oldCarInsertList);
    	}
    	
    	if(oldCarUpdateList != null && oldCarUpdateList.size() > 0){
    		finOldcarMapper.updateBatch(oldCarUpdateList);
    	}
	}
	
	/**
   	 * 读取单个excel入库,处理海关缴款书发票
   	 *
   	 * @param invoiceList
   	 * @return
   	 */
	public List<String> dealCuspay(List<FinCuspay> cuspayList) throws Exception{
		   if(cuspayList == null || cuspayList.size() == 0){
	    		return null;
	    	}
	    	
		    List<List<String>> result = new ArrayList<>();
	    	List<FinCuspay> cuspayInsertList = new ArrayList<FinCuspay>();
	    	List<FinCuspay> cuspayUpdateList = new ArrayList<FinCuspay>();
	    	List<String> detailDeleteList = new ArrayList<String>();
	    	Iterator<FinCuspay> iter = cuspayList.iterator();
	    	while(iter.hasNext()){
	    		FinCuspay invoice = iter.next();
	    		FinCuspay invoiceLib = finCuspayMapper.queryByPayNo(invoice);
	    		if(invoiceLib == null){//未查到
	    			cuspayInsertList.add(invoice);
	    		}else{
	    			MyBeanUtils.copyBeanNotNull2Bean(invoice, invoiceLib);
	    			invoiceLib.setUpdateBy("systemauto");
	    			invoiceLib.setUpdateDate(new Date());
	    			cuspayUpdateList.add(invoiceLib);
	    			detailDeleteList.add(invoice.getPayNo());
	    		}
	    	}
	    	
	    	if(cuspayInsertList != null && cuspayInsertList.size() > 0){
	    		finCuspayMapper.insertForeach(cuspayInsertList);
	    	}
	    	
	    	if(cuspayUpdateList != null && cuspayUpdateList.size() > 0){
	    		finCuspayMapper.updateBatch(cuspayUpdateList);
	    	}
	    
	    	return detailDeleteList;
	}
	
	/**
   	 * 读取单个excel入库,处理海关缴款书发票明细
   	 *
   	 * @param cuspayDetailList
   	 * @param detailDeleteList 存储需要做删除操作的缴款书号码
   	 * @return
   	 */
	public void dealCuspayDetail(List<FinCuspayDetail> cuspayDetailList,List<String> detailDeleteList) throws Exception{
		if(cuspayDetailList == null || cuspayDetailList.size() == 0){
    		return;
    	}
		
		
    	if(detailDeleteList != null && detailDeleteList.size() > 0){
    		finCuspayDetailMapper.deletetForeachBuyPayNo(detailDeleteList);
    	}
    	
    	finCuspayDetailMapper.insertForeach(cuspayDetailList);
	}
	
	/** 
     * 根据当前日期获取表名
     * @param invdate 当前日期的年月 格式yyyy-MM 
     */ 
    public String getTableByNowDate(){
    	
    	String nowDate = new SimpleDateFormat("yyyyMM").format(new Date());
    	
    	String tableName = INVOICE_FRONT+nowDate;
    	
    	String result = tableMap.get(tableName);
    	if(StringUtil.isNotEmpty(result)){
    		return result;
    	}
    	
    	//下面开始创建表
    	int n = finInvoiceMapper.existTable(tableName);
    	if(n > 0){
    		tableMap.put(tableName, tableName);
    		return tableName;
    	}else{
    		finInvoiceMapper.createNewTable(tableName);
    		tableMap.put(tableName, tableName);
    		return tableName;
    	}
    	
    }
	
	
	/**
   	 * 读取单个excel入库,处理非机动车发票
   	 *
   	 * @param invoiceList
   	 * @return
   	 */
	public List<String> dealInvoice(List<FinInvoice> invoiceList) throws Exception{
		   if(invoiceList == null || invoiceList.size() == 0){
	    		return null;
	    	}
	    	
		    List<List<String>> result = new ArrayList<>();
	    	List<FinInvoice> invoiceInsertList = new ArrayList<FinInvoice>();
	    	List<FinInvoice> invoiceUpdateList = new ArrayList<FinInvoice>();
	    	List<String> detailDeleteList = new ArrayList<String>();
	    	Iterator<FinInvoice> iter = invoiceList.iterator();
	    	String tableName = getTableByNowDate();//获取表名
	    	
	    	while(iter.hasNext()){
	    		FinInvoice invoice = iter.next();
	    		
	    		if(StringUtil.isEmpty(tableName)){
	    			log.info("dealInvoice getTableByNowDate is null");
	    			continue;
	    		}
	    		
	    		Map invoiceMap = new HashMap();
	    		invoiceMap.put("tableName", tableName);
	    		invoiceMap.put("invoice", invoice);
	    		FinInvoice invoiceLib = finInvoiceMapper.queryByInvkindAndInvnum(invoiceMap);
	    		if(invoiceLib == null){//未查到
	    			invoiceInsertList.add(invoice);
	    		}else{
	    			MyBeanUtils.copyBeanNotNull2Bean(invoice, invoiceLib);
	    			invoiceLib.setUpdateDate(new Date());
	    			invoiceUpdateList.add(invoiceLib);
	    			detailDeleteList.add(invoiceLib.getInvkind()+invoiceLib.getInvnum());
	    		}
	    	}
	    	
	    	if(invoiceInsertList != null && invoiceInsertList.size() > 0){
	    		Map insertMap = new HashMap();
	    		insertMap.put("tableName", tableName);
	    		insertMap.put("invoiceInsertList", invoiceInsertList);
	    		finInvoiceMapper.insertForeach(insertMap);
	    	}
	    	
	    	if(invoiceUpdateList != null && invoiceUpdateList.size() > 0){
	    		Map updateMap = new HashMap();
	    		updateMap.put("tableName", tableName);
	    		updateMap.put("invoiceUpdateList", invoiceUpdateList);
	    		finInvoiceMapper.updateBatch(updateMap);
	    	}
	    
	    	return detailDeleteList;
	}
	
	/**
   	 * 读取单个excel入库,处理发票明细
   	 *
   	 * @param invoiceDetailList
   	 * @param detailDeleteList 存储需要做删除操作的代码号码
   	 * @return
   	 */
	public void dealInvoiceDetail(List<FinInvoiceDetail> invoiceDetailList,List<String> detailDeleteList) throws Exception{
		if(invoiceDetailList == null || invoiceDetailList.size() == 0){
    		return;
    	}
		
		
    	if(detailDeleteList != null && detailDeleteList.size() > 0){
    		finInvoiceDetailMapper.deletetForeachBuyKindNum(detailDeleteList);
    	}
    	
    	finInvoiceDetailMapper.insertForeach(invoiceDetailList);
	}

}
