package com.sifang.modules.platform.fittingManager.service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.order.utils.WebPageFunUtils;
import com.sifang.modules.platform.controller.form.ComplaintReply;
import com.sifang.modules.platform.fittingManager.dao.PlatformFittingDao;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.FittingAmountDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSiteAssetFrozenRecord;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.financialManagement.dao.SiteAssetDao;
import com.sifang.modules.sunshine.financialManagement.entity.CrmPlatformCollections;
import com.sifang.modules.sunshine.financialManagement.entity.CrmSiteAsset;
import com.sifang.modules.sunshine.fittingManager.dao.FactoryFittingRefundMsgDao;
import com.sifang.modules.sunshine.fittingManager.dao.FittingApplyDao;
import com.sifang.modules.sunshine.fittingManager.dao.PlatformFittingApplymsgDao;
import com.sifang.modules.sunshine.fittingManager.entity.CrmPlantformFittingApply;
import com.sifang.modules.sunshine.fittingManager.entity.CrmPlatformFittingRefund;
import com.sifang.modules.platform.fittingManager.dao.FacFittingRefundDao;
import com.sifang.modules.sunshine.fittingManager.entity.CrmPlantformFittingRefundMsg;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.http.EzTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author lzp
 * @date 2019/10/11 14:28
 * 平台备件返厂service
 */
@Service
public class FacFittingRefundService extends BaseService {

	@Autowired
	private FacFittingRefundDao fittingRefundDao;
    @Autowired
	private FactoryFittingRefundMsgDao fittingRefundMsgDao;
    @Autowired
	private FittingApplyDao fittingApplyDao;


	@Autowired
	EzTemplate template;

	public void getAllRefundFitList(LayuiPage page, Map<String, String> map) {
		List<Record> list = fittingRefundDao.getAllFittingData(page, map);
		page.setData(list);
		page.setCount(fittingRefundDao.queryFittingCount(map));
	}


	public Record getFitRefundDetail(String id){
		StringBuilder sb = new StringBuilder();
		sb.append("select a.*,b.status as orderStatus,b.customer_name,b.customer_mobile ");
		sb.append(" ,b.appliance_brand,b.appliance_category,b.appliance_model");
		sb.append(" from crm_platform_fitting_refund a");
		sb.append(" left join crm_order b on a.order_id=b.id");
		sb.append(" where id=? ");
		return Db.findFirst(sb.toString(), id);
	}

	@Autowired
	private PlatformFittingDao platformFittingDao;
	@Autowired
	private SiteAssetDao siteAssetDao;
	@Autowired
	private FittingAmountDao fittingAmountDao;

	/**
	 * 确认到厂
	 * @param ids
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public String cofToTheFac(String ids) {
		User user = UserUtils.getUser();
		String userName = CrmUtils.getUserXM(user);
		String[] idArr = ids.split(",");
		Date now = new Date();
		//取出所有绑定过得服务商
		List<Map<String,Object>> listmap = Lists.newArrayList();
		List<Record> sites = Db.find(" SELECT id,name,customer_id,customer_name FROM crm_site WHERE is_crm_customer='2' AND STATUS='0' ");
		List<CrmPlatformFittingRefund> list = Lists.newArrayList();
		List<CrmPlantformFittingRefundMsg> msgList=Lists.newArrayList();

		Map<String,BigDecimal> amountMap= Maps.newHashMap();
		List<CrmPlatformCollections> collections=Lists.newArrayList();
		for (String id : idArr) {
			if(StringUtil.isNotBlank(id)){
				CrmPlatformFittingRefund refund = fittingRefundDao.get(id);
				if (refund == null) {
					return "203";//必要参数为空
				}
				if(!CrmPlatformFittingRefund.STATUS_SHIPED.equals(refund.getStatus())){
                          return "204";    //只有未到厂状态才能操作确认到厂
				}

				for(Record rd : sites){
					String siteId = rd.getStr("id");
					if(siteId.equals(refund.getSiteId())){
						Record record=platformFittingDao.getFittingByCode(refund.getFittingCode());
						if(record==null){
							logger.info(">>>>>> cofToTheFac >>>> record==null,该备件不存在");

							return "206";
						}

                        BigDecimal totalAmount=(record.getBigDecimal("site_price").multiply(refund.getRefundNum())).setScale(2, BigDecimal.ROUND_HALF_UP);
						Map<String,Object> maps = new HashMap<>();
						maps.put("customerId",rd.getStr("customer_id"));
						maps.put("customerName",rd.getStr("customer_name"));
						maps.put("materielNumber",record.getStr("code"));
						maps.put("fittingName",record.getStr("name"));
						maps.put("refundNum",refund.getRefundNum());
						maps.put("sitePrice",record.getBigDecimal("site_price"));
						maps.put("confirmName",userName);
						maps.put("totalAmount",totalAmount);
						listmap.add(maps);

						//绑定CRM客户的才会有返款信息
						if(amountMap.get(siteId)==null){
							amountMap.put(siteId,totalAmount);
						}else{
							amountMap.put(siteId,amountMap.get(siteId).add(totalAmount));
						}

						CrmPlatformCollections cpfc = new CrmPlatformCollections();
						cpfc.setSiteId(siteId);
						cpfc.setSiteName(rd.getStr("name"));
						cpfc.setPaymentAmount(totalAmount);
						cpfc.setMarks("备件返回的返款记录");
						cpfc.setPaymentType("3");
						cpfc.setCreateBy(user.getId());
						cpfc.setCreateTime(new Date());
						cpfc.setPayTime(new Date());
						cpfc.setStatus("0");
						cpfc.setImgs("");
						cpfc.setNumber("D" + PlantformUtils.getSiteNumber());
						collections.add(cpfc);
					}
				}

				refund.setConfirmName(userName);
				refund.setStatus(CrmPlatformFittingRefund.STATUS_FINISHED);
				refund.setEndTime(now);//备件签收时间/取消时间
				refund.setUpdateTime(now);
				refund.setUpdateName(CrmUtils.getUserXM(UserUtils.getUser()));
				list.add(refund);

				CrmPlantformFittingRefundMsg fittingRefundMsg=fittingRefundMsgDao.getByRefundId(id);
				ComplaintReply ta = new ComplaintReply();
				ta.setT(DateUtils.getDateTime());
				ta.setP(userName);
				String str=null;
				if(fittingRefundMsg==null){
					fittingRefundMsg=new CrmPlantformFittingRefundMsg();
					fittingRefundMsg.setSiteId(refund.getSiteId());
					fittingRefundMsg.setFittingRefundId(id);
					ta.setC(userName + "修改旧件信息:旧件确认到厂;");
					str = WebPageFunUtils.appendProcessDetail(ta, "");
				}else{
					ta.setC(userName + "修改旧件信息:旧件确认到厂;");
					str = WebPageFunUtils.appendProcessDetail(ta, fittingRefundMsg.getUpdateDetail());
				}
				fittingRefundMsg.setUpdateDetail(str);
				msgList.add(fittingRefundMsg);
			}
		}
		if(listmap.size()>0){
			logger.info(">>>>>>>>>>> cofToTheFac 确认到厂 有服务商关联crm系统 listmap：{}",listmap);
			String url ="/welcome/depositReturnApplication";
			Map<String,Object> map = new HashMap<>();
			Gson gson = new Gson();
			map.put("data",gson.toJson(listmap));
			Map<String,Object> jieMap=	template.postForm(url, map, new ParameterizedTypeReference<Map<String,Object>>() {
			});
			if(!"200".equals(jieMap.get("code"))){
				//不可以出库
				throw new IllegalArgumentException("确认到厂失败，"+jieMap.get("msg"));
				//new Exception("审核失败，"+jieMap.get("msg"));
			}
			//修改售后系统中 服务商账号金额
			if(amountMap.size()>0){
				List<CrmSiteAsset> assets=Lists.newArrayList();
				Date date=new Date();
				for(Map.Entry<String, BigDecimal> entry:amountMap.entrySet()){
					CrmSiteAsset asset = siteAssetDao.getSiteId(entry.getKey());
					logger.info(">>>>>>>>>>> cofToTheFac 确认到厂 服务商会有返款金额 原服务商金额：{}",asset.getAvailableAmount());
					asset.setAvailableAmount(asset.getUsedAmount().add(entry.getValue()));
					asset.setUpdateTime(date);
					assets.add(asset);
				}
				if(assets.size()>0){
					siteAssetDao.save(assets);
				}
			}

           //保存返款记录
			if(collections.size()>0){
				logger.info(">>>>>>>>>>> cofToTheFac 确认到厂 服务商会有返款记录 size:{}",collections.size());
				fittingAmountDao.save(collections);
			}
		}


		fittingRefundMsgDao.save(msgList);
		fittingRefundDao.save(list);
		return "200";
	}

}
