package cn.com.tenlion.bigdata.service.bigdatamodule.impl;

import cn.com.tenlion.bigdata.dao.bigdatamodule.IBigdataModuleDao;
import cn.com.tenlion.bigdata.dao.bigdatatemplatearea.IBigdataTemplateAreaDao;
import cn.com.tenlion.bigdata.pojo.dtos.bigdatamodule.BigdataModuleDTO;
import cn.com.tenlion.bigdata.pojo.dtos.bigdatatemplatearea.BigdataTemplateAreaDTO;
import cn.com.tenlion.bigdata.pojo.vos.bigdatamodule.BigdataModuleVO;
import cn.com.tenlion.bigdata.service.bigdatamodule.IBigdataModuleService;
import cn.com.tenlion.bigdata.service.bigdatatemplate.IBigdataTemplateService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.util.concurrent.AbstractService;
import ink.wgink.common.base.DefaultBaseService;
import ink.wgink.exceptions.RemoveException;
import ink.wgink.exceptions.SaveException;
import ink.wgink.exceptions.SearchException;
import ink.wgink.exceptions.UpdateException;
import ink.wgink.pojo.ListPage;
import ink.wgink.pojo.result.SuccessResult;
import ink.wgink.pojo.result.SuccessResultData;
import ink.wgink.pojo.result.SuccessResultList;
import ink.wgink.util.UUIDUtil;
import ink.wgink.util.date.DateUtil;
import ink.wgink.util.map.HashMapUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @ClassName: BigdataModuleServiceImpl
 * @Description: 大数据展示模块
 * @Author: WenG
 * @Date: 2020-10-19 16:18
 * @Version: 1.0
 **/
@Service
public class BigdataModuleServiceImpl extends DefaultBaseService implements IBigdataModuleService {

    @Autowired
    private IBigdataModuleDao bigdataModuleDao;
    @Autowired
    private IBigdataTemplateAreaDao iBigdataTemplateAreaDao;

    @Autowired
    private IBigdataTemplateService bigdataTemplateService;


    @Override
    public SuccessResult saveBigdataModule(BigdataModuleVO bigdataModuleVO) throws Exception {
        saveBigdataModuleInfo(null, bigdataModuleVO);
        return new SuccessResult();
    }

    @Override
    public SuccessResult saveBigdataModuleByToken(String token, BigdataModuleVO bigdataModuleVO) throws Exception {
        saveBigdataModuleInfo(token, bigdataModuleVO);
        return new SuccessResult();
    }

    @Override
    public String saveBigdataModuleReturnId(BigdataModuleVO bigdataModuleVO) throws Exception {
        return saveBigdataModuleInfoReturnId(null, bigdataModuleVO);
    }

    @Override
    public String saveBigdataModuleByTokenReturnId(String token, BigdataModuleVO bigdataModuleVO) throws Exception {
        return saveBigdataModuleInfoReturnId(token, bigdataModuleVO);
    }

    /**
     * 新增大数据展示模块
     *
     * @param token
     * @param bigdataModuleVO
     * @throws Exception
     */
    private void saveBigdataModuleInfo(String token, BigdataModuleVO bigdataModuleVO) throws Exception {
        saveBigdataModuleInfoReturnId(token, bigdataModuleVO);
    }

    /**
     * 新增大数据展示模块
     *
     * @param token
     * @param bigdataModuleVO
     * @return bigdataModuleId
     * @throws Exception
     */
    private String saveBigdataModuleInfoReturnId(String token, BigdataModuleVO bigdataModuleVO) throws Exception {
        String bigdataModuleId = UUIDUtil.getUUID();
        /**
         * 判断编码是否已经存在
         */
        BigdataModuleDTO dto = bigdataModuleDao.getBigdataModuleByCode(bigdataModuleVO.getBigdataModuleCode());
        if(dto != null) {
            throw new SaveException("该编码已经存在");
        }
        bigdataModuleVO.setBigdataModuleModuleJson("{id:'" + bigdataModuleVO.getBigdataModuleCode() + "',data:{fontColor:'#fff',loop:true},list:[],title:'" + bigdataModuleVO.getBigdataModuleName() + "',params:{}}");
        bigdataModuleVO.setBigdataModuleServerJson("{data:{},list:[],msg:'加载成功',state:'200'}");
        bigdataModuleVO.setBigdataModuleContent("\n<style type=\"text/css\">\n\t." + bigdataModuleVO.getBigdataModuleCode()+ "{\n\n\t}\n</style>\n<script type=\"text/javascript\">\n\t/**\n" +
                "\t* 将模块的代码封装到此函数中供模板组装调用. \n" +
                "\t* moduleData * 模块数据 {id , data , list , title , params}\n" +
                "\t* serverData * 渲染数据  {data , list , msg , state}\n" +
                "\t* 模块编号 * " + bigdataModuleVO.getBigdataModuleCode() + "\n" +
                "\t* 模块名称 * " + bigdataModuleVO.getBigdataModuleName()+ "\n" +
                "\t* 创建日期 * " + DateUtil.getTime() + "\n" +
                "\t* 使用说明 * 这里阐述该模块的使用说明\n" +
                "\t* # 调用注意 : moduleData.data对象参数为fontColor(字体颜色)与loop(数据轮播)\n" +
                "\t* # 调用注意 : moduleData.list集合为对象, 参数为\n" +
                "\t* # 调用注意 : serverData.data对象参数为\n" +
                "\t* # 调用注意 : serverData.list集合为对象, 参数为\n" +
                "\t*/\n" +
                "\tfunction "+ bigdataModuleVO.getBigdataModuleCode() +"(moduleData, serverData) {\n" +
                "\t\t// 被联动触发\n" +
                "\t\tif(moduleData.params.sponsor) {\n" +
                "\t\t\tconsole.log(moduleData.params.sponsor + \"模块触发了当前模块的联动函数\");\n" +
                "\t\t\tconsole.log(moduleData.params);\n" +
                "\t\t}\n" +
                "\t\tconsole.log(moduleData.id + '初始化...');\n" +
                "\t\t// 清除旧的循环任务\n" +
                "\t\techarts.dispose(document.getElementById(moduleData.id));\n" +
                "\t\tvar elem = echarts.init(document.getElementById(moduleData.id));\n" +
                "\t\tvar option = {\n\n\t\t};\n" +
                "\t\telem.setOption(option);\n" +
                "\t\t\n" +
                "\t\t// ToolTip轮播\n" +
                "\t\tif(moduleData.data.loop == true) {\n" +
                "\t\t\ttools.loopShowTooltip(elem, option, {loopSeries: true});\n" +
                "\t\t}\n" +
                "\t\t\n" +
                "\t\t// 发起联动更新\n" +
                "\t\t// globalData[moduleData.id].linkAllAction('要联动的值');\n" +
                "\t}\n</script>");
        bigdataModuleVO.setBigdataModuleRemark("配置参数格式说明\n" +
                "id:模块编码  ||  " +
                "data:配置参数对象{fontColor(字体颜色),loop(轮播显示)}  ||  " +
                "list:配置参数集合  ||  " +
                "title:展示标题  ||  " +
                "params::联动传入对象{sponsor(发起模块),(动态参数 mapLink、dateLink、selectLink)}\n"+
                "渲染参数格式说明\n" +
                "msg:响应说明  ||  " +
                "state:响应状态200、400  ||  " +
                "data:展示参数对象  ||  " +
                "list:展示数据集合");
        Map<String, Object> params = HashMapUtil.beanToMap(bigdataModuleVO);
        params.put("bigdataModuleId", bigdataModuleId);
        if (StringUtils.isBlank(token)) {
            setSaveInfo(params);
        } else {
            setAppSaveInfo(token, params);
        }
        bigdataModuleDao.saveBigdataModule(params);
        return bigdataModuleId;
    }

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

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

    /**
     * 删除大数据展示模块
     *
     * @param token
     * @param ids
     */
    private void removeBigdataModuleInfo(String token, String ids) {
        Map<String, Object> params = getHashMap(3);
        params.put("bigdataModuleIds", Arrays.asList(ids.split("_")));
        if (StringUtils.isBlank(token)) {
            setUpdateInfo(params);
        } else {
            setAppUpdateInfo(token, params);
        }
        bigdataModuleDao.removeBigdataModule(params);
    }

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

    @Override
    public SuccessResult updateBigdataModule(String bigdataModuleId, BigdataModuleVO bigdataModuleVO) throws Exception {
        updateBigdataModuleInfo(null, bigdataModuleId, bigdataModuleVO);
        return new SuccessResult();
    }

    @Override
    public SuccessResult updateBigdataModuleByToken(String token, String bigdataModuleId, BigdataModuleVO bigdataModuleVO) throws Exception {
        updateBigdataModuleInfo(token, bigdataModuleId, bigdataModuleVO);
        return new SuccessResult();
    }

    /**
     * 修改大数据展示模块
     *
     * @param token
     * @param bigdataModuleId
     * @param bigdataModuleVO
     */
    private void updateBigdataModuleInfo(String token, String bigdataModuleId, BigdataModuleVO bigdataModuleVO) throws Exception {
        Map<String, Object> params = HashMapUtil.beanToMap(bigdataModuleVO);
        params.put("bigdataModuleId", bigdataModuleId);
        if (StringUtils.isBlank(token)) {
            setUpdateInfo(params);
        } else {
            setAppUpdateInfo(token, params);
        }
        bigdataModuleDao.updateBigdataModule(params);
    }

    @Override
    public BigdataModuleDTO getBigdataModuleById(String bigdataModuleId) throws SearchException {
        Map<String, Object> params = super.getHashMap(1);
        params.put("bigdataModuleId", bigdataModuleId);
        BigdataModuleDTO dto = bigdataModuleDao.getBigdataModule(params);
        return dto;
    }

    @Override
    public List<BigdataModuleDTO> listBigdataModule(Map<String, Object> params) throws SearchException {
        return bigdataModuleDao.listBigdataModule(params);
    }

    @Override
    public SuccessResultList<List<BigdataModuleDTO>> listPageBigdataModule(ListPage page) throws SearchException {
        PageHelper.startPage(page.getPage(), page.getRows());
        List<BigdataModuleDTO> bigdataModuleDTOs = bigdataModuleDao.listBigdataModule(page.getParams());
        PageInfo<BigdataModuleDTO> pageInfo = new PageInfo<>(bigdataModuleDTOs);
        return new SuccessResultList<>(bigdataModuleDTOs, pageInfo.getPageNum(), pageInfo.getTotal());
    }

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

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

    @Override
    public SuccessResult updateBigdataModuleContent(String bigdataModuleId, String bigdataModuleContent) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("bigdataModuleId", bigdataModuleId);
        params.put("bigdataModuleContent", bigdataModuleContent);
        if(StringUtils.isEmpty(bigdataModuleContent)) {
            throw new UpdateException("代码内容不能为空!");
        }
        setUpdateInfo(params);
        bigdataModuleDao.updateBigdataModuleContent(params);
        return new SuccessResult();
    }

    @Override
    public SuccessResult updateBigdataModuleSwitch(String bigdataModuleId, Boolean bigdataModuleSwitch) throws Exception {
        Map<String, Object> params = HashMapUtil.beanToMap(3);
        params.put("bigdataModuleId", bigdataModuleId);
        params.put("bigdataModuleSwitch", bigdataModuleSwitch ? "1" : "0");
        setUpdateInfo(params);
        bigdataModuleDao.updateBigdataModuleSwitch(params);
        return new SuccessResult();
    }

    @Override
    public SuccessResult buiderBigdataTemplateAll(String bigdataModuleId) throws Exception {
        Map<String, Object> params = HashMapUtil.beanToMap(3);
        params.put("bigdataModuleId", bigdataModuleId);
        List<BigdataTemplateAreaDTO> list = iBigdataTemplateAreaDao.getBigdataTemplateIdGroupByBigdataModuleId(params);
        for (BigdataTemplateAreaDTO dto : list) {
            bigdataTemplateService.buiderBigdataTemplateByBigdataTemplateCode(dto.getBigdataTemplateCode());
        }
        return new SuccessResult();
    }

}