package com.house365.ws.interfaces.impl;

import com.house365.beans.entity.BaseAttachment;
import com.house365.beans.entity.ReportAttachEntity;
import com.house365.beans.system.Page;
import com.house365.beans.system.QueryParams;
import com.house365.ws.beans.request.AttachmentListRequest;
import com.house365.ws.beans.request.AttachmentRequest;
import com.house365.ws.beans.response.AttachmentListResponse;
import com.house365.ws.beans.response.AttachmentResponse;
import com.house365.ws.dao.mapper.ReportAttachMapper;
import com.house365.ws.interfaces.server.IAttachmentInterface;
import com.house365.ws.service.interfaces.IAttachmentService;
import com.house365.ws.system.ReturnResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Component("attachmentInterface")
public class AttachmentInterfaceImpl implements IAttachmentInterface {

    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(AttachmentInterfaceImpl.class);

    @Autowired
    private IAttachmentService<BaseAttachment> attachmentService;
    @Autowired
    private ReportAttachMapper attachMapper;

    /**
     * 查询附件列表
     *
     * @param request
     * @author duhui
     * @version [v1.0.0, 2015-1-18]
     */
    @Override
    public AttachmentListResponse getAttachments(AttachmentListRequest request) {
        AttachmentListResponse response = new AttachmentListResponse();
        try {
            QueryParams<BaseAttachment> queryParams = new QueryParams<BaseAttachment>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            queryParams.setOrderColumn(request.getOrderColumn());
            queryParams.setOrderMode(request.getOrderMode());
            List<BaseAttachment> attachment = attachmentService.queryByPage(queryParams);

            response.setPaging(queryParams.getPaging());
            response.setObjectList(attachment);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 获取单个Attachment
     *
     * @author duhui
     * @version [v1.0.0, 2015-1-18]
     */
    @Override
    public AttachmentResponse getAttachment(Integer id) {
        AttachmentResponse response = new AttachmentResponse();
        try {
            BaseAttachment attachment = attachmentService.getById(id);
            response.setAttachment(attachment);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 添加附件
     *
     * @param request
     * @author duhui
     * @version [v1.0.0, 2015-1-18]
     */
    @Override
    public AttachmentResponse addAttachment(AttachmentRequest request) {
        AttachmentResponse response = new AttachmentResponse();
        try {
            BaseAttachment attachment = request.getAttachment();
            Integer id = attachmentService.save(attachment);
            //置业报告新增同时更新表中url
            String resourceType = attachment.getResourceType();
            if (resourceType.contains("report_attach")) {
                ReportAttachEntity entity = attachMapper.getById(attachment.getResourceId());
                entity.setUrl(attachment.getRemotePath());
                attachMapper.update(entity);
            }
            attachment.setId(id);
            response.setAttachment(attachment);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 修改Attachment
     *
     * @param request
     * @author duhui
     * @version [v1.0.0, 2015-1-18]
     */
    @Override
    public AttachmentResponse updateAttachment(AttachmentRequest request) {
        AttachmentResponse response = new AttachmentResponse();
        try {
            BaseAttachment attachment = request.getAttachment();
            attachmentService.update(attachment);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 删除Attachment
     *
     * @param id
     * @author duhui
     * @version [v1.0.0, 2015-1-18]
     */
    @Override
    public AttachmentResponse deleteAttachment(Integer id) {
        AttachmentResponse response = new AttachmentResponse();
        try {
            //置业报告删除同时更新表中url
            BaseAttachment attachment = attachmentService.getById(id);
            String resourceType = attachment.getResourceType();
            if (resourceType.contains("report_attach")) {
                ReportAttachEntity entity = attachMapper.getById(attachment.getResourceId());
                entity.setUrl("");
                attachMapper.update(entity);
            }
            attachmentService.delete(id);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 修改临时 资源ID resourceId
     *
     * @param tmpResourceId
     * @param resourceId
     * @author duhui
     * @version [v1.0.0, 2015-1-18]
     */
    @Override
    public void updateAttachmentByResourceId(Integer tmpResourceId, Integer resourceId) {
        AttachmentListResponse response = new AttachmentListResponse();
        AttachmentListRequest request = new AttachmentListRequest();
        Map<String, Object> searchParams = new TreeMap<String, Object>();
        {
            searchParams.put("EQ_resourceId", tmpResourceId);
        }
        request.setSearchParams(searchParams);
        response = getAttachments(request);
        List<BaseAttachment> attachments = response.getObjectList();
        for (BaseAttachment attachment : attachments) {
            attachment.setResourceId(resourceId);
            AttachmentRequest req = new AttachmentRequest();
            req.setAttachment(attachment);
            updateAttachment(req);
        }
    }

    @Override
    public void deleteTempAttachment(String resourceType) {
        //delete temp images
        Map<String, Object> searchParams = new HashMap<>();
        AttachmentListRequest attachmentListRequest = new AttachmentListRequest();
        Page page = new Page();
        page.setCurrentPage(1);
        page.setPageSize(Integer.MAX_VALUE);

        searchParams.put("EQ_resourceType", resourceType);
        searchParams.put("EQ_resourceId", 0);

        attachmentListRequest.setPaging(page);
        attachmentListRequest.setSearchParams(searchParams);
        AttachmentListResponse attachmentListResponse = getAttachments(attachmentListRequest);
        if (attachmentListResponse != null && attachmentListResponse.getObjectList() != null) {
            List<BaseAttachment> baseAttachments = attachmentListResponse.getObjectList();
            for (BaseAttachment attachment : baseAttachments) {
                deleteAttachment(attachment.getId());
            }
        }
    }

    @Override
    public void updateTempAttachmentBySourceType(String resourceType, Integer sourceId) {
        //delete temp images
        Map<String, Object> searchParams = new HashMap<>();
        AttachmentListRequest attachmentListRequest = new AttachmentListRequest();
        Page page = new Page();
        page.setCurrentPage(1);
        page.setPageSize(Integer.MAX_VALUE);

        searchParams.put("EQ_resourceType", resourceType);
        searchParams.put("EQ_resourceId", 0);

        attachmentListRequest.setPaging(page);
        attachmentListRequest.setSearchParams(searchParams);
        AttachmentListResponse attachmentListResponse = getAttachments(attachmentListRequest);
        if (attachmentListResponse != null && attachmentListResponse.getObjectList() != null) {
            List<BaseAttachment> baseAttachments = attachmentListResponse.getObjectList();
            if (baseAttachments != null && !baseAttachments.isEmpty()) {
                BaseAttachment attachment = baseAttachments.get(0);
                attachment.setResourceId(sourceId);
                attachmentService.update(attachment);
            }
        }
    }

    @Override
    public AttachmentListResponse getAttachmentBySource(String resourceType, Integer sourceId) {
        Map<String, Object> searchParams = new HashMap<>();
        AttachmentListRequest attachmentListRequest = new AttachmentListRequest();
        Page page = new Page();
        page.setCurrentPage(1);
        page.setPageSize(Integer.MAX_VALUE);

        searchParams.put("EQ_resourceType", resourceType);
        searchParams.put("EQ_resourceId", sourceId);

        attachmentListRequest.setPaging(page);
        attachmentListRequest.setSearchParams(searchParams);

        return getAttachments(attachmentListRequest);
    }

    @Override
    public AttachmentListResponse queryByResourceIdAndResouceType(String resourceId, String channel) {
        AttachmentListResponse response = new AttachmentListResponse();
        try {
            List<BaseAttachment> list = attachmentService.queryByResourceIdAndResouceType(resourceId, channel);
            response.setPaging(new Page(list.size()));
            response.setObjectList(list);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

}
