package com.yd.api.agms.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.yd.api.agms.service.AgmsTagService;
import com.yd.api.agms.vo.tag.TagUpdateRequestVO;
import com.yd.api.agms.vo.tag.TagUpdateResponseVO;
import com.yd.api.agms.vo.tag.TagViewUpdateRequestVO;
import com.yd.api.agms.vo.tag.TagViewUpdateResponseVO;
import com.yd.api.result.CommonResult;
import com.yd.dal.entity.meta.MdTagNew;
import com.yd.dal.entity.meta.MdTagView;
import com.yd.dal.service.meta.MdTagNewDALService;
import com.yd.dal.service.meta.MdTagViewDALService;
import com.yd.rmi.ali.oss.service.OssService;
import com.yd.rmi.ali.oss.vo.OssOperateTypeEnum;
import com.yd.rmi.ali.oss.vo.OssRequestVO;
import com.yd.rmi.ali.oss.vo.OssResponseVO;
import com.yd.rmi.cache.SystemConfigService;
import com.yd.util.CommonUtil;
import com.yd.util.config.ZHBErrorConfig;

/**
 * @author xxy
 * @date 2021年06月21日 23:39
 */
@Service("AgmsTagService")
public class AgmsTagServiceImpl implements AgmsTagService {

    @Autowired
    public MdTagNewDALService mdTagNewDALService;

    @Autowired
    public MdTagViewDALService mdTagViewDALService;
    
	@Autowired
	private SystemConfigService systemConfigService;
	
    @Autowired
	private OssService ossService;

    @Override
    public TagUpdateResponseVO tagUpdate(TagUpdateRequestVO requestVO) {
        TagUpdateResponseVO responseVO = new TagUpdateResponseVO();
        CommonResult commonResult = new CommonResult();
        tagUpdateEntryCheck(requestVO,commonResult);
        if (!commonResult.isSuccess()){
            responseVO.setCommonResult(commonResult);
            return responseVO;
        }

        MdTagNew mdTagNew = new MdTagNew();
        BeanUtils.copyProperties(requestVO,mdTagNew);
        if (CommonUtil.isNullOrZero(requestVO.getId())){
            mdTagNew.setCreatedAt(new Date());
            mdTagNew.setUpdatedAt(new Date());
            mdTagNew.setCreatedBy(requestVO.getLoginId());
            mdTagNew.setUpdatedBy(requestVO.getLoginId());
            mdTagNewDALService.insert(mdTagNew);
        }else {
            mdTagNew.setUpdatedAt(new Date());
            mdTagNew.setUpdatedBy(requestVO.getLoginId());
            mdTagNewDALService.updateByPrimaryKeySelective(mdTagNew);
        }
        commonResult.setSuccess(true);
        commonResult.setMessage(ZHBErrorConfig.getErrorInfo("800000"));
        responseVO.setId(mdTagNew.getId());
        responseVO.setCommonResult(commonResult);
        return responseVO;
    }

    private void tagUpdateEntryCheck(TagUpdateRequestVO requestVO, CommonResult commonResult) {
        if (CommonUtil.isNullOrZero(requestVO.getConfigLevel())){
            commonResult.setSuccess(false);
            commonResult.setMessage(ZHBErrorConfig.getErrorInfo("830027"));
            return;
        }
        if (CommonUtil.isNullOrZero(requestVO.getLoginId())){
            String[] params = {"loginId"};
            commonResult.setSuccess(false);
            commonResult.setMessage(ZHBErrorConfig.getErrorInfo("610001", params));
            return;
        }
        
        if (CommonUtil.isNullOrZero(requestVO.getTagType())){
            String[] params = {"tagType"};
            commonResult.setSuccess(false);
            commonResult.setMessage(ZHBErrorConfig.getErrorInfo("610001", params));
            return;
        }
        if (CommonUtil.isNullOrBlank(requestVO.getTagName())){
            String[] params = {"tagName"};
            commonResult.setSuccess(false);
            commonResult.setMessage(ZHBErrorConfig.getErrorInfo("610001", params));
            return;
        }
        if (CommonUtil.isNullOrZero(requestVO.getIsActive())){
            commonResult.setSuccess(false);
            String[] params = {"isActive"};
            commonResult.setMessage(ZHBErrorConfig.getErrorInfo("610001", params));
            return;
        }
        if (CommonUtil.isNullOrZero(requestVO.getUpperTagId()) && requestVO.getConfigLevel() != 1L){
            commonResult.setSuccess(false);
            commonResult.setMessage(ZHBErrorConfig.getErrorInfo("830028"));
            return;
        }
        commonResult.setSuccess(true);
        commonResult.setMessage(ZHBErrorConfig.getErrorInfo("800000"));
    }
    

    /**
     * AGMS -- 前端显示标签 保存与修改
     * @author ywenyang
     * @param tagViewImage 请求文件图片
     * @date 2021年06月30日 23:39
     */
    @Override
    public TagViewUpdateResponseVO tagViewUpdate(TagViewUpdateRequestVO requestVO,MultipartFile tagViewImage) {
    	TagViewUpdateResponseVO responseVO = new TagViewUpdateResponseVO();
        CommonResult commonResult = new CommonResult();
        tagViewUpdateEntryCheck(requestVO,commonResult);
        if (!commonResult.isSuccess()){
            responseVO.setCommonResult(commonResult);
            return responseVO;
        }

		//上传文件
		boolean success = false;
		String message = "";
		String filePathOss = null;
		if (tagViewImage != null) {
			String originalFilename = null;
			String ossKey = null;
			originalFilename = tagViewImage.getOriginalFilename();
			ossKey = "downloadfile/" + originalFilename.replaceAll(" ", "").replaceAll("	", "");
			File file = null;
			try {
				file = File.createTempFile("tmp", null);
				tagViewImage.transferTo(file);
				OssRequestVO ossRequestVO = new OssRequestVO();
				ossRequestVO.setOperateType(OssOperateTypeEnum.PUT_OBJECT.getCode());
				String bucketName = systemConfigService.getSingleConfigValue("ALI_OSS_IMAGES");
				ossRequestVO.setBucketName(bucketName);
				ossRequestVO.setKey(ossKey);
				ossRequestVO.setFile(file);
				OssResponseVO ossresponseVO = ossService.ossOperate(ossRequestVO);
				if(ossresponseVO.getCommonResult().isSuccess()){
					ossRequestVO.setOperateType(OssOperateTypeEnum.GENERATE_URL.getCode());
					ossresponseVO = ossService.ossOperate(ossRequestVO);
					filePathOss = ossresponseVO.getUrl();
				}else{
					success = true;
					message = ossresponseVO.getCommonResult().getMessage();
				}
			} catch (IOException e) {
				e.printStackTrace();
				success = true;
				message = "Update FileImage error:" + e.getMessage();
			}finally{
				if(file != null){file.delete();}
			}
			if(success){
                commonResult.setSuccess(false);
                commonResult.setMessage(message);
                responseVO.setCommonResult(commonResult);
                return responseVO;
			}
		}
		
        MdTagView mdTagView = new MdTagView();
        BeanUtils.copyProperties(requestVO,mdTagView);
        if(filePathOss != null && !"".equals(filePathOss)){
        	mdTagView.setDisplayImage(filePathOss);
        }
        if (CommonUtil.isNullOrZero(requestVO.getId())){
        	mdTagView.setCreatedAt(new Date());
            mdTagView.setUpdatedAt(new Date());
            mdTagView.setCreatedBy(requestVO.getLoginId());
            mdTagView.setUpdatedBy(requestVO.getLoginId());
            mdTagViewDALService.insert(mdTagView);
        }else {
        	mdTagView.setUpdatedAt(new Date());
        	mdTagView.setUpdatedBy(requestVO.getLoginId());
        	mdTagViewDALService.updateByPrimaryKeySelective(mdTagView);
        }
    	responseVO.setFilePathOss(mdTagView.getDisplayImage());
        commonResult.setSuccess(true);
        commonResult.setMessage(ZHBErrorConfig.getErrorInfo("800000"));
        responseVO.setId(mdTagView.getId());
        responseVO.setCommonResult(commonResult);
        return responseVO;
    }
    
    private void tagViewUpdateEntryCheck(TagViewUpdateRequestVO requestVO, CommonResult commonResult) {
        if (CommonUtil.isNullOrBlank(requestVO.getTagViewType())){
            commonResult.setSuccess(false);
            commonResult.setMessage(ZHBErrorConfig.getErrorInfo("830029"));
            return;
        }
        if (CommonUtil.isNullOrZero(requestVO.getTagId())){
            commonResult.setSuccess(false);
            commonResult.setMessage(ZHBErrorConfig.getErrorInfo("830030"));
            return;
        }else{
        	MdTagNew mdTagNew = mdTagNewDALService.selectByPrimaryKey(requestVO.getTagId());
        	if(!(mdTagNew != null && !CommonUtil.isNullOrZero(mdTagNew.getIsActive()) && mdTagNew.getIsActive() == 1)){
                commonResult.setSuccess(false);
                commonResult.setMessage(ZHBErrorConfig.getErrorInfo("830035"));
                return;
        	}
        }
        if (CommonUtil.isNullOrBlank(requestVO.getTagLevel())){
            commonResult.setSuccess(false);
            commonResult.setMessage(ZHBErrorConfig.getErrorInfo("830027"));
            return;
        }
        if (CommonUtil.isNullOrZero(requestVO.getUpperTagViewId()) && !"1".equals(requestVO.getTagLevel())){
            commonResult.setSuccess(false);
            commonResult.setMessage(ZHBErrorConfig.getErrorInfo("830028"));
            return;
        }else{
        	if(!CommonUtil.isNullOrZero(requestVO.getUpperTagViewId())){
	        	MdTagView mdTagView = mdTagViewDALService.selectByPrimaryKey(requestVO.getUpperTagViewId());
	        	if(mdTagView != null){
	        		if(!requestVO.getTagViewType().equals(mdTagView.getTagViewType())){
	                    commonResult.setSuccess(false);
	                    commonResult.setMessage(ZHBErrorConfig.getErrorInfo("830033"));
	                    return;
	        		}
	        		if(CommonUtil.stringParseInt(requestVO.getTagLevel()) !=  CommonUtil.stringParseInt(mdTagView.getTagLevel()) + 1){
	                    commonResult.setSuccess(false);
	                    commonResult.setMessage(ZHBErrorConfig.getErrorInfo("830034"));
	                    return;
	        		}
	        	}else{
	                commonResult.setSuccess(false);
	                commonResult.setMessage(ZHBErrorConfig.getErrorInfo("830032"));
	                return;
	        	}
        	}
        }
        commonResult.setSuccess(true);
        commonResult.setMessage(ZHBErrorConfig.getErrorInfo("800000"));
    }
    
}
