package com.artfess.sysConfig.persistence.manager.impl;

import com.artfess.base.feign.SystemConfigFeignService;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.StringUtil;
import com.artfess.base.util.UniqueIdUtil;
import com.artfess.sysConfig.persistence.dao.BpmApprovalItemDao;
import com.artfess.sysConfig.persistence.manager.BpmApprovalItemManager;
import com.artfess.sysConfig.persistence.model.BpmApprovalItem;
import com.artfess.uc.api.impl.util.ContextUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.http.client.ClientProtocolException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * 常用语管理
 *
 * @company 阿特菲斯信息技术有限公司
 * @author heyifan
 * @email heyf@jee-soft.cn
 * @date 2020年4月15日
 */
@Service("bpmApprovalItemManager")
public class BpmApprovalItemManagerImpl extends BaseManagerImpl<BpmApprovalItemDao, BpmApprovalItem> implements BpmApprovalItemManager {
	@Resource
	SystemConfigFeignService systemConfigFeignService;

	@Override
    @Transactional
	public void addTaskApproval(BpmApprovalItem bpmApprovalItem) throws Exception {
		short type = bpmApprovalItem.getType();
		String curUserId = ContextUtil.getCurrentUserId();
		String[] expressions={StringUtil.join(bpmApprovalItem.getExpression().split("\n"), "")};
		if(type == 1 || type ==4){
			for (String expression : expressions) {
				if (StringUtil.isNotEmpty(expression)) {
                    if(getCount(expression,type,bpmApprovalItem.getId())){
                        bpmApprovalItem.setUpdateTime(LocalDateTime.now());
                        baseMapper.updateById(bpmApprovalItem);
                        return;
                    }
					BpmApprovalItem approvalItem = new BpmApprovalItem();
					approvalItem.setId(UniqueIdUtil.getSuid());
					approvalItem.setType(type);
					approvalItem.setExpression(expression);
					approvalItem.setUserId(curUserId);
                    approvalItem.setUpdateTime(LocalDateTime.now());
					baseMapper.insert(approvalItem);
				}

			}
		}else if(type == 2) {
			if(StringUtil.isEmpty(bpmApprovalItem.getTypeId()))return;
			String[] typeIds = bpmApprovalItem.getTypeId().split(",");
			for (String typeId : typeIds) {
				for (String expression : expressions) {
					if (StringUtil.isNotEmpty(expression)) {
						BpmApprovalItem approvalItem = new BpmApprovalItem();
						approvalItem.setId(UniqueIdUtil.getSuid());
						approvalItem.setType(type);
						approvalItem.setTypeId(typeId);
						approvalItem.setExpression(expression);
						approvalItem.setUserId(curUserId);
						approvalItem.setDefName(systemConfigFeignService.getSysTypeById(typeId).get("name").asText());
                        approvalItem.setUpdateTime(LocalDateTime.now());
						baseMapper.insert(approvalItem);
					}
				}
			}

		}else if(type == 3) {
			if(StringUtil.isEmpty(bpmApprovalItem.getDefKey()))return;
			String[] defKeys = bpmApprovalItem.getDefKey().split(",");
			String names = bpmApprovalItem.getDefName();
			String[] defNames = names.split(",");
			for (int i=0;i<defKeys.length;i++) {
				for (String expression : expressions) {
					if (StringUtil.isNotEmpty(expression)) {
						BpmApprovalItem approvalItem = new BpmApprovalItem();
						approvalItem.setId(UniqueIdUtil.getSuid());
						approvalItem.setType(type);
						approvalItem.setDefKey(defKeys[i]);
						approvalItem.setExpression(expression);
						approvalItem.setDefName(defNames[i]);
						approvalItem.setUserId(curUserId);
                        approvalItem.setUpdateTime(LocalDateTime.now());
						baseMapper.insert(approvalItem);
					}
				}
			}
		}
		if(StringUtil.isNotEmpty(bpmApprovalItem.getId())){
			baseMapper.deleteById(bpmApprovalItem.getId());
		}

	}

    private Boolean getCount(String expression,int type,String id) throws Exception{
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("expression_",expression);
        wrapper.eq("type_",type);
        Boolean falg = false;
        BpmApprovalItem bpmApprovalItem = baseMapper.selectOne(wrapper);
        if(BeanUtils.isNotEmpty(bpmApprovalItem) && StringUtil.isEmpty(id)){//新增时 传入的ID为空，但是查询结果不为空
            throw new RuntimeException("常用语【"+expression+"】已存在");
        }
        if(BeanUtils.isNotEmpty(bpmApprovalItem) &&
                StringUtil.isNotEmpty(id) && !id.equals(bpmApprovalItem.getId())){//修改时 传入的ID不为空，查询结果不为空且ID不相等 则不可以修改
            throw new RuntimeException("常用语【"+expression+"】已存在");
        }
        if(BeanUtils.isNotEmpty(bpmApprovalItem) &&
                StringUtil.isNotEmpty(id) && id.equals(bpmApprovalItem.getId())){//修改时 传入的ID不为空，查询结果不为空且ID相等 则可以修改
            falg = true;
        }
        if(BeanUtils.isEmpty(bpmApprovalItem) && StringUtil.isNotEmpty(id)){//修改时 传入的ID不为空，查询结果为空 则可以修改
            falg = true;
        }
        return falg;
    }


	/**
	 * 取流程常用语。
	 * @param defKey	流程定义Key。
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	@Override
	public List<String> getApprovalByDefKeyAndTypeId(String defKey,String typeId,String userId) throws ClientProtocolException, IOException{
        List<String> taskAppItemsList = new ArrayList<String>();
        String curUserId = StringUtil.isNotEmpty(userId)?userId:ContextUtil.getCurrentUserId();
        //获取本人的常用语,应用端新增的
        List<BpmApprovalItem> taskAppItem1=baseMapper.getByDefKeyAndUserAndSys(defKey,curUserId);
        //获取分类为4的所有的常用语,指定流程分类的
        List<BpmApprovalItem> taskAppItem2=baseMapper.getItemByType(BpmApprovalItem.TYPE_GLOBAL);

        if (BeanUtils.isNotEmpty(taskAppItem1)) {
            for(BpmApprovalItem taskAppItem:taskAppItem1){
                taskAppItemsList.add(taskAppItem.getExpression());
            }
        }
        if (BeanUtils.isNotEmpty(taskAppItem2)) {
            for(BpmApprovalItem taskAppItem:taskAppItem2){
                Boolean falg = true;
                //去除重复的元素
                for(BpmApprovalItem entity:taskAppItem1){
                    if(entity.getExpression().equals(taskAppItem.getExpression())){
                        falg = false;
                        break;
                    }
                }
                if(falg){
                    taskAppItemsList.add(taskAppItem.getExpression());
                }
            }
        }
        return taskAppItemsList;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void removeDuplicate (List<?> list){
		  HashSet h = new HashSet(list);
	      list.clear();
	      list.addAll(h);
	}

}
