package com.cm.common.service.bigdatatemplate.impl;

import com.cm.common.base.AbstractService;
import com.cm.common.exception.RemoveException;
import com.cm.common.exception.SaveException;
import com.cm.common.exception.SearchException;
import com.cm.common.plugin.pojo.dtos.datadictionary.DataDictionaryDTO;
import com.cm.common.plugin.service.datadictionary.impl.DataDictionaryServiceImpl;
import com.cm.common.plugin.service.file.IFileService;
import com.cm.common.pojo.ListPage;
import com.cm.common.pojo.dtos.bigdatatemplate.BigdataTemplateFileDTO;
import com.cm.common.pojo.dtos.bigdatatemplatearea.BigdataTemplateAreaDTO;
import com.cm.common.pojo.dtos.bigdatatemplatearea.BigdataTemplateAreaFileDTO;
import com.cm.common.pojo.pos.FilePO;
import com.cm.common.pojo.vos.templaterecord.TemplateRecordVO;
import com.cm.common.result.SuccessResult;
import com.cm.common.result.SuccessResultData;
import com.cm.common.result.SuccessResultList;
import com.cm.common.service.bigdatatemplatearea.IBigdataTemplateAreaService;
import com.cm.common.util.TemplateBuilderUtil;
import com.cm.common.util.TemplateCreateData;
import com.cm.common.utils.DateUtil;
import com.cm.common.utils.HashMapUtil;
import com.cm.common.utils.UUIDUtil;
import com.cm.common.dao.bigdatatemplate.IBigdataTemplateDao;
import com.cm.common.pojo.dtos.bigdatatemplate.BigdataTemplateDTO;
import com.cm.common.pojo.vos.bigdatatemplate.BigdataTemplateVO;
import com.cm.common.service.bigdatatemplate.IBigdataTemplateService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

/**
 * @ClassName: BigdataTemplateServiceImpl
 * @Description: 大数据展示的模板管理
 * @Author: WenG
 * @Date: 2020-10-20 10:49
 * @Version: 1.0
 **/
@Service
public class BigdataTemplateServiceImpl extends AbstractService implements IBigdataTemplateService {

    @Autowired
    private IBigdataTemplateDao bigdataTemplateDao;

    @Autowired
    private IBigdataTemplateAreaService iBigdataTemplateAreaService;

    @Autowired
    private IFileService iFileService;

    @Autowired
    private DataDictionaryServiceImpl dataDictionaryServiceImpl;

    @Override
    public SuccessResult saveBigdataTemplate(BigdataTemplateVO bigdataTemplateVO) throws Exception {
        saveBigdataTemplateInfo(null, bigdataTemplateVO);
        return new SuccessResult();
    }

    @Override
    public SuccessResult saveBigdataTemplateByToken(String token, BigdataTemplateVO bigdataTemplateVO) throws Exception {
        saveBigdataTemplateInfo(token, bigdataTemplateVO);
        return new SuccessResult();
    }

    @Override
    public String saveBigdataTemplateReturnId(BigdataTemplateVO bigdataTemplateVO) throws Exception {
        return saveBigdataTemplateInfoReturnId(null, bigdataTemplateVO);
    }

    @Override
    public String saveBigdataTemplateByTokenReturnId(String token, BigdataTemplateVO bigdataTemplateVO) throws Exception {
        return saveBigdataTemplateInfoReturnId(token, bigdataTemplateVO);
    }

    /**
     * 新增大数据展示的模板管理
     *
     * @param token
     * @param bigdataTemplateVO
     * @throws Exception
     */
    private void saveBigdataTemplateInfo(String token, BigdataTemplateVO bigdataTemplateVO) throws Exception {
        saveBigdataTemplateInfoReturnId(token, bigdataTemplateVO);
    }

    /**
     * 新增大数据展示的模板管理
     *
     * @param token
     * @param bigdataTemplateVO
     * @return bigdataTemplateId
     * @throws Exception
     */
    private String saveBigdataTemplateInfoReturnId(String token, BigdataTemplateVO bigdataTemplateVO) throws Exception {
        String bigdataTemplateId = UUIDUtil.getUUID();
        /**
         * 判断编码是否已经存在
         */
        BigdataTemplateDTO dto = bigdataTemplateDao.getBigdataTemplateByCode(bigdataTemplateVO.getBigdataTemplateCode());
        if(dto != null) {
            throw new SaveException("该编码已经存在");
        }
        Map<String, Object> params = HashMapUtil.beanToMap(bigdataTemplateVO);
        params.put("bigdataTemplateId", bigdataTemplateId);
        if (token != null) {
            setSaveInfo(token, params);
        } else {
            setSaveInfo(params);
        }
        bigdataTemplateDao.saveBigdataTemplate(params);
        return bigdataTemplateId;
    }

    @Override
    public SuccessResult removeBigdataTemplate(String ids) throws RemoveException {
        removeBigdataTemplateInfo(null, ids);
        return new SuccessResult();
    }

    @Override
    public SuccessResult removeBigdataTemplateByToken(String token, String ids) throws RemoveException {
        removeBigdataTemplateInfo(token, ids);
        return new SuccessResult();
    }

    /**
     * 删除大数据展示的模板管理
     *
     * @param token
     * @param ids
     */
    private void removeBigdataTemplateInfo(String token, String ids) {
        Map<String, Object> params = getHashMap(3);
        params.put("bigdataTemplateIds", Arrays.asList(ids.split("_")));
        if (token != null) {
            setUpdateInfo(token, params);
        } else {
            setUpdateInfo(params);
        }
        bigdataTemplateDao.removeBigdataTemplate(params);
    }

    @Override
    public void deleteBigdataTemplate(String ids) throws RemoveException {
        Map<String, Object> params = getHashMap(3);
        params.put("bigdataTemplateIds", Arrays.asList(ids.split("_")));
        bigdataTemplateDao.deleteBigdataTemplate(params);
    }

    @Override
    public SuccessResult updateBigdataTemplate(String bigdataTemplateId, BigdataTemplateVO bigdataTemplateVO) throws Exception {
        updateBigdataTemplateInfo(null, bigdataTemplateId, bigdataTemplateVO);
        return new SuccessResult();
    }

    @Override
    public SuccessResult updateBigdataTemplateByToken(String token, String bigdataTemplateId, BigdataTemplateVO bigdataTemplateVO) throws Exception {
        updateBigdataTemplateInfo(token, bigdataTemplateId, bigdataTemplateVO);
        return new SuccessResult();
    }

    /**
     * 修改大数据展示的模板管理
     *
     * @param token
     * @param bigdataTemplateId
     * @param bigdataTemplateVO
     */
    private void updateBigdataTemplateInfo(String token, String bigdataTemplateId, BigdataTemplateVO bigdataTemplateVO) throws Exception {
        Map<String, Object> params = HashMapUtil.beanToMap(bigdataTemplateVO);
        params.put("bigdataTemplateId", bigdataTemplateId);
        if (token != null) {
            setUpdateInfo(token, params);
        } else {
            setUpdateInfo(params);
        }
        bigdataTemplateDao.updateBigdataTemplate(params);
    }

    @Override
    public BigdataTemplateDTO getBigdataTemplateById(String bigdataTemplateId) throws SearchException {
        Map<String, Object> params = super.getHashMap(1);
        params.put("bigdataTemplateId", bigdataTemplateId);
        BigdataTemplateDTO dto = bigdataTemplateDao.getBigdataTemplate(params);
        List<BigdataTemplateAreaDTO> areaList = iBigdataTemplateAreaService.getBigdataTemplateAreaByBigdataTemplateId(bigdataTemplateId);
        dto.setAreaList(areaList);
        return dto;
    }

    @Override
    public List<BigdataTemplateDTO> listBigdataTemplate(Map<String, Object> params) throws SearchException {
        return bigdataTemplateDao.listBigdataTemplate(params);
    }

    @Override
    public SuccessResultList<List<BigdataTemplateDTO>> listPageBigdataTemplate(ListPage page) throws SearchException {
        PageHelper.startPage(page.getPage(), page.getRows());
        List<BigdataTemplateDTO> bigdataTemplateDTOs = bigdataTemplateDao.listBigdataTemplate(page.getParams());
        PageInfo<BigdataTemplateDTO> pageInfo = new PageInfo<>(bigdataTemplateDTOs);
        return new SuccessResultList<>(bigdataTemplateDTOs, pageInfo.getPageNum(), pageInfo.getTotal());
    }

    @Override
    public Integer countNumberBigdataTemplate(Map<String, Object> params) throws SearchException {
        Integer count = bigdataTemplateDao.countBigdataTemplate(params);
        return count == null ? 0 : count;
    }

    @Override
    public SuccessResultData<Integer> countBigdataTemplate(Map<String, Object> params) throws SearchException {
        return new SuccessResultData<>(countNumberBigdataTemplate(params));
    }

    @Override
    public SuccessResult buiderBigdataTemplateByBigdataTemplateCode(String bigdataTemplateCode) throws Exception {
        Map<String, Object> params = super.getHashMap(1);
        params.put("bigdataTemplateCode", bigdataTemplateCode);
        BigdataTemplateDTO dto = bigdataTemplateDao.getBigdataTemplateByCode(bigdataTemplateCode);
        List<BigdataTemplateAreaDTO> areaList = iBigdataTemplateAreaService.getBigdataTemplateAreaByBigdataTemplateId(dto.getBigdataTemplateId());
        // 封装自定义上传的js和css文件
        for (BigdataTemplateAreaDTO area : areaList) {
            // 查找模块附件
            String[] fileList = area.getTemplateAreaFile().split(",");
            List<BigdataTemplateAreaFileDTO> templateAreaFileDTOList = new ArrayList<BigdataTemplateAreaFileDTO>();
            for (String file : fileList) {
                Map<String, Object> queryParams = super.getHashMap(1);
                queryParams.put("fileId", file);
                FilePO filePO = iFileService.getFile(queryParams);
                    if(filePO != null) {
                    BigdataTemplateAreaFileDTO fileDTO = new BigdataTemplateAreaFileDTO();
                    fileDTO.setTemplateAreaFile(file);
                    fileDTO.setTemplateAreaFileType(filePO.getFileType());
                    templateAreaFileDTOList.add(fileDTO);
                }
            }
            area.setFileList(templateAreaFileDTOList);
            // 查询跳转模板
            if(!StringUtils.isEmpty(area.getTemplateAreaJumpTemplateId())) {
                BigdataTemplateDTO bigdataTemplateDTO = getBigdataTemplateById(area.getTemplateAreaJumpTemplateId());
                if(bigdataTemplateDTO != null) {
                    area.setBigdataTemplateJumpUrl(bigdataTemplateDTO.getBigdataTemplateUrl());
                    area.setBigdataTemplateJumpTitle(bigdataTemplateDTO.getBigdataTemplateTitle());
                    area.setBigdataTemplateJumpHeight(bigdataTemplateDTO.getBigdataTemplateHeight());
                    area.setBigdataTemplateJumpWidth(bigdataTemplateDTO.getBigdataTemplateWidth());
                }
            }
        }
        // 查找模板附件
        String[] templateFileList = dto.getBigdataTemplateFile().split(",");
        List<BigdataTemplateFileDTO> templateFileDTOList = new ArrayList<BigdataTemplateFileDTO>();
        for (String templateFile : templateFileList) {
            Map<String, Object> queryFileParams = super.getHashMap(1);
            queryFileParams.put("fileId", templateFile);
            FilePO dDDto = iFileService.getFile(queryFileParams);
            if(dDDto != null) {
                BigdataTemplateFileDTO fileDTO = new BigdataTemplateFileDTO();
                fileDTO.setBigdataTemplateFile(dDDto.getFileId());
                fileDTO.setBigdataTemplateFilePath(dDDto.getFilePath());
                fileDTO.setBigdataTemplateFileType(dDDto.getFileType());
                templateFileDTOList.add(fileDTO);
            }
        }

        dto.setFileList(templateFileDTOList);
        dto.setAreaList(areaList);
        Map<String, Object> templateDataMap = HashMapUtil.beanToMap(dto);
        TemplateCreateData createData = new TemplateCreateData();
        createData.setTemplateCode("C0001");
        createData.setBusinessId(dto.getBigdataTemplateId());
        createData.setBusinessContent(dto.getBigdataTemplateTitle());
        createData.setTemplateDataMap(templateDataMap);

        TemplateRecordVO recordVo =  TemplateBuilderUtil.getInstance().createFile(createData);
        /**
         * 更新访问路径
         */
        Map<String, Object> updateParams = super.getHashMap(2);
        updateParams.put("bigdataTemplateUrl", recordVo.getTemplateRecordUrl());
        updateParams.put("bigdataTemplateId", dto.getBigdataTemplateId());
        bigdataTemplateDao.updataBigdataTemplateUrl(updateParams);

        return new SuccessResult();
    }

    @Override
    public SuccessResult updateBigdataTemplatePublishStatus(String bigdataTemplateId, Boolean bigdataTemplatePublishStatus) throws Exception {
        Map<String, Object> params = HashMapUtil.beanToMap(3);
        params.put("bigdataTemplateId", bigdataTemplateId);
        params.put("bigdataTemplatePublishStatus", bigdataTemplatePublishStatus ? "1" : "0");
        params.put("bigdataTemplatePublishTime", DateUtil.getTime());
        setUpdateInfo(params);
        bigdataTemplateDao.updateBigdataTemplatePublishStatus(params);
        return new SuccessResult();
    }

    @Override
    public SuccessResult buiderBigdataTemplateAll() throws Exception {
        Map<String, Object> params = HashMapUtil.beanToMap(3);
        params.put("bigdataTemplatePublishStatus", "1");
        List<BigdataTemplateDTO> dtos = listBigdataTemplate(params);
        for (BigdataTemplateDTO dto : dtos) {
            buiderBigdataTemplateByBigdataTemplateCode(dto.getBigdataTemplateCode());
        }
        return new SuccessResult();
    }

}