package com.upyuns.platform.rs.website.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.upyuns.platform.rs.datacenter.entity.RscpMonitorimage;
import com.upyuns.platform.rs.website.dto.ImageInformationStorageDto;
import com.upyuns.platform.rs.website.dto.ImageStorageImgDto;
import com.upyuns.platform.rs.website.entity.ImageInfoRelation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.upyuns.platform.rs.website.entity.ImageImgStorage;
import com.upyuns.platform.rs.website.mapper.ImageImgStorageMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * 影像图库
 *
 * @author jiaoruizhen
 * @email jiaoruizhen@126.com
 * @date 2020-11-28 14:15:32
 */
@Service
public class ImageImgStorageBiz extends BaseBiz<ImageImgStorageMapper,ImageImgStorage> {

	@Autowired
	ImageInfoRelationBiz imageInfoRelationBiz;

	@Autowired
	ShoppingCartInfoBiz shoppingCartInfoBiz;

	@Autowired
	ImageimgMenuBiz imageimgMenuBiz;

	/**
	 * 新增或者编辑图像库信息
	 * @param imageImgStorage
	 * @return
	 */
	public ObjectRestResponse addUpdate(ImageImgStorage imageImgStorage) {
		if (imageImgStorage == null) {
			return ObjectRestResponse.paramIsEmpty();
		}
//		//如果是url 则转存
//		if(imageImgStorage.getUptype() == ImageImgStorage.UPTYPE_URL) {
//			imageImgStorage.getCoverImg()
//
//		}
		if (imageImgStorage.getId() == null) {
			insertSelectiveRe(imageImgStorage);
			if (imageImgStorage.getImageInfoRelationList() != null && imageImgStorage.getImageInfoRelationList().size() > 0) {
				imageImgStorage.getImageInfoRelationList().stream().forEach(imageInfoRelation -> {
					imageInfoRelation.setType(1);
					imageInfoRelation.setRelationId(imageImgStorage.getId());
					imageInfoRelationBiz.addUpdate(imageInfoRelation);
				});
			}
		} else {
			ImageImgStorage old = selectById(imageImgStorage.getId());
			if (old == null) {
				return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
			} else {
				BeanUtil.copyProperties(imageImgStorage, old, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
				updateSelectiveByIdRe(old);
				if (imageImgStorage.getIsDel() != null) {
					shoppingCartInfoBiz.updateObj(old.getId(), null, imageImgStorage.getIsDel());
				}
			}
			imageInfoRelationBiz.deleteAll(old.getId());
			if (old.getImageInfoRelationList() != null && old.getImageInfoRelationList().size() > 0) {
				old.getImageInfoRelationList().stream().forEach(imageInfoRelation -> {
					imageInfoRelation.setType(1);
					imageInfoRelation.setRelationId(old.getId());
					imageInfoRelationBiz.addUpdate(imageInfoRelation);
				});
			}
		}
		return ObjectRestResponse.succ();
	}

	/**
	 * 更新状态 上下架
	 * @param imageImgStorage
	 * @return
	 */
	public ObjectRestResponse updateStatus(ImageImgStorage imageImgStorage) {
		ImageImgStorage old = selectById(imageImgStorage.getId());
		if (old == null) {
			return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
		} else {
			BeanUtil.copyProperties(imageImgStorage, old, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
			updateSelectiveByIdRe(old);
			List<ImageInfoRelation> imageInfoRelationList = imageInfoRelationBiz.getAllById(imageImgStorage.getId(), 1);
			if (imageInfoRelationList != null && imageInfoRelationList.size() > 0) {
				imageInfoRelationList.parallelStream().forEach(imageInfoRelation -> {
					shoppingCartInfoBiz.updateObj(imageInfoRelation.getId(), imageImgStorage.getStatus(), null);
				});
			}
		}
		return ObjectRestResponse.succ();
	}

	/**
	 * 分页查询图像库信息
	 * @param imageInformationStorageDto
	 * @return
	 */
	public ObjectRestResponse selectList(ImageInformationStorageDto imageInformationStorageDto, Integer sort) {
		Example example = new Example(ImageImgStorage.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("isDel", 0);
		if (imageInformationStorageDto.getStatus() != null) {
			criteria.andEqualTo("status", imageInformationStorageDto.getStatus());
		}
		if (imageInformationStorageDto.getType() != null) {
			criteria.andEqualTo("type", imageInformationStorageDto.getType());
		}
		if (StringUtils.isNotBlank(imageInformationStorageDto.getName())) {
			criteria.andLike("name", "%" + imageInformationStorageDto.getName() + "%");
		}

		if(StrUtil.isNotBlank(imageInformationStorageDto.getMenuIds())) {
			criteria.andIn("menuId", imageimgMenuBiz.getIdsByTopId(
					Integer.valueOf(imageInformationStorageDto.getMenuIds())));
		}
		if (sort == 1) {
			example.orderBy("updTime").desc();
		} else {
			example.orderBy("rank");
		}
		Query query = new Query(imageInformationStorageDto);
		PageDataVO<ImageImgStorage> pageDataVO = PageDataVO.pageInfo(query, () -> mapper.selectByExample(example));
		if (pageDataVO != null && pageDataVO.getData() != null) {
			pageDataVO.getData().stream().forEach(imageImgStorage -> {
				List<ImageInfoRelation> imageInfoRelationList = imageInfoRelationBiz.getAllById(imageImgStorage.getId(), 1);
				if (imageInfoRelationList != null) {
					imageImgStorage.setImageInfoRelationList(imageInfoRelationList);
				}
				if (StringUtils.isNotBlank(imageImgStorage.getRelatedIds())) {
					imageImgStorage.setSimilarImageList(getListByIds(imageImgStorage.getRelatedIds()));
				}
			});
		}
		return ObjectRestResponse.succ(pageDataVO);
	}

	public List<ImageImgStorage> getListByIds(String ids) {
		List<ImageImgStorage> list = new ArrayList<>();
		String[] arr = ids.split(",");
		if (arr != null) {
			for (String id : arr) {
				if (StringUtils.isNotBlank(id)) {
					ImageImgStorage imageImgStorage = selectById(Integer.valueOf(id));
					if (imageImgStorage != null && imageImgStorage.getIsDel() == 0 && imageImgStorage.getStatus() == 1) {
						List<ImageInfoRelation> imageInfoRelationList = imageInfoRelationBiz.getAllById(imageImgStorage.getId(), 1);
						if (imageInfoRelationList != null) {
							imageImgStorage.setImageInfoRelationList(imageInfoRelationList);
						}
						list.add(imageImgStorage);
					}
				}
			}
		}
		return list;
	}

	/**
	 * 查询详情信息
	 * @param id
	 * @return
	 */
	public ObjectRestResponse<ImageImgStorage> getDetail(Integer id) {
		if (id == null) {
			return ObjectRestResponse.paramIsEmpty();
		}
		ImageImgStorage imageImgStorage = selectById(id);
		if (imageImgStorage == null) {
			ImageInfoRelation imageInfoRelation = imageInfoRelationBiz.selectById(id);
			if (imageInfoRelation == null) {
				return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
			}
			imageImgStorage = selectById(imageInfoRelation.getRelationId());
			if (imageImgStorage == null) {
				return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
			}
		}
		List<ImageInfoRelation> imageInfoRelationList = imageInfoRelationBiz.getAllById(id, 1);
		if (imageInfoRelationList != null) {
			imageImgStorage.setImageInfoRelationList(imageInfoRelationList);
		}
		if (StringUtils.isNotBlank(imageImgStorage.getRelatedIds())) {
			imageImgStorage.setSimilarImageList(getListByIds(imageImgStorage.getRelatedIds()));
		}
		return ObjectRestResponse.succ(imageImgStorage);
	}

	public ObjectRestResponse<List<ImageImgStorage>> getAll(Integer type, String name) {
		Example example = new Example(ImageImgStorage.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("isDel", 0).andEqualTo("status", 1);
		if (type != null) {
			criteria.andEqualTo("type", type);
		}
		if (StringUtils.isNotBlank(name)) {
			criteria.andLike("name", "%" + name + "%");
		}
		example.orderBy("updTime").desc();
		List<ImageImgStorage> list = mapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			list.stream().forEach(imageImgStorage -> {
				List<ImageInfoRelation> imageInfoRelationList = imageInfoRelationBiz.getAllById(imageImgStorage.getId(), 1);
				if (imageInfoRelationList != null) {
					imageImgStorage.setImageInfoRelationList(imageInfoRelationList);
				}
				if (StringUtils.isNotBlank(imageImgStorage.getRelatedIds())) {
					imageImgStorage.setSimilarImageList(getListByIds(imageImgStorage.getRelatedIds()));
				}
			});
		}
		return ObjectRestResponse.succ(list);
	}

	/**
	 * 根据ID List 获取所有图库信息
	 * @param idList
	 * @return
	 */
	public List<ImageImgStorage> getAllByIds(Set<Integer> idList) {
		Example example = new Example(ImageImgStorage.class);
		example.createCriteria().andIn("id", idList);
		return mapper.selectByExample(example);
	}

	/**
	 * 批量更新或者批量删除
	 * @param imageStorageImgDto
	 * @return
	 */
	public ObjectRestResponse updateBatch(ImageStorageImgDto imageStorageImgDto) {
		if (imageStorageImgDto == null || StringUtils.isBlank(imageStorageImgDto.getIds())) {
			return ObjectRestResponse.paramIsEmpty();
		}
		String[] arr = imageStorageImgDto.getIds().split(",");
		if (arr != null) {
			Example example = new Example(ImageImgStorage.class);
			example.createCriteria().andIn("id", Arrays.asList(arr)).andEqualTo("isDel", 0);
			List<ImageImgStorage> imageImgStorageList = mapper.selectByExample(example);
			if (imageImgStorageList != null && imageImgStorageList.size() > 0) {
				imageImgStorageList.parallelStream().forEach(imageImgStorage -> {
					if (imageStorageImgDto.getStatus() != null) {
						imageImgStorage.setStatus(imageStorageImgDto.getStatus());
						List<ImageInfoRelation> imageInfoRelationList = imageInfoRelationBiz.getAllById(imageImgStorage.getId(), 1);
						if (imageInfoRelationList != null && imageInfoRelationList.size() > 0) {
							imageInfoRelationList.parallelStream().forEach(imageInfoRelation -> {
								shoppingCartInfoBiz.updateObj(imageInfoRelation.getId(), imageImgStorage.getStatus(), null);
							});
						}
					}
					if (imageStorageImgDto.getIsDel() != null) {
						imageImgStorage.setIsDel(imageStorageImgDto.getIsDel());
						List<ImageInfoRelation> imageInfoRelationList = imageInfoRelationBiz.getAllById(imageImgStorage.getId(), 1);
						if (imageInfoRelationList != null && imageInfoRelationList.size() > 0) {
							imageInfoRelationList.parallelStream().forEach(imageInfoRelation -> {
								shoppingCartInfoBiz.updateObj(imageInfoRelation.getId(), null, imageImgStorage.getIsDel());
							});
						}
					}
				});
				mapper.batchSave(imageImgStorageList);
			}
		}
		return ObjectRestResponse.succ();
	}

    public ObjectRestResponse mapAll(ImageInformationStorageDto dto) {
        Example example = new Example(ImageImgStorage.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDel",0);
        criteria.andEqualTo("status",1);
        example.setOrderByClause("crt_time DESC");
        PageDataVO pageDataVO = PageDataVO.pageInfo(dto.getPage(), dto.getLimit(), ()->selectByExample(example));
        return ObjectRestResponse.succ(pageDataVO);
    }

        public ObjectRestResponse all(ImageInformationStorageDto dto) {
            Example example = new Example(ImageImgStorage.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("isDel",0);
            criteria.andEqualTo("status",1);
            example.setOrderByClause("hot DESC");
            PageDataVO pageDataVO = PageDataVO.pageInfo(dto.getPage(), dto.getLimit(), ()->selectByExample(example));
            return ObjectRestResponse.succ(pageDataVO);
        }
}