package com.prolog.rdc.tms.service.impl;

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

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.prolog.common.util.ToolKits;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Order;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.product.core.framework.entity.UserEntity;
import com.prolog.product.core.framework.util.PlgFxUsrUtils;
import com.prolog.rdc.tms.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.constant.SeriaNnumberConstant;
import com.prolog.rdc.tms.dao.mapper.SysQueryConfigurationDtlMapper;
import com.prolog.rdc.tms.dao.mapper.SysQueryConfigurationHdrMapper;
import com.prolog.rdc.tms.model.dto.ConfigurationQueryDDTO;
import com.prolog.rdc.tms.model.dto.ConfigurationQueryDTO;
import com.prolog.rdc.tms.model.dto.SysRefdatadDTO;
import com.prolog.rdc.tms.model.entity.SysQueryCfgDtlModel;
import com.prolog.rdc.tms.model.entity.SysQueryCfgHdrModel;
import com.prolog.rdc.tms.model.vo.ConfigurationDAddVO;
import com.prolog.rdc.tms.model.vo.ConfigurationHDeleteVO;
import com.prolog.rdc.tms.model.vo.ConfigurationHSaveVO;
import com.prolog.rdc.tms.model.vo.ConfigurationHSetVO;
import com.prolog.rdc.tms.model.vo.ConfigurationQueryVO;
import com.prolog.rdc.tms.model.vo.SysRefdatadQueryVO;
import com.prolog.rdc.tms.service.SysCodeengineService;
import com.prolog.rdc.tms.service.SysQueryConfigurationService;
import com.prolog.rdc.tms.service.SysRefdatadService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class SysQueryConfigurationServiceImpl implements SysQueryConfigurationService {

	@Autowired
	private SysQueryConfigurationHdrMapper sysQueryConfigurationHdrMapper;
	@Autowired
	private SysQueryConfigurationDtlMapper sysQueryConfigurationDtlMapper;
	@Autowired
	private SysCodeengineService sysCodeengineService;
	@Autowired
	private SysRefdatadService sysRefdatadService;

	/**
	 * 查询汇总
	 *
	 * @param configurationQueryVO
	 * @return
	 */
	@Override
	public List<ConfigurationQueryDTO> queryConfigurationH(ConfigurationQueryVO configurationQueryVO) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		if (ToolKits.isEmpty(user)) {
			throw new PrologException("当前用户无权限");
		}
		if (ToolKits.isEmpty(configurationQueryVO)) {
			throw new PrologException("请求参数不能为空");
		}
		configurationQueryVO.setEnterpriseId(user.getEnterpriseId());
		List<ConfigurationQueryDTO> list = sysQueryConfigurationHdrMapper.queryConfigurationH(configurationQueryVO);
		return list;
	}

	/**
	 * 保存
	 *
	 * @param configurationHSaveVOs
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveConfiguration(List<ConfigurationHSaveVO> configurationHSaveVOs) {
		ToolKits.isParamNull(configurationHSaveVOs, "请求参数不能为空");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前用户无权限");

		Date date = DateUtil.date();
		List<SysQueryCfgHdrModel> hdrs = new ArrayList<SysQueryCfgHdrModel>();
		for (ConfigurationHSaveVO configurationHSaveVO : configurationHSaveVOs) {
			if (ToolKits.isEmpty(configurationHSaveVO)) {
				throw new PrologException("汇总数据不能为空");
			}
			List<ConfigurationDAddVO> configurationDAddVOs = configurationHSaveVO.getDetails();
			if (ToolKits.isEmpty(configurationDAddVOs)) {
				throw new PrologException("明细数据不能为空");
			}
			SysQueryCfgHdrModel hdr = sysQueryConfigurationHdrMapper.findById(configurationHSaveVO.getId(), SysQueryCfgHdrModel.class);
			if (ToolKits.isEmpty(hdr)) {
				hdr = new SysQueryCfgHdrModel();
				String id = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.SYS_QUERY_CONFIGURATION_H_ID, "L");
				if (ToolKits.isEmpty(id)) {
					throw new PrologException("汇总id获取失败");
				}
				hdr.setId(id);
				hdr.setBizType(configurationHSaveVO.getBizType());
				hdr.setBizName(configurationHSaveVO.getBizName());
				if (ObjectUtil.isEmpty(configurationHSaveVO.getDefaultFlag())) {
					if (ObjectUtil.isNotEmpty(hdrs)) {
						SysQueryCfgHdrModel hdr1 = hdrs.stream().filter(h -> "1".equals(h.getDefaultFlag())).findAny().orElse(null);
						if (ObjectUtil.isEmpty(hdr1)) {
							hdr.setDefaultFlag("1");
						} else {
							hdr.setDefaultFlag("0");
						}
					} else if (configurationHSaveVOs.size() == 1) {
						hdr.setDefaultFlag("1");
					} else {
						hdr.setDefaultFlag("0");
					}
				} else {
					hdr.setDefaultFlag(configurationHSaveVO.getDefaultFlag());
				}
				hdr.setCreateby(user.getNickname());
				hdr.setCreatedate(date);
				hdr.setEnterpriseId(user.getEnterpriseId());
				hdr.setEnterpriseName(user.getEnterpriseName());
				hdrs.add(hdr);
				saveDtl(configurationDAddVOs, user, hdr.getId());
			} else {
				BeanUtils.copyProperties(configurationHSaveVO, hdr);
				hdr.setLastmodifyby(user.getNickname());
				hdr.setLastmodifydate(date);
				saveDtl(configurationDAddVOs, user, hdr.getId());
				sysQueryConfigurationHdrMapper.update(hdr);
			}
		}
		if (ToolKits.isNotEmpty(hdrs)) {
			sysQueryConfigurationHdrMapper.saveBatch(hdrs);
		}
	}

	public void saveDtl(List<ConfigurationDAddVO> configurationDAddVOs, UserEntity user, String hId) {
		// 明细
		List<SysQueryCfgDtlModel> dtls = new ArrayList<SysQueryCfgDtlModel>();
		for (ConfigurationDAddVO configurationDAddVO : configurationDAddVOs) {
			SysQueryCfgDtlModel dtl = sysQueryConfigurationDtlMapper.findById(configurationDAddVO.getSeqId(), SysQueryCfgDtlModel.class);
			if (ToolKits.isEmpty(dtl)) {
				if (ToolKits.isEmpty(configurationDAddVO)) {
					throw new PrologException("明细数据不能为空");
				}
				if (ToolKits.isEmpty(configurationDAddVO.getFieldCode())) {
					throw new PrologException("字段编码不能为空");
				}
				if (ToolKits.isEmpty(configurationDAddVO.getFieldName())) {
					throw new PrologException("字段名称不能为空");
				}
				if (ToolKits.isEmpty(configurationDAddVO.getFieldType())) {
					throw new PrologException("字段类型不能为空");
				}
				if (ToolKits.isEmpty(configurationDAddVO.getOperationSymbol())) {
					throw new PrologException("操作符不能为空");
				}
				if (ToolKits.isEmpty(configurationDAddVO.getFieldValue())) {
					throw new PrologException("字段值不能为空");
				}
				if (ToolKits.isEmpty(configurationDAddVO.getSeqNo())) {
					throw new PrologException("明细序号不能为空");
				}
				dtl = new SysQueryCfgDtlModel();
				String seqId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.SYS_QUERY_CONFIGURATION_D_ID, "L");
				if (ToolKits.isEmpty(seqId)) {
					throw new PrologException("明细id获取失败");
				}
				dtl.setSeqId(seqId);
				dtl.setSeqNo(Integer.valueOf(seqId));
				dtl.setHdrId(hId);
				dtl.setFieldCode(configurationDAddVO.getFieldCode());
				dtl.setFieldName(configurationDAddVO.getFieldName());
				dtl.setFieldType(configurationDAddVO.getFieldType());
				dtl.setLogicSymbol(configurationDAddVO.getLogicSymbol());
				dtl.setOperationSymbol(configurationDAddVO.getOperationSymbol());
				dtl.setFieldValue(configurationDAddVO.getFieldValue());
				dtl.setCreateby(user.getNickname());
				dtl.setCreatedate(new Date());
				dtl.setEnterpriseId(user.getEnterpriseId());
				dtl.setEnterpriseName(user.getEnterpriseName());
				dtls.add(dtl);
			} else {
				if (ToolKits.isEmpty(configurationDAddVO)) {
					throw new PrologException("明细数据不能为空");
				}
				if (ToolKits.isEmpty(configurationDAddVO.getFieldCode())) {
					throw new PrologException("字段编码不能为空");
				}
				if (ToolKits.isEmpty(configurationDAddVO.getFieldName())) {
					throw new PrologException("字段名称不能为空");
				}
				if (ToolKits.isEmpty(configurationDAddVO.getFieldType())) {
					throw new PrologException("字段类型不能为空");
				}
				if (ToolKits.isEmpty(configurationDAddVO.getOperationSymbol())) {
					throw new PrologException("操作符不能为空");
				}
				if (ToolKits.isEmpty(configurationDAddVO.getFieldValue())) {
					throw new PrologException("字段值不能为空");
				}
				if (ToolKits.isEmpty(configurationDAddVO.getSeqNo())) {
					throw new PrologException("明细序号不能为空");
				}
				BeanUtils.copyProperties(configurationDAddVO, dtl);
				dtl.setHdrId(hId);
				dtl.setLastmodifyby(user.getNickname());
				dtl.setLastmodifydate(new Date());
				sysQueryConfigurationDtlMapper.update(dtl);
			}
		}
		if (ToolKits.isNotEmpty(dtls)) {
			sysQueryConfigurationDtlMapper.saveBatch(dtls);
		}
	}

	/**
	 * 删除汇总
	 *
	 * @param configurationHDeleteVO
	 * @return
	 */
	@Override
	public void deleteConfigurationH(ConfigurationHDeleteVO configurationHDeleteVO) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		if (ToolKits.isEmpty(user)) {
			throw new PrologException("当前用户无权限");
		}
		if (ToolKits.isEmpty(configurationHDeleteVO)) {
			throw new PrologException("请求参数不能为空");
		}
		if (ToolKits.isEmpty(configurationHDeleteVO.getId())) {
			throw new PrologException("ID不能为空");
		}
		// 删除汇总
		sysQueryConfigurationHdrMapper.deleteById(configurationHDeleteVO.getId(), SysQueryCfgHdrModel.class);

		// 删除明细
		Criteria criteriaDtl = Criteria.forClass(SysQueryCfgDtlModel.class);
		Restriction r1 = Restrictions.eq("hId", configurationHDeleteVO.getId());
		Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		criteriaDtl.setRestriction(Restrictions.and(r1, r2));
		sysQueryConfigurationDtlMapper.deleteByCriteria(criteriaDtl);
	}

	/**
	 * 查询明细
	 *
	 * @param hId
	 * @return
	 */
	@Override
	public List<ConfigurationQueryDDTO> queryConfigurationD(String hId) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		if (ToolKits.isEmpty(user)) {
			throw new PrologException("当前用户无权限");
		}
		if (ToolKits.isEmpty(hId)) {
			throw new PrologException("请求参数不能为空");
		}
		List<ConfigurationQueryDDTO> list = sysQueryConfigurationDtlMapper.queryConfigurationD(hId);
		SysRefdatadQueryVO sysrefdatadqueryvo = new SysRefdatadQueryVO();
		String[] objectcodes = { DataDictionaryConstant.LOGIC_SYMBOL };
		sysrefdatadqueryvo.setObjectcodes(objectcodes);
		List<SysRefdatadDTO> sysrefdataddtos = new ArrayList<SysRefdatadDTO>();
		try {
			sysrefdataddtos = sysRefdatadService.getSysRefdatadData(sysrefdatadqueryvo);
		} catch (Exception e) {
			e.printStackTrace();
			throw new PrologException("获取数据字典失败");
		}
		for (ConfigurationQueryDDTO dto : list) {
			for (SysRefdatadDTO sysrefdataddto : sysrefdataddtos) {
				if (DataDictionaryConstant.LOGIC_SYMBOL.equals(sysrefdataddto.getObjectcode()) && sysrefdataddto.getCode().equals(dto.getLogicSymbol())) {
					dto.setLogicSymbolName(sysrefdataddto.getName());
				}
			}
		}
		return list;
	}

	/**
	 * 设为默认
	 *
	 * @param configurationHSetVO
	 * @return
	 */
	@Override
	public void setDefaultConfiguration(ConfigurationHSetVO configurationHSetVO) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		if (ToolKits.isEmpty(user)) {
			throw new PrologException("当前用户无权限");
		}
		if (ToolKits.isEmpty(configurationHSetVO)) {
			throw new PrologException("请求参数不能为空");
		}
		if (ToolKits.isEmpty(configurationHSetVO.getId())) {
			throw new PrologException("ID不能为空");
		}
		if (ToolKits.isEmpty(configurationHSetVO.getDefaultFlag())) {
			throw new PrologException("默认标识不能为空");
		}
		SysQueryCfgHdrModel sysQueryConfigurationHdr = sysQueryConfigurationHdrMapper.findById(configurationHSetVO.getId(), SysQueryCfgHdrModel.class);
		if (ToolKits.isEmpty(sysQueryConfigurationHdr)) {
			throw new PrologException("当前汇总配置未找到");
		}
		// 清除默认
		Criteria criteria = Criteria.forClass(SysQueryCfgHdrModel.class);
		Restriction r1 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		Restriction r2 = Restrictions.eq("defaultFlag", "1");
		Restriction r3 = Restrictions.eq("bizType", sysQueryConfigurationHdr.getBizType());
		Restriction r4 = Restrictions.ne("id", sysQueryConfigurationHdr.getId());
		criteria.setRestriction(Restrictions.and(r1, r2, r3, r4));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("defaultFlag", "0");
		sysQueryConfigurationHdrMapper.updateMapByCriteria(map, criteria);
		// 设置默认
		if (ObjectUtil.equal("0", sysQueryConfigurationHdr.getDefaultFlag())) {
			map.put("defaultFlag", "1");
			sysQueryConfigurationHdrMapper.updateMapById(sysQueryConfigurationHdr.getId(), map, SysQueryCfgHdrModel.class);
		}
	}

	/**
	 * 获取高级查询配置
	 *
	 * @param bizType
	 * @return
	 */
	@Override
	public String getQueryConfiguration(String bizType) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		if (ToolKits.isEmpty(user)) {
			throw new PrologException("当前用户无权限");
		}
		if (ToolKits.isEmpty(bizType)) {
			throw new PrologException("业务类型不能为空");
		}
		Criteria criteria = Criteria.forClass(SysQueryCfgHdrModel.class);
		Restriction r1 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		Restriction r2 = Restrictions.eq("defaultFlag", "1");
		Restriction r3 = Restrictions.eq("bizType", bizType);
		criteria.setRestriction(Restrictions.and(r1, r2, r3));
		List<SysQueryCfgHdrModel> hdrs = sysQueryConfigurationHdrMapper.findByCriteria(criteria);
		if (ToolKits.isEmpty(hdrs)) {
			return " 1=1 ";
		}
		Criteria criteriad = Criteria.forClass(SysQueryCfgDtlModel.class);
		Restriction rd1 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		Restriction rd2 = Restrictions.eq("hdrId", hdrs.get(0).getId());
		criteriad.setRestriction(Restrictions.and(rd1, rd2));
		criteriad.setOrder(Order.newInstance().asc("seqNo"));
		List<SysQueryCfgDtlModel> dtls = sysQueryConfigurationDtlMapper.findByCriteria(criteriad);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < dtls.size(); i++) {
			if (ToolKits.isNotEmpty(dtls.get(i).getLogicSymbol())) {
				if (dtls.get(i).getLogicSymbol().equals("or")) {
					dtls.get(i - 1).setLogicSymbol(" " + dtls.get(i - 1).getLogicSymbol() + " (");
					if (dtls.get(i).getOperationSymbol().indexOf("like") > 0) {
						dtls.get(i).setFieldValue(" '%" + dtls.get(i).getFieldValue() + "%') ");
					} else {
						if (dtls.get(i).getOperationSymbol().indexOf("null") > 0) {
							dtls.get(i).setFieldValue(") ");
						} else {
							dtls.get(i).setFieldValue(" '" + dtls.get(i).getFieldValue() + "') ");
						}
					}
				} else {
					dtls.get(i).setLogicSymbol(" " + dtls.get(i).getLogicSymbol() + " ");
					if (dtls.get(i).getOperationSymbol().indexOf("like") > 0) {
						dtls.get(i).setFieldValue(" '%" + dtls.get(i).getFieldValue() + "%' ");
					} else {
						if (dtls.get(i).getOperationSymbol().indexOf("null") > 0) {
							dtls.get(i).setFieldValue("");
						} else {
							dtls.get(i).setFieldValue(" '" + dtls.get(i).getFieldValue() + "' ");
						}
					}
				}
			} else {
				if (dtls.get(i).getOperationSymbol().indexOf("like") > 0) {
					dtls.get(i).setFieldValue(" '%" + dtls.get(i).getFieldValue() + "%' ");
				} else {
					if (dtls.get(i).getOperationSymbol().indexOf("null") > 0) {
						dtls.get(i).setFieldValue("");
					} else {
						dtls.get(i).setFieldValue(" '" + dtls.get(i).getFieldValue() + "' ");
					}
				}
			}
			dtls.get(i).setFieldCode(" " + dtls.get(i).getFieldCode().replaceAll("()([A-Z])", "$1_$2") + " ");
			dtls.get(i).setOperationSymbol(dtls.get(i).getOperationSymbol());
		}
		for (SysQueryCfgDtlModel dtlh : dtls) {
			sb.append(ToolKits.isEmpty(dtlh.getLogicSymbol()) ? "" : dtlh.getLogicSymbol()).append(dtlh.getFieldCode()).append(dtlh.getOperationSymbol()).append(dtlh.getFieldValue());
		}
		// sb.insert(0, "where");
		log.info("高级查询: " + sb.toString().toLowerCase());
		return sb.toString().toLowerCase();
	}

}
