package net.wicp.tams.duckula.ops.pages.cas;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.util.TextStreamResponse;
import org.springframework.dao.DuplicateKeyException;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.app.duckula.controller.bean.constant.OptGroupStatus;
import net.wicp.tams.app.duckula.controller.bean.models.SysOptgroup;
import net.wicp.tams.app.duckula.controller.bean.models.SysOptgroupExample;
import net.wicp.tams.app.duckula.controller.bean.models.SysOptitem;
import net.wicp.tams.app.duckula.controller.bean.models.SysOptitemExample;
import net.wicp.tams.app.duckula.controller.bean.models.SysOptitemExample.Criteria;
import net.wicp.tams.app.duckula.controller.dao.SysOptgroupMapper;
import net.wicp.tams.app.duckula.controller.dao.SysOptitemMapper;
import net.wicp.tams.cas.convert.ConvertValueOpt;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.CollectionUtil;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.apiext.json.EasyUiAssist;
import net.wicp.tams.common.apiext.json.JSONUtil;
import net.wicp.tams.common.apiext.json.easyuibean.EasyUINode;
import net.wicp.tams.common.apiext.json.easyuibean.EasyUINodeConf;
import net.wicp.tams.common.callback.IConvertValue;
import net.wicp.tams.common.callback.impl.convertvalue.ConvertValueEnum;
import net.wicp.tams.common.constant.dic.YesOrNo;
import net.wicp.tams.component.tools.TapestryAssist;
import net.wicp.tams.duckula.ops.convert.ConvertValueMyBatis;
import net.wicp.tams.duckula.ops.pages.ParentPage;
import net.wicp.tams.duckula.ops.pages.ParentPageBean;
import redis.clients.jedis.Jedis;

@Import(library = { "${path.jquery.plugin}/aop.min.js" })
@SuppressWarnings("all")
@Slf4j
public class OptionItemManager extends ParentPageBean<SysOptitem> {

	@Inject
	private SysOptitemMapper sysOptitemMapper;
	@Inject
	private SysOptgroupMapper sysOptgroupMapper;

	@Override
	public void packageQuery(SysOptitem t, QueryWrapper<SysOptitem> queryWrapper) {
		if (StringUtils.isNotBlank(t.getItemCode())) {
			queryWrapper.eq("item_code", t.getItemCode());
		}
		String itemName = request.getParameter("itemName");
		if (StringUtils.isNotBlank(itemName)) {
			String lan = supportedLocales.getCurLocale().getLanguage().substring(0, 1).toUpperCase()
					+ supportedLocales.getCurLocale().getLanguage().substring(1);
			if ("en".equals(lan)) {
				queryWrapper.eq("name_en", itemName);
			} else {
				queryWrapper.eq("name_zh", itemName);
			}
		}
		if (StringUtils.isNotBlank(t.getGroupCode())) {
			queryWrapper.eq("group_code", t.getGroupCode());
		}
		if (t.getParentId() != null) {
			queryWrapper.eq("parent_id", t.getParentId());
		}
		if (StringUtils.isNotBlank(t.getStatus())) {
			queryWrapper.eq("status", t.getStatus());
		}
	}

	@Override
	protected Pair<String[], Map<String, IConvertValue>> packageConvert() {
		String[] cols = new String[] { "status,status1", "groupCode,group1", getColLan("name"),
				"parentId,parentId1"};
		Map<String, IConvertValue> conv = new HashMap<String, IConvertValue>();
		conv.put("status1", new ConvertValueEnum(YesOrNo.class));
		conv.put("group1", new ConvertValueMyBatis(sysOptgroupMapper,"remark"));
		conv.put("parentId1", new ConvertValueMyBatis(sysOptitemMapper,"nameZh"));
		return Pair.of(cols, conv);
	}

	@Override
	public void doSave(SysOptitem t, boolean isInsert) {
		if (isInsert) {
			t.setCreateTime(new Date());
			sysOptitemMapper.insert(t);
		} else {
			//保留没有放到界面的信息
			SysOptitem oriObj = sysOptitemMapper.selectByPrimaryKey(t.getId());
			t.setCreateTime(oriObj.getCreateTime());
			sysOptitemMapper.updateByPrimaryKey(t);
		}
	}



	public TextStreamResponse onSaveGroup() {
		SysOptgroup group = TapestryAssist.getBeanFromPage(SysOptgroup.class, request);
		String isInsert = request.getParameter("isInsert");
		try {
			if("yes".equals(isInsert)) {
				sysOptgroupMapper.insert(group);
			}else {
				sysOptgroupMapper.updateByPrimaryKey(group);
				updateItemParentStatus(group.getId(),YesOrNo.yes);
			}
		}catch (DuplicateKeyException e) {
			return TapestryAssist.getTextStreamResponse(Result.getError("选项组编码重复,有可能这个编码被设置为废弃"));
		}
		return TapestryAssist.getTextStreamResponse(Result.getSuc());
	}

	@SetupRender
	void init() {

	}

	public TextStreamResponse onGroupTree() {
		List<SysOptgroup> groups = sysOptgroupMapper.selectByExample(new SysOptgroupExample());
		EasyUINodeConf conf = new EasyUINodeConf("id", "remark", "parentId");
		conf.setAttrCols("isEdit", "isValid");
		List<EasyUINode> roots = new ArrayList<>();
		try {
			roots = EasyUiAssist.getTreeRoot(groups, conf);
		} catch (Exception e) {
		}
		return TapestryAssist.getTextStreamResponse(EasyUiAssist.getTreeFromList(roots));
	}

	public TextStreamResponse onDelGroup() {
		String groupId = request.getParameter("groupId");		
		QueryWrapper<SysOptgroup> queryWrapper=new QueryWrapper<SysOptgroup>();
		queryWrapper.eq("parent_id", groupId);
		Integer count = sysOptgroupMapper.selectCount(queryWrapper);
		if(count>0) {
			return TapestryAssist.getTextStreamResponse(Result.getError("此组下面有子组，不允许删除。"));
		}		
		SysOptgroup group = new SysOptgroup();
		group.setIsValid(YesOrNo.no.name());
		group.setId(groupId);
		sysOptgroupMapper.updateByPrimaryKeySelective(group);
		
		updateItemParentStatus(groupId,YesOrNo.no);
		
		return TapestryAssist.getTextStreamResponse(Result.getSuc());
	}

	private void updateItemParentStatus(String groupId,YesOrNo status) {
		//删除item相关
		SysOptitemExample sysOptitemExample=new SysOptitemExample();
		Criteria criteria = sysOptitemExample.createCriteria();
		criteria.andGroupCodeEqualTo(groupId);		
		SysOptitem record=new SysOptitem();
		record.setStatusParent(status.name());
		sysOptitemMapper.updateByExampleSelective(record, sysOptitemExample);
	}

	/***
	 * 移动组要做的动作： 1、修改组缓存、旧parentIdOld的optionsubs删除选项、optionitem重新put 2、修改组父信息
	 * 3、把组下所有的opt字段设置为： parentId='',parentIdOld=parentId,parentStatus='MOV' 、
	 * 
	 * @return
	 */
	public TextStreamResponse onDragGroup() {
		String sourceId = request.getParameter("sourceId");
		String targetId = request.getParameter("targetId");
		// 1、修改组缓存、旧parentIdOld的optionsubs删除选项、optionitem重新put
		SysOptgroup optGroup = sysOptgroupMapper.selectByPrimaryKey(sourceId);
		optGroup.setParentId(targetId);
		sysOptgroupMapper.updateByPrimaryKey(optGroup);// 2、修改组父信息
		List<SysOptitem> alllist = sysOptitemMapper
				.selectByMap(CollectionUtil.newMap("group_code", sourceId));
		for (SysOptitem optionitem : alllist) {
			SysOptitem newobj =null;
			try {
				newobj = (SysOptitem) BeanUtils.cloneBean(optionitem);
				newobj.setParentId(null);
			} catch (Exception e) {
				log.error("移动时修改对应item错误",e);
				return TapestryAssist.getTextStreamResponse(Result.getSuc());
			}
			
			if(optionitem.getParentId()==null) {//一种是曾经有parent但被移除了，另一种是从来就没有parent
				if(optionitem.getParentIdOld()!=null) {//曾经有parent但被移除了
					SysOptitem parentOld = sysOptitemMapper.selectByPrimaryKey(optionitem.getParentIdOld());
					if(parentOld.getGroupCode().equals(targetId)) {//刚好移到之前的group下,恢复
						newobj.setParentId(optionitem.getParentIdOld());
						newobj.setParentIdOld(null);
					}
				}
			}else {//防止两次移动冲掉此项，parent不为空,设置为ParentIdOld为parent的值
				newobj.setParentId(null);
				newobj.setParentIdOld(optionitem.getParentId());
			}
			sysOptitemMapper.updateByPrimaryKey(newobj);
		}
		return TapestryAssist.getTextStreamResponse(Result.getSuc());
	}

	public TextStreamResponse onQueryGroup() {
		List<SysOptgroup> groups = sysOptgroupMapper.selectByExample(new SysOptgroupExample());
		
		EasyUINodeConf conf = new EasyUINodeConf("id", "remark", "parentId");
		conf.setFieldCols("isEdit", "isValid");
		String str ="";
		try {
			List<EasyUINode> treeRoot = EasyUiAssist.getTreeRoot(groups, conf);
			str = EasyUiAssist.getTreeFromList(treeRoot);
		} catch (Exception e) {
			log.error("组装选项组树失败");
		}
		return TapestryAssist.getTextStreamResponse(str);
	}

	public TextStreamResponse onQueryParentGroup() {
		String groupid = request.getParameter("parent");
		List<SysOptitem> optlist=new ArrayList<SysOptitem>();
		if(StringUtil.isNotNull(groupid)) {
			SysOptgroup group = sysOptgroupMapper.selectById(groupid);
			if(StringUtil.isNotNull(group.getParentId())) {
				optlist = sysOptitemMapper.selectByMap(CollectionUtil.newMap("group_code",group.getParentId()));
			}			
		}
		Map<String, IConvertValue<String>> conv = new HashMap<String, IConvertValue<String>>();
		conv.put("status1", new ConvertValueEnum(YesOrNo.class));
		// conv.put("group1", new ConvertValueOpt(supportedLocales));
		String str = JSONUtil.getJsonForListAlias(optlist,new String[] { "status,status1", "groupCode,group1" },
				conv);
		return TapestryAssist.getTextStreamResponse(str);
	}
	
	

	
	


	@Override
	public void doDel(String id) {
		
	}

	@Override
	public BaseMapper<SysOptitem> getBaseMapper() {
		return this.sysOptitemMapper;
	}

}
