package com.uas.platform.b2b.service.impl;

import com.uas.platform.b2b.core.util.ContextUtils;
import com.uas.platform.b2b.core.util.ThreadTask;
import com.uas.platform.b2b.dao.*;
import com.uas.platform.b2b.event.PurchaseApCheckReplyReleaseEvent;
import com.uas.platform.b2b.model.*;
import com.uas.platform.b2b.service.PurchaseApCheckService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.exception.IllegalOperatorException;
import com.uas.platform.core.model.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PurchaseApCheckServiceImpl implements PurchaseApCheckService {

	@Autowired
	PurchaseApCheckDao purchaseApCheckDao;

	@Autowired
	PurchaseApCheckItemDao purchaseApCheckItemDao;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private UserOrderDao userOrderDao;

	@Override
	public List<PurchaseApCheck> findNotUploadAPcheck() {
		return purchaseApCheckDao.findByCustUuAndStatusAndCheckStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value(), "未对账");
	}

	@Override
	public void onApCheckSuccess(String[] idArray) {
		for (String id : idArray) {
			PurchaseApCheck apCheck = purchaseApCheckDao.findOne(Long.parseLong(id));
			if (apCheck != null) {
				apCheck.setStatus((short) Status.DOWNLOADED.value());
				purchaseApCheckDao.save(apCheck);
			}
		}
	}

	@Override
	public void saveApChecks(List<PurchaseApCheckItem> checkItems) {
		if (checkItems != null && checkItems.size() > 0) {
			purchaseApCheckItemDao.save(checkItems);
			List <PurchaseApCheck> apChecks = PurchaseApCheckItem.distinct(checkItems);
			saveUserOrders(apChecks);
			ContextUtils.publishEvent(new PurchaseApCheckReplyReleaseEvent(apChecks));
		}
	}

	private void saveUserOrders(final List<PurchaseApCheck> checks) {
		ThreadTask.getInstance().execute(new Runnable() {
			@Override
			public void run() {
            	/* 添加供应商的阅读记录*/
            	List<UserOrders> list = new ArrayList<>();
				for(PurchaseApCheck check : checks) {
					if (check.getRecorderUU() == null) {
						continue;
					}
					UserOrders userOrders = new UserOrders(check.getRecorderUU(), check.getEnUu(), check.getId(), "purc", "purc$apcheck");
					list.add(userOrders);
				}
				userOrderDao.save(list);
			}
		});
	}

	@Override
	public PurchaseApCheck findById(Long id) {
		return purchaseApCheckDao.findOne(id);
	}

	@Override
	@Transactional
	public PurchaseApCheck save(PurchaseApCheck purchaseApCheck) {
		purchaseApCheck.setRecordDate(new Date());
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMddhhmmss_sss");
		String code = sdf.format(d);
		purchaseApCheck.setCode(code);
		purchaseApCheck.setRecorder(SystemSession.getUser().getUserName());
		purchaseApCheck.setRecorderUU(SystemSession.getUser().getUserUU());
		Short number = 0;
		List<PurchaseApCheckItem> items = new ArrayList<PurchaseApCheckItem>();
		// 保存成功的同时来源单据更新一下
		List<SourceForApcheck> sources = new ArrayList<>();
		for (PurchaseApCheckItem item : purchaseApCheck.getItems()) {
			SourceForApcheck source = new SourceForApcheck(item);
			sources.add(source);
			item.setNumber(++number);
			item.setApCheck(purchaseApCheck);
			items.add(item);
		}
		updateSourceInfo(sources);
		purchaseApCheckItemDao.save(items);
		// TODO 把items转成主记录的形式
		return purchaseApCheck;
	}

	public boolean updateSourceInfo(List<SourceForApcheck> list) {
		if (!CollectionUtils.isEmpty(list)) {
			for (SourceForApcheck source : list) {
				if (source.hasInfo()) {
					String idName = null;
					String yCheckQtyName = null;
					if (source.getSourcetable().equals("purc$returnitem")) {
						idName = "pri_id";
						yCheckQtyName = "pri_ycheckqty";
					} else if (source.getSourcetable().equals("purc$acceptitem")) {
						idName = "pai_id";
						yCheckQtyName = "pai_ycheckqty";
					} else if (source.getSourcetable().equals("purc$badinitem")) {
						idName = "pbi_id";
						yCheckQtyName = "pbi_ycheckqty";
					} else if (source.getSourcetable().equals("purc$badoutitem")) {
						idName = "poi_id";
						yCheckQtyName = "poi_ycheckqty";
					} else if (source.getSourcetable().equals("make$acceptitem")) {
						idName = "mai_id";
						yCheckQtyName = "mai_ycheckqty";
					} else if (source.getSourcetable().equals("make$returnitem")) {
						idName = "mri_id";
						yCheckQtyName = "mri_ycheckqty";
					} else if (source.getSourcetable().equals("purc$apbilladjustment")) {
						idName = "aa_id";
						yCheckQtyName = "aa_ycheckqty";
					}
					String sql = "update " + source.getSourcetable() + " set " + yCheckQtyName + " = "
							+ source.getNewYCheckQty() + " where " + idName + " = " + source.getSourceid();
					jdbcTemplate.execute(sql);
				} else {
					throw new IllegalOperatorException("保存失败！");
				}
			}
			return true;
		}
		throw new IllegalOperatorException("保存失败！");
	}

}
