package nccloud.openapi.imag.invoice.tax;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import nc.bs.framework.common.NCLocator;
import nc.dto.imag.boot.RequestInfo;
import nc.dto.imag.boot.ResponseInfo;
import nc.dto.imag.invoice.accountentry.AccountEntryCommonRequest;
import nc.dto.imag.invoice.accountentry.AccountEntryCommonResponse;
import nc.dto.imag.invoice.reimbursed.ReimbursedCommonRequest;
import nc.dto.imag.invoice.reimbursed.ReimbursedCommonResponse;
import nc.dto.imag.invoice.tax.AllInvoiceDeleteCommonRequest;
import nc.dto.imag.invoice.tax.EInvoiceCommonRequest;
import nc.dto.imag.invoice.tax.EInvoiceCommonResponse;
import nc.dto.imag.invoice.tax.InvalidCommonRequest;
import nc.dto.imag.invoice.tax.InvalidCommonResponse;
import nc.dto.imag.invoice.tax.TaxAllInvoiceRequest;
import nc.dto.imag.invoice.tax.TaxCommonRequest;
import nc.dto.imag.invoice.tax.TaxCommonResponse;
import nc.dto.imag.invoice.view.PreviewCommonRequest;
import nc.dto.imag.invoice.view.PreviewCommonResponse;
import nc.itf.openapi.invoice.tax.IEInvoiceService;
import nc.itf.openapi.invoice.tax.ITaxInvoiceService;
import nc.itf.uap.IUAPQueryBS;
import nc.vo.image.log.ImageLogBusiTypeEnum;
import nc.vo.image.log.ImageLogUtil;
import nccloud.api.rest.utils.NCCRestUtils;
import nccloud.openapi.imag.ImageOpenApiResources;
import nccloud.openapi.imag.service.ImagOpenApiServiceLocator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import nc.dto.imag.invoice.tax.InvoiceDeleteCommonRequest;
import nc.itf.sscivm.service.IInvoiceUploadService;
import nc.itf.sscivm.service.IVMInvoiceQueryService;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.pub.BusinessException;
import nc.vo.sscivm.invoice.IVMInvoiceAggVO;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.commons.lang.StringUtils;
import nccloud.itf.sscivm.ivrec.service.IVRecService;
import org.json.JSONString;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONString;

/**
 * openapi 影像税务服务
 * 
 * @author gaozhf@yonyou.com
 * 
 */
@Path("imag/invoice/tax")
public class InvoiceTaxResources extends ImageOpenApiResources {
	@SuppressWarnings("unchecked")
	@POST
	@Path("uploadeinvoice")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString uploadEInvoice(RequestInfo<EInvoiceCommonRequest> request) {
		ResponseInfo<EInvoiceCommonResponse> response = new ResponseInfo<EInvoiceCommonResponse>();
		try {
			response = ImagOpenApiServiceLocator.find(IEInvoiceService.class).uploadEInvoice(request);
			
		} catch (Exception e) {
			// 日志落库
			ImageLogUtil.insertErrorLog(e);
			
			response = (ResponseInfo<EInvoiceCommonResponse>) parseErrorMessage(e);
		} finally{
			// 日志落库
			ImageLogUtil.insertMainLog(ImageLogBusiTypeEnum.UPLOAD_EINVOICE, request, response);
		}
		
		return NCCRestUtils.toJSONString(response);
	}
	
	@SuppressWarnings("unchecked")
	@POST
	@Path("deleteeinvoice")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString deleteEInvoice(RequestInfo<EInvoiceCommonRequest> request) {
		ResponseInfo<EInvoiceCommonResponse> response = new ResponseInfo<EInvoiceCommonResponse>();
		try {
			response = ImagOpenApiServiceLocator.find(IEInvoiceService.class).deleteEInvoice(request);
			
		} catch (Exception e) {
			// 日志落库
			ImageLogUtil.insertErrorLog(e);
			
			response = (ResponseInfo<EInvoiceCommonResponse>) parseErrorMessage(e);
			
		} finally{
			// 日志落库
			ImageLogUtil.insertMainLog(ImageLogBusiTypeEnum.DELETE_EINVOICE, request, response);
		}
		
		return NCCRestUtils.toJSONString(response);
	}

	/**
	 * 发票全票面上传入口（新）
	 * @param request
	 * @return
	 */
	@POST
	@Path("upload_allinvoice")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString doUploadForAllInvoice(RequestInfo<TaxAllInvoiceRequest[]> request) {

		ResponseInfo<TaxCommonResponse[]> response = null;
		Object result = null;

		try {
			
			response = ImagOpenApiServiceLocator.find(ITaxInvoiceService.class).doUploadForAllInvoice(request, true);
			
			result = buildSucessResponseInfo(response);

		} catch (Exception e) {
			// 日志落库
			ImageLogUtil.insertErrorLog(e);
			
			result = parseErrorMessage(e);
		}finally{
			// 日志落库
			ImageLogUtil.insertMainLog(ImageLogBusiTypeEnum.SAVE_ALLINVOICE, request, result);
		}

		return NCCRestUtils.toJSONString(result);
	}

	/**
	 * 增值税发票上传入口（旧）
	 * @param request
	 * @return
	 */
	@POST
	@Path("upload")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString doUpload(RequestInfo<TaxCommonRequest[]> request) {

		ResponseInfo<TaxCommonResponse[]> response = null;
		Object result = null;

		try {
			
			response = ImagOpenApiServiceLocator.find(ITaxInvoiceService.class).doUploadForVATInvoice(request, true);
			
			result = buildSucessResponseInfo(response);

		} catch (Exception e) {
			// 日志落库
			ImageLogUtil.insertErrorLog(e);
			
			result = parseErrorMessage(e);
		}finally{
			// 日志落库
			ImageLogUtil.insertMainLog(ImageLogBusiTypeEnum.SAVE, request, result);
		}

		return NCCRestUtils.toJSONString(result);
	}

	@POST
	@Path("uploadtotax")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString doUploadToTax(RequestInfo<TaxCommonRequest[]> request) {

		ResponseInfo<TaxCommonResponse[]> response = null;

		try {
			response = ImagOpenApiServiceLocator.find(ITaxInvoiceService.class).doUploadToTax(request);
		} catch (Exception e) {
			return NCCRestUtils.toJSONString(parseErrorMessage(e));
		}

		return NCCRestUtils.toJSONString(buildSucessResponseInfo(response));
	}

	/**
	 * 全票面发票删除入口
	 * @param request
	 * @return
	 */
	@POST
	@Path("delete_allinvoice")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString doDeleteForAllInvoice(RequestInfo<TaxAllInvoiceRequest[]> request) {

		ResponseInfo<TaxCommonResponse[]> response = null;
		Object result = null;

		try {
			response = ImagOpenApiServiceLocator.find(ITaxInvoiceService.class).doDeleteForAllInvoice(request);
			
			result = buildSucessResponseInfo(response);
			
		} catch (Exception e) {
			// 日志落库
			ImageLogUtil.insertErrorLog(e);
			
			result = parseErrorMessage(e);
		}finally{
			// 日志落库
			ImageLogUtil.insertMainLog(ImageLogBusiTypeEnum.FACTORY_DELETE_IMAGE_ALLINVOICE, request, result);
		}

		return NCCRestUtils.toJSONString(result);
	}

	/**
	 * 全票面发票删除入口（旧）
	 * @param request
	 * @return
	 */
	@POST
	@Path("delete")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString doDelete(RequestInfo<TaxCommonRequest[]> request) {

		ResponseInfo<TaxCommonResponse[]> response = null;
		Object result = null;

		try {
			response = ImagOpenApiServiceLocator.find(ITaxInvoiceService.class).doDeleteForVATInvoice(request);
			
			result = buildSucessResponseInfo(response);
			
		} catch (Exception e) {
			// 日志落库
			ImageLogUtil.insertErrorLog(e);
			
			result = parseErrorMessage(e);
		}finally{
			// 日志落库
			ImageLogUtil.insertMainLog(ImageLogBusiTypeEnum.FACTORY_DELETE_IMAGE, request, result);
		}

		return NCCRestUtils.toJSONString(result);
	}

	@POST
	@Path("deletetotax")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString doDeleteToTax(RequestInfo<AllInvoiceDeleteCommonRequest[]> request) {

		ResponseInfo<TaxCommonResponse[]> response = null;

		try {
			response = ImagOpenApiServiceLocator.find(ITaxInvoiceService.class).doDeleteToTax(request);
		} catch (Exception e) {
			return NCCRestUtils.toJSONString(parseErrorMessage(e));
		}

		return NCCRestUtils.toJSONString(buildSucessResponseInfo(response));
	}

	@POST
	@Path("reimbursed")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString doReimbursed(RequestInfo<ReimbursedCommonRequest[]> request) {

		ResponseInfo<ReimbursedCommonResponse> response = null;

		try {
			response = ImagOpenApiServiceLocator.find(ITaxInvoiceService.class).doReimbursed(request);
		} catch (Exception e) {
			return NCCRestUtils.toJSONString(parseErrorMessage(e));
		}

		return NCCRestUtils.toJSONString(buildSucessResponseInfo(response));
	}

	@POST
	@Path("unreimbursed")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString doUnReimbursed(RequestInfo<ReimbursedCommonRequest[]> request) {

		ResponseInfo<ReimbursedCommonResponse> response = null;

		try {
			response = ImagOpenApiServiceLocator.find(ITaxInvoiceService.class).doUnReimbursed(request);
		} catch (Exception e) {
			return NCCRestUtils.toJSONString(parseErrorMessage(e));
		}

		return NCCRestUtils.toJSONString(buildSucessResponseInfo(response));
	}

	@POST
	@Path("accountentry")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString doAccountEntry(RequestInfo<AccountEntryCommonRequest[]> request) {

		ResponseInfo<AccountEntryCommonResponse> response = null;

		try {
			response = ImagOpenApiServiceLocator.find(ITaxInvoiceService.class).doAccountEntry(request);
		} catch (Exception e) {
			return NCCRestUtils.toJSONString(parseErrorMessage(e));
		}

		return NCCRestUtils.toJSONString(buildSucessResponseInfo(response));
	}

	@POST
	@Path("cancelaccountentry")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString doCancelAccountEntry(RequestInfo<AccountEntryCommonRequest[]> request) {

		ResponseInfo<AccountEntryCommonResponse> response = null;

		try {
			response = ImagOpenApiServiceLocator.find(ITaxInvoiceService.class).doCancelAccountEntry(request);
		} catch (Exception e) {
			return NCCRestUtils.toJSONString(parseErrorMessage(e));
		}

		return NCCRestUtils.toJSONString(buildSucessResponseInfo(response));
	}

	@POST
	@Path("preview")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString doPreview(RequestInfo<PreviewCommonRequest[]> request) {

		ResponseInfo<PreviewCommonResponse> response = null;

		try {
			response = ImagOpenApiServiceLocator.find(ITaxInvoiceService.class).doPreview(request);
		} catch (Exception e) {
			return NCCRestUtils.toJSONString(parseErrorMessage(e));
		}

		return NCCRestUtils.toJSONString(buildSucessResponseInfo(response));
	}

	@POST
	@Path("invalid")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString doInvalid(RequestInfo<InvalidCommonRequest> request) {

		ResponseInfo<InvalidCommonResponse> response = null;

		try {
			response = ImagOpenApiServiceLocator.find(ITaxInvoiceService.class).invoiceInvalid(request);
		} catch (Exception e) {
			return NCCRestUtils.toJSONString(parseErrorMessage(e));
		}

		return NCCRestUtils.toJSONString(buildSucessResponseInfo(response));
	}

	@POST
	@Path("dzfpupload")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString doDzfpUpload(JSONString json) {
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> res = new HashMap<String, Object>();

		res.put("code", "0000");
		try {
			JSONObject jObject = JSON.parseObject(json.toJSONString());
			if (jObject == null) {
				res.put("success", false);
				res.put("message", "JSONString is null ");
				
				return NCCRestUtils.toJSONString(res);
			}
			String pk_org = jObject.getString("pk_org");// 财务组织主键
			if (StringUtils.isBlank(pk_org)) {
				res.put("success", false);
				res.put("message", "财务组织主键(pk_org)不能为空 ");
				
				return NCCRestUtils.toJSONString(res);
			}
	
			String pk_bill = jObject.getString("billid");// 单据主键
			if (StringUtils.isBlank(pk_bill)) {
				res.put("success", false);
				res.put("message", "单据主键(billid)不能为空 ");
				
				
				return NCCRestUtils.toJSONString(res);
			}
	
			String billtype = jObject.getString("billtype");// 单据类型编码
			if (StringUtils.isBlank(billtype)) {
				res.put("success", false);
				res.put("message", "单据类型编码(billtype)不能为空 ");
				
				return NCCRestUtils.toJSONString(res);
			}
			
			
			String transitype = jObject.getString("transitype");// 交易类型编码
			 
			if (StringUtils.isBlank(transitype)) {
				transitype=getTradeTypeCode(billtype,pk_bill);
			}
//			String tradetype=getTradeTypeCode(billtype,pk_bill);
		

	
			JSONArray jsrr= jObject.getJSONArray("data");
			if(jsrr.isEmpty()) {
				res.put("success", false);
				res.put("message", "电子发票源文件(file)不能为空");
				
				return NCCRestUtils.toJSONString(res);
			}
			
			int i_true=0;
			
			ArrayList<Map<String, Object>> l_true=new ArrayList<>();
			ArrayList<Map<String, Object>> l_false=new ArrayList<>();
			for (int i = 0; i < jsrr.size(); i++) {
				
				JSONObject nodeinsTodo = jsrr.getJSONObject(i);
				
				String fileContent = nodeinsTodo.getString("file");// 电子发票源文件
				if (StringUtils.isBlank(fileContent)) {
					res.put("success", false);
					res.put("message", "电子发票源文件(file)不能为空");
					
					
					
					return NCCRestUtils.toJSONString(res);
				}
		
				String filename = nodeinsTodo.getString("filename");// 文件名称
				if (filename == null) {
					filename = pk_bill+String.valueOf(i+1);
				}
				
				
				Map<String, Object>  result = NCLocator.getInstance().lookup(IInvoiceUploadService.class).upload(pk_org, pk_bill, billtype,transitype, filename, fileContent);

				
				if (result.get("success") == null||(boolean) result.get("success")) {
					res.put("success", true);
					i_true++;
					l_true.add((Map<String, Object>) result.get("data"));
				}else {
					
					Map<String, Object> f_map =( Map<String, Object>) result.get("data");
					f_map.put("message", result.get("message"));
					
					
					l_false.add(f_map);
				}
				
				
//				String add_json = objectMapper.writeValueAsString(result);
				
			}
			
			if(i_true== jsrr.size()) {
				res.put("code", "0000");
				res.put("message", "请求成功");
				res.put("success", true);
				if(!l_true.isEmpty()) {
					res.put("tdata", l_true);
				}
				
			}else {
				res.put("success", false);
				if(i_true==0) {
					res.put("message", "上传失败");
				}else {
					res.put("message", "部分成功");
				}
//				result.put("message", "部分成功");
				if(!l_true.isEmpty()) {
					res.put("tdata", l_true);
				}
				if(!l_false.isEmpty()) {
					res.put("fdata", l_false);
				}
				
			}
			
			
			
			
			
//			String fileContent = jObject.getString("file");// 电子发票源文件
//			if (StringUtils.isBlank(fileContent)) {
//				result.put("success", false);
//				result.put("message", "电子发票源文件(file)不能为空");
//				return NCCRestUtils.toJSONString(result);
//			}
//	
//			String filename = jObject.getString("filename");// 文件名称
//			if (filename == null) {
//				filename = pk_bill;
//			}
//			
//			
//	
//			
//
//			result = NCLocator.getInstance().lookup(IInvoiceUploadService.class).upload(pk_org, pk_bill, billtype,tradetype, filename, fileContent);
//
//	
//			if (result.get("success") == null) {
//				result.put("success", true);
//			}
//
			String add_json = objectMapper.writeValueAsString(res);
			
		
			return NCCRestUtils.toJSONString(add_json);

		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
//			return NCCRestUtils.toJSONString(e.getMessage());
			return NCCRestUtils.toJSONString(parseErrorMessage(e));
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			return NCCRestUtils.toJSONString(parseErrorMessage(e));
		}

	}

	@POST
	@Path("dzfpdelete")
	@Consumes({ "application/json" })
	@Produces({ "application/json" })
	public JSONString doDzfpDelete(JSONString json) {
		JSONObject jObject = JSON.parseObject(json.toJSONString());
		Map<String, Object> result = new HashMap<>();
		ObjectMapper objectMapper = new ObjectMapper();
		result.put("code", "0000");
		try {
			if (jObject == null) {
				result.put("success", false);
				result.put("message", "JSONString is null ");
				
				
				return NCCRestUtils.toJSONString(result);
			}
		
		
		
		JSONArray jsrr= jObject.getJSONArray("data");
		if(jsrr.isEmpty()) {
			result.put("success", false);
			result.put("message", "参数错误");
			
			
			return NCCRestUtils.toJSONString(result);
		}
		
		ArrayList<Map<String, Object>> l_false=new ArrayList<>();
		
		for (int i = 0; i < jsrr.size(); i++) {
			JSONObject nodeinsTodo = jsrr.getJSONObject(i);
			
			
			
			String fphm = nodeinsTodo.getString("fpHm");// 发票号码
			if (StringUtils.isBlank(fphm)) {
				result.put("success", false);
				result.put("message", "发票号码(fpHm)不能为空");
				
				
				
				return NCCRestUtils.toJSONString(result);
			}

			String fpdm = nodeinsTodo.getString("fpDm");// 发票代码
			String condition = "";
			if (StringUtils.isBlank(fpdm)) {
				condition = "fphm = '" + fphm + "' and dr = 0 ";
			} else {
				condition = "fphm = '" + fphm + "' and fpdm = '" + fpdm + "' and dr = 0 ";
			}

			
				IVMInvoiceAggVO[] invoices = NCLocator.getInstance().lookup(IVMInvoiceQueryService.class).queryAggVOsByCondition(condition);
				if (invoices != null && invoices.length > 0) {
					String pk_invoice = invoices[0].getHeadVO().getPk_invoice();
					ArrayList<String> l = new ArrayList<>();
					l.add(pk_invoice);
					boolean bool = NCLocator.getInstance().lookup(IVRecService.class).deleteIVMInvoices(l.toArray(new String[0]));
//					result.put("success", bool);
//					result.put("code", "0000");
//					String add_json = objectMapper.writeValueAsString(result);
//					return NCCRestUtils.toJSONString(add_json);
					
					if(!bool) {
						Map<String, Object> map_f = new HashMap<>();
						map_f.put("fphm", fphm);
						if (StringUtils.isBlank(fpdm)) {
							map_f.put("fpdm", "");
						}else {
							map_f.put("fpdm", fpdm);
						}
						l_false.add(map_f);
					}
					
				} else {
					Map<String, Object> map_f = new HashMap<>();
					map_f.put("fphm", fphm);
					if (StringUtils.isBlank(fpdm)) {
						map_f.put("fpdm", "");
					}else {
						map_f.put("fpdm", fpdm);
					}
					l_false.add(map_f);
				}
				
		}
		
		if(!l_false.isEmpty()) {
			result.put("success", false);
			result.put("code", "0000");
			result.put("fdata", l_false);
		}else {
			result.put("success", true);
			result.put("code", "0000");
		}
		
		
		String add_json = objectMapper.writeValueAsString(result);
		
		return NCCRestUtils.toJSONString(add_json);
//		return NCCRestUtils.toJSONString(add_json);
		
		
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			return NCCRestUtils.toJSONString(parseErrorMessage(e));
		}catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			return NCCRestUtils.toJSONString(parseErrorMessage(e));
		}
	}
	
	
	private String getTradeTypeCode(String billtype,String billid) throws BusinessException {
		
		String sql="";
		
		if(billtype.startsWith("264")) {//报销
			sql="select djlxbm from er_bxzb where dr=0 and pk_jkbx='"+billid+"'";
		}else if(billtype.equals("F1")) {//应付单
			sql="select pk_tradetype From ap_payablebill where isnull(dr, 0)=0 and pk_payablebill='"+billid+"'";
		}
		

		String tradetypecode = (String)getQueryService().executeQuery(sql, new ColumnProcessor());
		return tradetypecode;
	}
	
	
	public IUAPQueryBS getQueryService() {
		return NCLocator.getInstance().lookup(IUAPQueryBS.class);
	}
	
	
	@Override
	public String getModule() {

		return null;
	}
}
