package cn.com.countrygarden.bi.main.service.extension.impl;

import cn.com.countrygarden.bi.main.dao.extension.ExtensionDupBindingMapper;
import cn.com.countrygarden.bi.main.dao.extension.ExtensionJointMapper;
import cn.com.countrygarden.bi.main.dao.extension.ExtensionProjectLeaderMapper;
import cn.com.countrygarden.bi.main.dao.extension.ExtensionReportMapper;
import cn.com.countrygarden.bi.main.dao.extension.ExtensionUploadFileMapper;
import cn.com.countrygarden.bi.main.dao.extension.ExtensionErpBindingMapper;
import cn.com.countrygarden.bi.main.constant.ExtensionContent;
import cn.com.countrygarden.bi.main.dao.mediaResource.BasicInfoMapper;
import cn.com.countrygarden.bi.main.dto.extension.ExtensionJointInfoDTO;
import cn.com.countrygarden.bi.main.dto.extension.ExtensionPageData;
import cn.com.countrygarden.bi.main.dto.extension.ExtensionProjectLeaderDTO;
import cn.com.countrygarden.bi.main.dto.extension.ExtensionReportDTO;
import cn.com.countrygarden.bi.main.dto.extension.ExtensionUpFileInfo;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.extension.ExtensionReportService;
import cn.com.countrygarden.bi.main.util.ExtensionReportUtils;
import cn.com.countrygarden.bi.main.util.OSSUtils;
import com.github.pagehelper.PageRowBounds;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ExtensionReportServiceImpl
 * @Description 市场拓展 -> 外拓报表 -> 业务逻辑 -> Impl
 * @Author Sjiang
 * @Date 2019/1/18 15:55
 * @Version 1.0
 **/
@Service
@Transactional
public class ExtensionReportServiceImpl  implements ExtensionReportService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    ExtensionReportMapper mapper;
    @Autowired
    private ExtensionErpBindingMapper erpMapper;
    @Autowired
    private ExtensionDupBindingMapper dupMapper;
    @Autowired
    private ExtensionJointMapper jointMapper;
    @Autowired
    private ExtensionProjectLeaderMapper leaderMapper;
    @Autowired
    private ExtensionUploadFileMapper fileMapper;
    @Autowired
    private OSSUtils ossUtils;

    @Autowired
    private BasicInfoMapper basicInfoMapper;
    /**
     * @return java.lang.Object
     * @Author Sjiang
     * @Description 获取外拓报表信息
     * @Date 15:07 2019/1/21
     * @Param []
     **/
    @Override
    public Object selectReportAll(ExtensionReportDTO reportDTO, AccessTokenService accessTokenService, HttpServletRequest request, ExtensionPageData pageData) {
        String userCode = ExtensionReportUtils.getUserCode(accessTokenService, request);
        // 获取 regionName ，如果为空则是总部权限
        String regionName = isExtensionAdmin(userCode);
        try {
            PageRowBounds pageRowBounds = new PageRowBounds(pageData.getPageIndex(), pageData.getPageSize());
            List<ExtensionReportDTO> plist = mapper.selectReportAll(reportDTO,regionName, pageRowBounds);
            return new ExtensionPageData(plist, pageRowBounds);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExtensionContent.GET_REPORT_ERROR + e.getMessage());
            throw new ServiceException(ExtensionContent.GET_REPORT_ERROR);
        }
    }

    /**
     * @return java.lang.Object
     * @Author Sjiang
     * @Description ERP 、DUP 信息绑定
     * @Date 9:30 2019/1/22
     * @Param [reportDTO]
     **/
    @Override
    public Object dataBinding(ExtensionReportDTO reportDTO, String userCode) {
        if (reportDTO.getErpId() == null || reportDTO.getDupId() == null) {
            return ExtensionContent.ERROR_NO_ID;
        }
        try {
            // 查询 erp 数据, 缓存进 DUP 数据存
            ExtensionReportDTO erpData = getReportByErpId(reportDTO.getErpId());
            // 合并 实体类中的属性值
            ExtensionReportDTO targetDTO = ExtensionReportUtils.combineSydwCore(reportDTO, erpData);
            targetDTO.setCreateBy(userCode);
            targetDTO.setLastUpdateBy(userCode);
            mapper.insertSelectiveByDto(targetDTO);
            // 子对象插入
            insertChild(targetDTO, userCode);
            return ExtensionContent.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExtensionContent.REPORT_BINDING_ERROR + e.getMessage());
            throw new ServiceException(ExtensionContent.REPORT_BINDING_ERROR);
        }

    }
    // 查询 erp 数据
    private ExtensionReportDTO getReportByErpId(Long erpId){
        ExtensionReportDTO erpData = erpMapper.selectById(erpId);
        if (erpData == null) {
            logger.error(ExtensionContent.ERP_NOT_DATA_ON_ID);
            throw new ServiceException(ExtensionContent.ERP_NOT_DATA_ON_ID);
        }
        // 将查询到的 开发主体名称拼接为字符串
        List<String> developmentSubjectNameList = erpData.getDevelopmentSubjectNameList();
        if (null != developmentSubjectNameList && !developmentSubjectNameList.isEmpty()) {
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < developmentSubjectNameList.size(); i++) {
                stringBuffer.append(developmentSubjectNameList.get(i));
                if (i != developmentSubjectNameList.size() - 1) {
                    stringBuffer.append(",");
                }
            }
            erpData.setDevelopmentSubjectNames(stringBuffer.toString());
        }
        return erpData;
    }


    /**
     * @return java.lang.Object
     * @Author Sjiang
     * @Description 根据 ID 获取已绑定信息
     * @Date 22:51 2019/1/22
     * @Param [dupDTO]
     **/

    @Override
    public Object getBindingById(ExtensionReportDTO reportDTO) {
        try {
            if (reportDTO.getId() == null) {
                logger.error(ExtensionContent.ID_NULL);
                throw new ServiceException(ExtensionContent.ID_NULL);
            }
            ExtensionReportDTO extensionReportDTO = mapper.selectByPrimaryKey(reportDTO.getId());
            if (extensionReportDTO.getIsDelete().intValue() == 1) {
                return ExtensionContent.DATA_DELETED;
            }
            return new ExtensionPageData(extensionReportDTO);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExtensionContent.GET_BINDING_ERROR + e.getMessage());
            throw new ServiceException(ExtensionContent.GET_BINDING_ERROR);
        }
    }

    /**
     * @return java.lang.Object
     * @Author Sjiang
     * @Description 根据 ID 撤销已绑定信息
     * @Date 10:42 2019/1/23
     * @Param [reportDTO]
     **/
    @Override
    public Object removeBinding(ExtensionReportDTO reportDTO, String userCode) {
        try {
            if (reportDTO.getId() == null) {
                logger.error(ExtensionContent.ID_NULL);
                throw new ServiceException(ExtensionContent.ID_NULL);
            }
            mapper.deleteByPrimaryKey(reportDTO.getId(), userCode);
            return ExtensionContent.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExtensionContent.REMOVE_ERROR + e.getMessage());
            throw new ServiceException(ExtensionContent.REMOVE_ERROR);
        }
    }

    /**
     * @return java.lang.Object
     * @Author Sjiang
     * @Description 根据 id 修改信息
     * @Date 23:27 2019/1/22
     * @Param [reportDTO]
     **/

    @Override
    public Object updateBinding(ExtensionReportDTO reportDTO, String userCode) {
        try {
            if (reportDTO.getId() == null) {
                logger.error(ExtensionContent.ID_NULL);
                throw new ServiceException(ExtensionContent.ID_NULL);
            }
            // 更新主数据
            mapper.updateSelectiveByDto(reportDTO);
            // 更新子数据
            updateChild(reportDTO, userCode);
            return ExtensionContent.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExtensionContent.UPDATE_ERROR + e.getMessage());
            throw new ServiceException(ExtensionContent.UPDATE_ERROR);
        }
    }

    /**
     * @return java.lang.Object
     * @Author Sjiang
     * @Description 获取外拓项目所有信息的总条数
     * @Date 15:10 2019/1/23
     * @Param []
     *
     * @param accessTokenService
     * @param request*/
    @Override
    public Object getExtensionCount(AccessTokenService accessTokenService, HttpServletRequest request) {
        String userCode = ExtensionReportUtils.getUserCode(accessTokenService, request);
        // 获取 regionName ，如果为空则是总部权限
        String regionName = isExtensionAdmin(userCode);
        try {
            HashMap<Object, Long> resultMap = Maps.newHashMap();
            resultMap.put("dupAll", dupMapper.selectAllCount(regionName));
            List<Long> dupIds = mapper.selectDupBindingId(regionName);
            resultMap.put("dupUnbinding", dupMapper.selectUnbindingCount(dupIds, regionName));
            resultMap.put("erpAll", erpMapper.selectAllCount(regionName));
            List<Long> erpIds = mapper.selectErpBindingId(regionName);
            resultMap.put("erpUnbinding", erpMapper.selectUnbindingCount(erpIds, regionName));
            resultMap.put("bindingAll", mapper.selectBindingCount(regionName));
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new ServiceException("总数获取失败！");
        }
    }

    /**
     * @Author Sjiang
     * @Description  用户删除已绑定数据的子数据信息
     * @Date 16:27 2019/2/12
     * @Param []
     * @return java.lang.Object
     **/
    @Override
    public Object deleteBindingChildInfo(Map<String, Long> param, String userCode) {
        try {
            Long jointId = param.get("jointId");
            Long leaderId = param.get("leaderId");
            Long fileId = param.get("fileId");
            if (jointId != null){
                // 删除 甲方联系人
                jointMapper.deleteByPrimaryKey(jointId);
            }
            if (leaderId != null){
                // 删除 项目负责人
                leaderMapper.deleteByPrimaryKey(leaderId);
            }
            if (fileId != null){
                ExtensionUpFileInfo fileInfo = fileMapper.selectByPrimaryKey(fileId);
                ossUtils.delFile(fileInfo.getFileRealName());
                // 删除 已上传文件
                fileMapper.deleteByPrimaryKey(fileId);
            }
            return ExtensionContent.SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new ServiceException("删除失败！");
        }



    }

    /**
     * @return void
     * @Author Sjiang
     * @Description 子对象更新
     * @Date 10:56 2019/1/23
     * @Param [reportDTO]
     **/

    private void updateChild(ExtensionReportDTO dto, String userCode) {
        try {

            // 甲方对接人
            if (dto.getJointDTO() != null && dto.getJointDTO().size() > 0) {
                for (ExtensionJointInfoDTO jointInfoDTO : dto.getJointDTO()) {
                    jointInfoDTO.setLastUpdateBy(userCode);
                    // id 为空表示新增
                    if (jointInfoDTO.getId() == null){
                        jointInfoDTO.setExtensionReportId(dto.getId());
                        jointInfoDTO.setCreateBy(userCode);
                        jointMapper.insert(jointInfoDTO);
                    }
                }
                jointMapper.updateBatchSelective(dto, userCode);
            }
            // 项目负责人
            if (dto.getLeaderDTO() != null && dto.getLeaderDTO().size() > 0) {
                for (ExtensionProjectLeaderDTO projectLeaderDTO : dto.getLeaderDTO()) {
                    projectLeaderDTO.setLastUpdateBy(userCode);
                    // id 为空表示新增
                    if (projectLeaderDTO.getId() == null){
                        projectLeaderDTO.setExtensionReportId(dto.getId());
                        projectLeaderDTO.setCreateBy(userCode);
                        leaderMapper.insert(projectLeaderDTO);
                    }
                }
                leaderMapper.updateBatchSelective(dto, userCode);
            }
            // 文件 URL
            if (dto.getFileInfos() != null && dto.getFileInfos().size() > 0) {
                for (ExtensionUpFileInfo fileInfo : dto.getFileInfos()) {
                    fileInfo.setLastUpdateBy(userCode);
                    // id 为空表示新增
                    if (fileInfo.getId() == null){
                        fileInfo.setExtensionReportId(dto.getId());
                        fileInfo.setCreateBy(userCode);
                        if (fileInfo.getFileName().indexOf(".") > 0) {
                            String substring = fileInfo.getFileName().substring(fileInfo.getFileName().indexOf(".") + 1);
                            fileInfo.setFileType(substring);
                        }
                        fileMapper.insert(fileInfo);
                    }
                }
                fileMapper.updateBatchSelective(dto, userCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("子对象更新失败！" + e.getMessage());
            throw new ServiceException("子对象更新失败！" + " 请检查子对象数据准确性！");
        }
    }




    /**
     * @return java.lang.Object
     * @Author Sjiang
     * @Description 子对象插入
     * @Date 21:15 2019/1/22
     * @Param [reportDTO]
     **/

    private void insertChild(ExtensionReportDTO dto, String userCode) {
        try {
            // 甲方对接人
            if (dto.getJointDTO() != null && dto.getJointDTO().size() > 0) {
                jointMapper.insertBatchSelective(dto, userCode);
            }
            // 项目负责人
            if (dto.getLeaderDTO() != null && dto.getLeaderDTO().size() > 0) {
                leaderMapper.insertBatchSelective(dto, userCode);
            }
            // 文件 URL
            if (dto.getFileInfos() != null && dto.getFileInfos().size() > 0) {
                for (ExtensionUpFileInfo fileInfo : dto.getFileInfos()) {
                    if (fileInfo.getFileName().indexOf(".") > 0) {
                        String substring = fileInfo.getFileName().substring(fileInfo.getFileName().indexOf(".") + 1);
                        fileInfo.setFileType(substring);
                    }
                }
                fileMapper.insertBatchSelective(dto, userCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExtensionContent.REPORT_BINDING_ERROR + " 子对象插入失败！" + e.getMessage());
            throw new ServiceException(ExtensionContent.REPORT_BINDING_ERROR + " 请检查子对象数据准确性！");
        }

    }

    public String isExtensionAdmin(String userCode ) {
        // 拿到 userCode 查询属于哪个角色下的
        List<String> roles = mapper.selectRoleByUserCode(userCode);
//        boolean fla = false;
        for (String role : roles) {
            // 为管理员
            if (ExtensionContent.EXTENSION_ADMIN.equals(role)){
                return null;
            }
        }
        Map<String, String> map =basicInfoMapper.findErpUserOrgan(userCode);
        if ("01".equals(map.get("organCode"))){
            return null;
        }
        // 表示为非管理员，需要做区域控制
        return  map.get("regionName");
    }

    /**
     * @Author sjiang
     * @Description  加入区域权限控制的查询
     * @Date 11:00 2019-03-16
     * @Param [reportDTO, accessTokenService, request, pageData]
     * @return java.lang.Object
     **/

    @Override
    public Object selectAll(ExtensionReportDTO reportDTO, AccessTokenService accessTokenService, HttpServletRequest request, ExtensionPageData pageData) {
        ExtensionReportUtils.checkBindingIdentifier(reportDTO);
        // 获取 userCode
        String userCode = ExtensionReportUtils.getUserCode(accessTokenService, request);
        // 获取 regionName ，如果为空则是总部权限
        String regionName = isExtensionAdmin(userCode);
        PageRowBounds pageRowBounds = new PageRowBounds(pageData.getPageIndex(),pageData.getPageSize());
        List<ExtensionReportDTO> plist = mapper.selectAllByDTO(reportDTO,regionName, pageRowBounds);
        return new ExtensionPageData(plist, pageRowBounds);
    }

    /**
     * @Author sjiang
     * @Description  更新已绑定的 erp 信息
     * @Date 16:57 2019/5/21
     * @Param [erpId, request]
     * @return java.lang.Object
     **/
    @Override
    public Object dataBindingUpdate(Long erpId, String userCode) {
        if (erpId == null){
            logger.error("请求参数缺失！");
            throw new ServiceException("请求参数缺失！");
        }
        // 获取 erp 最新数据
        ExtensionReportDTO reportDTO = getReportByErpId(erpId);
        reportDTO.setLastUpdateBy(userCode);
        reportDTO.setLastUpdateDate(new Date());
        // 根据 erp id 去更新最新数据
        mapper.updateByErpId(reportDTO);
        return "更新成功";
    }
}
