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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.order.utils.OrderUtils;
import com.sifang.modules.platform.fittingManager.dao.PlatformFittingDao;
import com.sifang.modules.platform.fittingManager.entity.PlatformFitting;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.fittingManager.dao.CrmSiteFittingDao;
import com.sifang.modules.sunshine.fittingManager.dao.PlantformFittingKeepDao;
import com.sifang.modules.sunshine.fittingManager.entity.CrmSiteFitting;
import com.sifang.modules.sunshine.fittingManager.entity.PlantformFittingKeep;
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.persistence.Page;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import com.sifang.modules.sys.util.SqlUtils;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

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


	@Autowired
	private PlatformFittingDao platformFittingDao;
	@Autowired
	private CrmSiteFittingDao crmSiteFittingDao;

	@Autowired
	private PlantformFittingKeepDao keepDao;

	public PlatformFitting getById(String fittingId ){
		return platformFittingDao.get(fittingId);
	}


	public LayuiPage getPlatFormFittingPage(LayuiPage pagee, Map<String,String> map){
			pagee.setData(platformFittingDao.getFittingList(pagee,map));
			pagee.setCount(platformFittingDao.getFittingCount(map));

		return pagee;
	}


	@Transactional(rollbackFor=Exception.class)
	public Result saveFitting(PlatformFitting fitting,User user ){
		String code = fitting.getCode();
		//判断该吾物料号是否存在
			if(platformFittingDao.getcheckFittingCode(code)){
				return Result.fail("202","该物料号已经存在");
			}
		//判断数量是否大于0
		if(fitting.getWarning().compareTo(BigDecimal.ZERO)<0){
			return Result.fail("202","该库存数量要大于等于0");
		}

		String name = CrmUtils.getUserXM(user);
		fitting.setCreateBy(user.getId());
		fitting.setNewestStorageTime(new Date());
		platformFittingDao.save(fitting);

		//保存出入库明细
		PlantformFittingKeep keep = new PlantformFittingKeep();
		keep.setNumber(CrmUtils.no());
		keep.setCreateBy(user.getId());
		/*keep.setRemarks(fitting.getRemarks());*/
		keep.setFittingName(fitting.getName());
		keep.setFittingCode(fitting.getCode());
		keep.setFittingId(fitting.getId());
		keep.setOperateTime(new Date());
		keep.setType(MaterialKeepConstants.TYPE_IN);
		keep.setAmount(fitting.getWarning());
		keep.setPrice(fitting.getPrice());
		keep.setSitePrice(fitting.getSitePrice());
		keep.setConfirmor(name);
		keepDao.save(keep);

		return Result.ok();
	}

	@Transactional(rollbackFor=Exception.class)
	public Result InventoryFitting(Map<String,String> map){
		String newWaring = map.get("newWaring");
		String id = map.get("id");
		String remarks = map.get("remarks"); //调整原因
		BigDecimal waring = new BigDecimal(newWaring);

		//判断盘点后数量是否大于0
		if(waring.compareTo(BigDecimal.ZERO)<0){
			return Result.fail("203","该库存数量要大于等于0");
		}
		User user = UserUtils.getUser();
		String name = CrmUtils.getUserXM(user);
		PlatformFitting fitting = platformFittingDao.get(id);

		/*BigDecimal Amount = fitting.getWarning().subtract(waring);*/
		BigDecimal Amount = waring.subtract(fitting.getWarning());
		logger.info(name +" 调整库存 ; 调整前库存数量为 ："+ fitting.getWarning() );

		fitting.setCreateBy(user.getId());
		fitting.setNewestStorageTime(new Date());
		fitting.setWarning(waring);
		platformFittingDao.save(fitting);
		logger.info(name +" 调整库存 ; 调整 后 库存数量为 ："+ waring + ",调整原因为 ： "+remarks);

		//保存出入库明细
		PlantformFittingKeep keep = new PlantformFittingKeep();
		keep.setNumber(CrmUtils.no());
		keep.setCreateBy(user.getId());
		keep.setRemarks("调整库存原因 ： "+remarks);
		keep.setFittingName(fitting.getName());
		keep.setFittingCode(fitting.getCode());
		keep.setFittingId(fitting.getId());
		keep.setOperateTime(new Date());
		keep.setType(MaterialKeepConstants.TYPE_CHANGE);
		keep.setAmount(Amount);
		keep.setPrice(fitting.getPrice());
		keep.setSitePrice(fitting.getSitePrice());
		keep.setConfirmor(name);
		keepDao.save(keep);

		return Result.ok();
	}


	public Result updateFitting(Map<String,String> map){
		String id = map.get("id");
		PlatformFitting fitt = platformFittingDao.get(id);
		fitt.setName(map.get("name"));
		fitt.setVersion(map.get("version"));
		fitt.setStorehouse(map.get("storehouse"));
		fitt.setSuitPrinter(map.get("suitPrinter"));
		fitt.setUnit(map.get("unit"));
		fitt.setSitePrice(new BigDecimal(map.get("sitePrice")));
		fitt.setCustomerPrice(new BigDecimal(map.get("customerPrice")));
		fitt.setRefundOldFlag(map.get("refundOldFlag"));
		fitt.setRemarks(map.get("remarks"));
		fitt.setImg(map.get("img"));
		platformFittingDao.save(fitt);
		List<CrmSiteFitting> list = crmSiteFittingDao.getByPlatformFittingId(id);
		for (CrmSiteFitting fitting :list) {
			fitting.setName(map.get("name"));
			fitting.setVersion(map.get("version"));
			fitting.setSuitPrinter(map.get("suitPrinter"));
			fitting.setUnit(map.get("unit"));
			fitting.setSitePrice(new BigDecimal(map.get("sitePrice")));
			fitting.setCustomerPrice(new BigDecimal(map.get("customerPrice")));
			fitting.setRefundOldFlag(map.get("refundOldFlag"));
			fitting.setRemarks(map.get("remarks"));
			fitting.setImg(map.get("img"));
			crmSiteFittingDao.save(fitting);
		}
		return Result.ok();
	}



	public List<Record> getPlatFitting(String ids ){
		String sql =" select * from crm_platform_fitting where id in ("+ StringUtil.joinInSql(ids.split(","))+") ";
		return Db.find(sql);
	}


	/**
	 * 备件批量手动入库
	*/
	@SuppressWarnings("unchecked")
	@Transactional(rollbackFor = Exception.class)
	public Result<Void> fittingInstockSave(HttpServletRequest request) {
		String jsonStr = request.getParameter("data1");
		JSONObject json = JSON.parseObject(jsonStr);
		User user = UserUtils.getUser();
		String name = CrmUtils.getUserXM(user);
		Date dt = new Date();
		String code = "200";
		for (Map.Entry<String, Object> js : json.entrySet()) {
			Map<String, String> map = (Map<String, String>) js.getValue();

			String fitId = map.get("fitId");
			String num = map.get("amount");
			String sitePrice = StringUtil.isNotBlank(map.get("sitePrice")) ? map.get("sitePrice"):"0";  //入库价格
			String storehouse = map.get("storehouse");//库位
			String remarks = map.get("remarks");

			PlatformFitting fit = platformFittingDao.get(fitId);// 备件信息remarks
			if (fit == null) {
				continue;
			}
			//判断数量是否大于0
			if(new BigDecimal(num).compareTo(BigDecimal.ZERO)<0){
				code ="203";
				break;
			}
			fit.setWarning(fit.getWarning().add(new BigDecimal(num)));
			fit.setSitePrice(new BigDecimal(sitePrice));
			fit.setStorehouse(storehouse);
			fit.setNewestStorageTime(new Date());
			platformFittingDao.save(fit);
			/*SQLQuery sqlFit = platformFittingDao.getSession()
					.createSQLQuery("update crm_platform_fitting a set a.site_price=:price,a.warning=a.warning+" + num + ",a.storehouse='" + storehouse
							+ "',a.newest_storage_time=now() where a.id=:id ");
			sqlFit.setParameter("price", sitePrice);
			sqlFit.setParameter("id", fitId);
			sqlFit.executeUpdate();// 更新备件主表库存信息*/

			PlantformFittingKeep sfk = new PlantformFittingKeep();
			sfk.setAmount(new BigDecimal(num));
			/*sfk.setApplicant(name);*/
			sfk.setConfirmor(name);
			sfk.setCreateBy(user.getId());
			sfk.setCreateTime(dt);
			sfk.setFittingCode(fit.getCode());
			sfk.setFittingId(fit.getId());
			sfk.setFittingName(fit.getName());
			sfk.setNumber(CrmUtils.no());
			sfk.setOperateTime(dt);
			sfk.setSitePrice(new BigDecimal(sitePrice));
			sfk.setPrice(new BigDecimal("0.00"));
			sfk.setRemarks(remarks);
			sfk.setType(MaterialKeepConstants.TYPE_IN);
			keepDao.save(sfk);// 生成入库明细
		}
		if("203".equals(code)){
			return Result.fail("203","库存数量要大于等于0");
		}

		return Result.ok("入库成功！");

	}

	/**
	 * 删除备件
	*/
	public Result PlatformfittingDelete(String ids ){
		try {
			long siteCount = Db.queryLong("SELECT COUNT(id) FROM crm_site_fitting WHERE platform_fitting_id=? AND warning>0 AND STATUS='1' ",ids);
			if(siteCount>0){
				return Result.fail("203","该备件服务商有库存，不可删除！");
			}
			long platCount = Db.queryLong("SELECT COUNT(id) FROM crm_platform_fitting WHERE id=? AND warning>0 AND STATUS='1' ",ids);
			if(platCount>0){
				return Result.fail("203","该备件有库存，不可删除！");
			}

			SqlBuilder sb = new SqlBuilder()
					.line(" DELETE FROM crm_platform_fitting WHERE id =:ids ");

			SQLQuery sqlQuery = platformFittingDao.getSession().createSQLQuery(sb.toString());
			sqlQuery.setParameter("ids",ids);
			sqlQuery.executeUpdate();
		}catch (Exception e){
			e.printStackTrace();
			return Result.fail("505","删除失败");
		}
		return Result.ok();
	}

}
