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

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.SourceConstants;
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.fittingManager.entity.PlatformFitting;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.CrmSiteAssetFrozenRecordDao;
import com.sifang.modules.sunshine.SystemSetting.dao.SiteInformationDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSite;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSiteAssetFrozenRecord;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.financialManagement.dao.SiteAssetDao;
import com.sifang.modules.sunshine.financialManagement.entity.CrmSiteAsset;
import com.sifang.modules.sunshine.fittingManager.dao.FittingApplyDao;
import com.sifang.modules.sunshine.fittingManager.dao.PlantformFittingKeepDao;
import com.sifang.modules.sunshine.fittingManager.dao.PlatformFittingApplymsgDao;
import com.sifang.modules.sunshine.fittingManager.entity.*;
import com.sifang.modules.supply.stock.constant.MaterialConstants;
import com.sifang.modules.supply.warehouse.constant.MaterialKeepConstants;
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.http.EzTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;
import com.sifang.modules.sys.util.LayuiPage;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author lzp
 * @date 2019/10/11 14:28
 */
@Service
public class FittingApplyService extends BaseService {

	@Autowired
	private FittingApplyDao fittingApplyDao;

	@Autowired
	private PlatformFittingApplymsgDao fittingApplyMsgDao;

	@Autowired
	private PlatformFittingDao fittingDao;
	@Autowired
	private PlantformFittingKeepDao fittingKeepDao;

	@Autowired
	SiteAssetDao siteAssetDao;
	@Autowired
	CrmSiteAssetFrozenRecordDao siteAssetRecordDao;

	@Autowired
	SiteInformationDao siteDao;

	@Autowired
	EzTemplate template;

	public CrmPlantformFittingApply getById(String id){
		return fittingApplyDao.get(id);
	}

	public Record getApplyDetail(String id){
		StringBuilder sb = new StringBuilder();
		sb.append("select a.*,DATE_FORMAT(a.create_time,\"%Y-%m-%d %H:%i:%s\") as createTime,m.message ");
		sb.append(" from crm_platform_fitting_apply a ");
		sb.append(" left join crm_platform_fitting_apply_msg m on m.fitting_apply_id=a.id ");
		sb.append(" where a.id=? ");
		return Db.findFirst(sb.toString(), id);
	}


	@Transactional(rollbackFor=Exception.class)
	public Result adoptApply(String id,String fittingAuditNum,String oldFittingFlag,String factoryMarks){
		User user = UserUtils.getUser();
		String name = CrmUtils.getUserXM(user);
		CrmPlantformFittingApply apply = fittingApplyDao.get(id);
		PlatformFitting fi = fittingDao.get(apply.getFittingId());
		if(!CrmPlantformFittingApply.APPLY_STATUS_UNDELIVERY.equals(apply.getStatus())){
			return Result.fail("401","审核失败,该备件申请已审核或者已取消,请刷新页面");
		}
		if(fi == null){
			return Result.fail("501","出库失败，该备件不存在");
		}
		if(apply == null){
			return Result.fail("501","出库失败，该备件申请数据有误");
		}
		String siteId = apply.getSiteId();
		CrmSiteAsset asset = siteAssetDao.getSiteId(siteId);
		if(asset == null){
			return Result.fail("502","没有备件额度!");
		}
		BigDecimal fittingAudit = new BigDecimal(fittingAuditNum);
		logger.info("fitting ：{} ,getFittingAuditNum :{}",fi.getWarning(),fittingAudit);
		if(fi.getWarning().compareTo(fittingAudit)==-1){
			//库存数量不足
			return Result.fail("503","库存数量不足");
		}
		BigDecimal fittingAmount = fittingAudit.multiply(fi.getSitePrice());
		if(fittingAmount.compareTo(asset.getAvailableAmount()) == 1){
			//备件总金额大于备件可使用额度
			return Result.fail("504","备件额度不足，请联系服务商充值!!");
		}
		CrmSite site = siteDao.get(siteId);

		apply.setStatus(MaterialConstants.PLAT_APPLY_STATUS_OUT);
		apply.setFittingAuditNum(fittingAudit);
		apply.setOldFittingFlag(oldFittingFlag);
		apply.setFactoryMarks(factoryMarks);
		apply.setConfirmTime(new Date());
		apply.setUpdateName(name);
		apply.setUpdateTime(new Date());
		apply.setAuditor(name);
		apply.setAuditorId(user.getId());
		fittingApplyDao.save(apply);
		//申请表修改记录
		PlantformFittingApplyMsg msg = fittingApplyMsgDao.findByApplyId(id);
		if(msg == null){
			msg = new PlantformFittingApplyMsg();
			msg.setFittingApplyId(id);
			msg.setSiteId(apply.getSiteId());
		}
		ComplaintReply tamd = new ComplaintReply();
		tamd.setT(DateUtils.getDateTime());
		tamd.setP(name);
		tamd.setC(name + " 审核 - 备件申请通过,可以出库;");
		String strmsg = WebPageFunUtils.appendProcessDetail(tamd, msg.getMessage());
		msg.setMessage(strmsg);
		fittingApplyMsgDao.save(msg);
		return Result.ok();
	}

	@Transactional(rollbackFor=Exception.class)
	public Result refuseFitting(String id,String refuseReason,String oldFittingFlag,String factoryMarks){
		User user = UserUtils.getUser();
		String name = CrmUtils.getUserXM(user);
		CrmPlantformFittingApply apply = fittingApplyDao.get(id);
		if(!CrmPlantformFittingApply.APPLY_STATUS_UNDELIVERY.equals(apply.getStatus())){
			return Result.fail("401","该备件申请不满足审核条件，已审核或者已取消");
		}
		apply.setStatus(MaterialConstants.PLAT_APPLY_STATUS_FAIL);
		apply.setFactoryMarks(factoryMarks);
		apply.setOldFittingFlag(oldFittingFlag);
		apply.setConfirmTime(new Date());
		apply.setUpdateName(name);
		apply.setUpdateTime(new Date());
		apply.setAuditor(name);
		apply.setAuditorId(user.getId());
		apply.setRefuseReason(refuseReason);
		fittingApplyDao.save(apply);
		//申请表修改记录
		PlantformFittingApplyMsg msg = fittingApplyMsgDao.findByApplyId(id);
		if(msg == null){
			msg = new PlantformFittingApplyMsg();
			msg.setFittingApplyId(id);
			msg.setSiteId(apply.getSiteId());
		}
		ComplaintReply tamd = new ComplaintReply();
		tamd.setT(DateUtils.getDateTime());
		tamd.setP(name);
		tamd.setC(name + " 审核 - 备件申请审核未通过;");
		String strmsg = WebPageFunUtils.appendProcessDetail(tamd, msg.getMessage());
		msg.setMessage(strmsg);
		fittingApplyMsgDao.save(msg);
		return Result.ok();
	}

	/**
	 * 出库
	 * @param id  备件申请id
	 * @param outMarks  出库备注
	 *   The application data status is changed to 3 items to be received. At the same time,
	 *    the inventory of the spare parts subtracts the corresponding quantity, and an issue detail record is added
	*/
	@Transactional(rollbackFor=Exception.class)
	public Result fittingOutStock(String id,String outMarks){
		User user = UserUtils.getUser();
		String name = CrmUtils.getUserXM(user);
		CrmPlantformFittingApply apply = fittingApplyDao.get(id);
		if(!CrmPlantformFittingApply.APPLY_STATUS_DELIVERYED.equals(apply.getStatus())){
			return Result.fail("401","该备件申请不满足出库条件，请刷新页面");
		}

		String siteId = apply.getSiteId();
		CrmSite site = siteDao.get(siteId);

		//修改备件库存
		PlatformFitting fi = fittingDao.get(apply.getFittingId());
		if(fi == null){
			return Result.fail("501","出库失败，该备件不存在");
		}
		logger.info(name + "-- 确认出库 out_fiting , 出库前库存数量为 ："+fi.getWarning() );
		//判断库存数量是否足够,库存数量需要大于审核出库数量
		if(fi.getWarning().compareTo(apply.getFittingAuditNum())==-1){
			//库存数量不足
			return Result.fail("502","库存数量不足");
		}
		BigDecimal fittingAmount = new BigDecimal("0.00");
		//判断备件额度是否足够 --- 没绑定服务商才会去判断
		CrmSiteAsset asset = siteAssetDao.getSiteId(siteId);
		if(asset == null){
			return Result.fail("503","没有备件额度!");
		}
		logger.info("备件可使用额度 使用前 AvailableAmount : "+asset.getAvailableAmount() +".UsedAmount :"+asset.getUsedAmount()+" ,备件申请id: " +apply.getId());
		//备件金额
		fittingAmount = apply.getFittingAuditNum().multiply(fi.getSitePrice());
		if(fittingAmount.compareTo(asset.getAvailableAmount()) == 1){
			//备件总金额大于备件可使用额度
			return Result.fail("504","备件额度不足，请联系服务商充值!!");
		}

		if(SourceConstants.TWO.equals(site.getIsCrmCustomer())){
			//该服务商绑定了CRM客户---- 扣除CRM客户备件账户金额  --- 如果是绑定服务商 则不减扣金额

			//该服务商绑定了CRM客户---- CRM判断生成一条押金扣款申请记录
			String url ="/welcome/depositDeductionApplication";
			Map<String,Object> map = new HashMap<>();
			map.put("customerId",site.getCustomerId());
			map.put("customerName",site.getCustomerName());
			map.put("materielNumber",apply.getFittingCode());
			map.put("fittingName",apply.getFittingName());
			map.put("applicantName",apply.getApplicantName());
			map.put("auditNum",apply.getFittingAuditNum());
			map.put("sitePrice",apply.getSitePrice());
			map.put("fittingAmount",fittingAmount);
			map.put("fittingApplyId",apply.getId());

			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"));
			}

		}




			asset.setAvailableAmount(asset.getAvailableAmount().subtract(fittingAmount));
			asset.setUsedAmount(asset.getUsedAmount().add(fittingAmount));
			siteAssetDao.save(asset);





		logger.info("备件可使用额度 使用后 AvailableAmount : "+apply.getFittingAuditNum() +",备件申请id: " +apply.getId());
		apply.setStatus(CrmPlantformFittingApply.APPLY_STATUS_FINISHED);
		apply.setOutFittingMarks(outMarks);
		apply.setOutFittingTime(new Date());
		apply.setCreator(name);
		apply.setConfirmorId(user.getId());
		apply.setUpdateName(name);
		apply.setUpdateTime(new Date());
		apply.setSitePrice(fi.getSitePrice());
		fittingApplyDao.save(apply);

		fi.setNewestKeepTime(new Date());
		fi.setWarning(fi.getWarning().subtract(apply.getFittingAuditNum()));

		fittingDao.save(fi);
		logger.info(" 确认出库后 备件 "+ fi.getId() +",库存数量为 : "+ fi.getWarning() +" ; 库存数量 减去 审核数量 :"+ apply.getFittingAuditNum());

		//新增一条出库明细记录
		PlantformFittingKeep keep = new PlantformFittingKeep();
		keep.setAmount(apply.getFittingAuditNum());
		keep.setNumber(PlantformUtils.getSiteNumber());
		keep.setType(MaterialKeepConstants.TYPE_OUT);
		keep.setFittingId(fi.getId());
		keep.setFittingCode(fi.getCode());
		keep.setFittingName(fi.getName());
		keep.setPrice(fi.getPrice());
		keep.setSitePrice(fi.getSitePrice());
		keep.setCustomerPrice(fi.getCustomerPrice());
		keep.setRemarks(outMarks);
		keep.setApplicant(apply.getApplicantName());
		keep.setConfirmor(name);
		keep.setCreateBy(user.getId());
		keep.setRelateRecordId(apply.getId());
		fittingKeepDao.save(keep);

		//申请表修改记录
		PlantformFittingApplyMsg msg = fittingApplyMsgDao.findByApplyId(id);
		if(msg == null){
			msg = new PlantformFittingApplyMsg();
			msg.setFittingApplyId(id);
			msg.setSiteId(apply.getSiteId());
		}
		ComplaintReply tamd = new ComplaintReply();
		tamd.setT(DateUtils.getDateTime());
		tamd.setP(name);
		tamd.setC(name + " 出库 - 备件申请 确认出库;");
		String strmsg = WebPageFunUtils.appendProcessDetail(tamd, msg.getMessage());
		msg.setMessage(strmsg);
		fittingApplyMsgDao.save(msg);

			//没有绑定CRM客户的才会有扣款信息
			CrmSiteAssetFrozenRecord ass = new CrmSiteAssetFrozenRecord();
			ass.setAmount(fittingAmount);
			ass.setSiteId(siteId);
			ass.setSitePrice(fi.getSitePrice());
			ass.setApplyFittingId(apply.getId());
			ass.setFittingId(apply.getFittingId());
			siteAssetRecordDao.save(ass);

			//添加扣款记录
		return Result.ok();
	}

	/**
	 * 驳回 ,即 返回待审核
	 * 将状态改为 status = 1 待审核
	*/
	@Transactional(rollbackFor=Exception.class)
	public Result RejectFitting(String id){
		User user = UserUtils.getUser();
		String name = CrmUtils.getUserXM(user);
		CrmPlantformFittingApply apply = fittingApplyDao.get(id);
		if(!CrmPlantformFittingApply.APPLY_STATUS_DELIVERYED.equals(apply.getStatus())){
			return Result.fail("401","该备件申请不满足驳回条件，请刷新页面");
		}
		apply.setStatus(MaterialConstants.PLAT_APPLY_STATUS_WAIT);
		apply.setUpdateName(name);
		apply.setUpdateTime(new Date());
		fittingApplyDao.save(apply);
		//申请表修改记录
		PlantformFittingApplyMsg msg = fittingApplyMsgDao.findByApplyId(id);
		if(msg == null){
			msg = new PlantformFittingApplyMsg();
			msg.setFittingApplyId(id);
			msg.setSiteId(apply.getSiteId());
		}
		ComplaintReply tamd = new ComplaintReply();
		tamd.setT(DateUtils.getDateTime());
		tamd.setP(name);
		tamd.setC(name + " 驳回 - 备件申请 待出库 返回到待审核;");
		String strmsg = WebPageFunUtils.appendProcessDetail(tamd, msg.getMessage());
		msg.setMessage(strmsg);
		fittingApplyMsgDao.save(msg);
		return Result.ok();
	}


	/**
	 * Spare parts application data
	 * @param status Application status: 1. To be approved; 2. To be issued; 3. To be received; 4. Completed; 5. Application cancelled; 6. Application deleted; 7. Approval failed
	 * @param map
	 */
	public void getAllApplyList(LayuiPage<Record> page, Map<String, String> map, String status) {
		List<Record> list = fittingApplyDao.getAllApplyList(page, map, status);
		page.setData(list);
		page.setCount(fittingApplyDao.queryApplyDataCount(map, status));
	}

	public Object[] getAllApplyListForExport(LayuiPage<Record> page, Map<String, String> map, String status) {
		List<Record> list = fittingApplyDao.getAllApplyList(page, map, status);
		Object[] str = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			Record re = list.get(i);
			Object[] childArr = new Object[12];
			childArr[0] = re.getStr("site_name");
			childArr[1] = re.getStr("factoryName");
			childArr[2] = re.getStr("fitting_name");
			childArr[3] = re.getStr("fitting_code");
			childArr[4] = re.getBigDecimal("apply_num");
			childArr[5] = re.getStr("order_number");
			childArr[6] = re.getStr("appliance_brand") + re.getStr("appliance_category");
			childArr[7] = re.getStr("appliance_model");
			childArr[8] = re.getStr("delivery_name");
			childArr[9] = re.getStr("delivery_mobile");
			childArr[10] = re.getStr("delivery_address");
			childArr[12] = re.getDate("create_time");
			str[i] = childArr;
		}
		return str;
	}

	public Object[] getAllApplyListForExportTw(LayuiPage<Record> page, Map<String, String> map, String status) {
		List<Record> list = fittingApplyDao.getAllApplyList(page, map, status);
		Object[] str = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			Record re = list.get(i);
			Object[] childArr = new Object[17];
			childArr[0] = re.getStr("'site_name'");
			childArr[1] = re.getStr("'factoryName'");
			childArr[2] = re.getStr("fitting_name");
			childArr[3] = re.getStr("fitting_code");
			childArr[4] = re.getBigDecimal("apply_num");
			childArr[5] = re.getStr("order_number");
			childArr[6] = re.getStr("appliance_brand") + re.getStr("appliance_category");
			childArr[7] = re.getStr("appliance_model");
			childArr[8] = re.getStr("'logistics_number'");
			childArr[9] = re.getStr("delivery_name");
			childArr[10] = re.getStr("delivery_mobile");
			childArr[11] = re.getStr("delivery_address");
			if("0".equals(re.getStr("'old_fitting_flag'"))){
				childArr[12] = "否";
			} else if ("1".equals(re.getStr("'old_fitting_flag'"))) {
				childArr[12] = "是";
			} else{
				childArr[12] = "";
			}
			if("0".equals(re.getStr("'refund_postage_type'"))){
				childArr[13] = "厂商到付";
			}else if("1".equals(re.getStr("'refund_postage_type'"))){
				childArr[13] = "服务商现付";
			}else{
				childArr[13] = "";
			}
			childArr[14] = re.getStr("'factory_marks'");
			childArr[15] = re.getDate("createTime");
			childArr[16] = re.getDate("'sendTime'");
			str[i] = childArr;
		}
		return str;
	}
	public Object[] getAllApplyListForExportTh(LayuiPage<Record> page, Map<String, String> map, String status) {
		List<Record> list = fittingApplyDao.getAllApplyList(page, map, status);
		Object[] str = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			Record re = list.get(i);
			Object[] childArr = new Object[17];
			childArr[0] = re.getStr("'site_name'");
			childArr[1] = re.getStr("'factoryName'");
			childArr[2] = re.getStr("fitting_name");
			childArr[3] = re.getStr("fitting_code");
			childArr[4] = re.getBigDecimal("apply_num");
			childArr[5] = re.getStr("order_number");
			childArr[6] = re.getStr("appliance_brand") + re.getStr("appliance_category");
			childArr[7] = re.getStr("appliance_model");
			childArr[8] = re.getStr("'logistics_number'");
			childArr[9] = re.getStr("delivery_name");
			childArr[10] = re.getStr("delivery_mobile");
			childArr[11] = re.getStr("delivery_address");
			if("0".equals(re.getStr("'old_fitting_flag'"))){
				childArr[12] = "否";
			} else if ("1".equals(re.getStr("'old_fitting_flag'"))) {
				childArr[12] = "是";
			} else{
				childArr[12] = "";
			}
			if("0".equals(re.getStr("'refund_postage_type'"))){
				childArr[13] = "厂商到付";
			}else if("1".equals(re.getStr("'refund_postage_type'"))){
				childArr[13] = "服务商现付";
			}else{
				childArr[13] = "";
			}
			childArr[14] = re.getStr("'factory_marks'");
			childArr[15] = re.getDate("createTime");
			childArr[16] = re.getDate("'sendTime'");
			str[i] = childArr;
		}
		return str;
	}

	public Record getSiteFittingApplyCount(String siteId){
		return fittingApplyDao.getSiteFittingApplyCount(siteId);
	}


	public Record getpaltformFittingApplyCount(){
		return fittingApplyDao.getpaltformFittingApplyCount();
	}



}
