package com.goafanti.order.service.impl;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.AdminMapper;
import com.goafanti.common.dao.OrganizationManagementMapper;
import com.goafanti.common.dao.TOrderInvoiceMapper;
import com.goafanti.common.dao.TOrderMidMapper;
import com.goafanti.common.dao.TOrderNewMapper;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.TOrderInvoice;
import com.goafanti.common.model.TOrderNew;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.order.bo.InputOrderInvoiceBo;
import com.goafanti.order.bo.TOrderInvoiceBo;
import com.goafanti.order.bo.TOrderInvoiceDetails;
import com.goafanti.order.service.OrderInvoiceService;
import com.goafanti.order.service.OrderNewService;


@Service
public class OrderInvoiceServiceImpl extends BaseMybatisDao<TOrderInvoiceMapper> implements OrderInvoiceService {
	@Autowired
	private TOrderInvoiceMapper tOrderInvoiceMapper;
	@Autowired
	private TOrderNewMapper		tOrderNewMapper;
	@Autowired
	private OrganizationManagementMapper	organizationManagementMapper;
	@Autowired
	private AdminMapper	adminMapper;
	@Autowired
	private OrderNewService	orderNewService;
	@Autowired
	private TOrderMidMapper	tOrderMidMapper;
	@Override
	public int createServiceOrder(TOrderInvoice o) {
		o.setCreateTime(new Date());
		sendNoticeAndEmail(o);
		return tOrderInvoiceMapper.insertSelective(o);
	}
	
	

	@Override
	public int updateServiceOrder(TOrderInvoice o) {
		sendNoticeAndEmail(o);
		return tOrderInvoiceMapper.updateByPrimaryKeySelective(o);
	}
	/**
	 * 	开票提交发送站内消息及邮件
	 * @param o
	 */
	private void sendNoticeAndEmail(TOrderInvoice o) {
		List<String> aids = new ArrayList<>();
		if (o.getStatus()==1) {//发起
			TOrderNew t=tOrderNewMapper.selectByPrimaryKey(o.getOrderNo());
			if (o.getType()==0) {//省内
				if(o.getApproval()==0) {
					aids.add(organizationManagementMapper.selectByPrimaryKey(t.getOrderDep()).getFinanceId());
				}else {
					for (Admin admin : adminMapper.getAdminRoleList("集团副总")) {
						aids.add(admin.getId());
					}
				}
			}else if (o.getType()==1) {//省外
				if(o.getApproval()==0) {
					aids.addAll(adminMapper.listNameByDepAndName(t.getOrderDep(), "营销管理员"));
				}else {
					aids.addAll(adminMapper.listNameByDepAndName(t.getOrderDep(), "公司管理"));
				}
			}
		}
		orderNewService.pushGeneralSendNoticeAndEmail(aids, NoticeStatus.ORDER_INVPICE_START.getCode(),o.getOrderNo(), TokenManager.getAdminId(),0);
	}

	@Override
	public boolean checkAmount(TOrderInvoice t) {
		TOrderNew tn=tOrderNewMapper.selectByPrimaryKey(t.getOrderNo());
		
			String i=tOrderInvoiceMapper.checkApplyAmount(t.getOrderNo(),t.getId());//新建时直接查所有数据,修改时除掉修改订单
			//处理精度问题
		BigDecimal q=t.getAmount().add(new BigDecimal(i)).setScale(4, BigDecimal.ROUND_DOWN);;
		BigDecimal w=tn.getTotalAmount();
		int	flag=q.compareTo(w);
		if (flag>0) {
			return true;
		}
		return false;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<TOrderInvoiceBo> financeOrderInvoiceList(InputOrderInvoiceBo o,Integer pageNo,
			Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(pageSize==null||pageSize<0)pageSize=10;
		if(pageNo==null||pageNo<0)pageNo=1;
		List<String> aDep=new ArrayList<>();
		//财务专员查看自己的
		if (TokenManager.hasRole(AFTConstants.FINANCE)) {
			params.put("financeId", TokenManager.getAdminId());
		}
		//财务经理
		if (TokenManager.hasRole(AFTConstants.FINANCE_MANAGER)) {
			aDep=adminMapper.selectDepIdWithSpuerId(TokenManager.getAdminId());
			params.put("aDep", aDep);
		}
		if(StringUtils.isNotBlank(o.getOrderDep()))params.put("orderDep", o.getOrderDep());
		if(o.getType()!=null)params.put("type", o.getType());
		//营销管理员
		if (TokenManager.hasRole(AFTConstants.SALESMAN_ADMIN)) {
			Admin a=adminMapper.selectByPrimaryKey(TokenManager.getAdminId());
			aDep.add(a.getDepartmentId());
			params.put("aDep", aDep);
		} 
		if(StringUtils.isNotBlank(o.getOrderNo()))params.put("orderNo", o.getOrderNo());
		if(StringUtils.isNotBlank(o.getName()))params.put("name", o.getName());
		if(null==o.getApproval())params.put("approval", o.getApproval());
		if(null==o.getStatus())params.put("status", o.getStatus());
		return (Pagination<TOrderInvoiceBo>)findPage("financeOrderInvoiceList", "financeOrderInvoiceCount", params, pageNo, pageSize);
		
	}

	@Override
	public TOrderInvoiceDetails selectByIdOrderInvoice(Integer id) {
		return tOrderInvoiceMapper.selectByInvoiceDitails(id);
	}
	
	@Override
	public TOrderInvoiceDetails getInvoiceDetails(String orderNo) {
		return tOrderInvoiceMapper.getInvoiceDetails(orderNo);
	}
	

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<TOrderInvoiceBo> salesmanOrderInvoiceList( String orderNo, 
			Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(pageSize==null||pageSize<0)pageSize=10;
		if(pageNo==null||pageNo<0)pageNo=1;
		if(StringUtils.isNotBlank(orderNo))params.put("orderNo", orderNo);
		return (Pagination<TOrderInvoiceBo>)findPage("salesmanOrderInvoiceList", "salesmanOrderInvoiceCount", params, pageNo, pageSize);
	}

	@Override
	public int updatefinanceExamine(Integer id, Integer examine, String reason) {
		TOrderInvoice t=new TOrderInvoice();
		t.setId(id);
		t.setRejectReason(reason);
		t.setStatus(examine);
		//examine 2通过 3拒绝
		List<String> aids = new ArrayList<>();
		TOrderInvoice t2=tOrderInvoiceMapper.selectByPrimaryKey(id);
		TOrderNew o=tOrderNewMapper.selectByPrimaryKey(t2.getOrderNo());
		Integer type=null;
		if(examine==3){
			if(t2.getApproval()==2)t.setApproval(1);
			type=NoticeStatus.ORDER_INVPICE_NO.getCode();
			aids.add(o.getSalesmanId());
		}else if(examine==2) {
			type=NoticeStatus.ORDER_INVPICE_END.getCode();
			aids.add(o.getSalesmanId());
			//重新计算开票金额
			
		}
		orderNewService.pushGeneralSendNoticeAndEmail(aids, type,t2.getOrderNo(), TokenManager.getAdminId(),0);
		tOrderInvoiceMapper.updateByPrimaryKeySelective(t);
		if(examine==2)tOrderMidMapper.updateInvoice(t2.getOrderNo());
		return 1; 
	}

		
		



	@SuppressWarnings("unchecked")
	@Override
	public Pagination<TOrderInvoiceBo> approvalOrderInvoiceList(Integer status,Integer approval,Integer type, String orderDep, String orderNo, String name,String userName,
			Integer pageNo, Integer pageSize) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(pageSize==null||pageSize<0)pageSize=10;
		if(pageNo==null||pageNo<0)pageNo=1;
		if(StringUtils.isNotBlank(orderDep))params.put("orderDep", orderDep);
		if(StringUtils.isNotBlank(orderNo))params.put("orderNo", orderNo);
		if(StringUtils.isNotBlank(name))params.put("name", name);
		if(StringUtils.isNotBlank(userName))params.put("userName", userName);
		if(approval!=null)params.put("approval", approval);
		if(status!=null)params.put("status", status);
		//0省内 1省外 2查看所有省外
		if(type==0||type==1)params.put("type", type);
		if (type==2) {
			params.put("type", 1);
			params.put("special", 1);
		}
		if (type ==1) {
			//如果是省外则直接查本部门
			Admin a=adminMapper.selectByPrimaryKey(TokenManager.getAdminId());
			params.put("aDep", a.getDepartmentId());
		}
		return (Pagination<TOrderInvoiceBo>)findPage("approvalOrderInvoiceList", "approvalOrderInvoiceCount", params, pageNo, pageSize);
	}

	@Override
	public int updateapprovalExamine(Integer id, Integer examine, String reason) {
 		TOrderInvoice t=new TOrderInvoice();
		t.setId(id);
		t.setRejectReason(reason);
		List<String> aids=new ArrayList<>();
		TOrderInvoice o=tOrderInvoiceMapper.selectByPrimaryKey(id);
		TOrderNew ts=tOrderNewMapper.selectByPrimaryKey(o.getOrderNo());
		//examine 2通过 3拒绝
		Integer type =null;
		if(examine==3) {
		t.setStatus(examine);
		type= NoticeStatus.ORDER_INVPICE_APPROVA_NO.getCode();
		aids.add(ts.getSalesmanId());
		}else {
			t.setApproval(examine);
			type= NoticeStatus.ORDER_INVPICE_APPROVA_YES.getCode();
			if (o.getType()==0) {
				aids.add(organizationManagementMapper.selectByPrimaryKey(ts.getOrderDep()).getFinanceId());
			}else if(o.getType()==1) {
				aids.addAll(adminMapper.listNameByDepAndName(ts.getOrderDep(), "营销管理员"));
			}
		
		}
		orderNewService.pushGeneralSendNoticeAndEmail(aids,type,o.getOrderNo(), TokenManager.getAdminId(),0);
		return tOrderInvoiceMapper.updateByPrimaryKeySelective(t);
	}

}
