package com.flossom.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.flossom.common.core.domain.entity.SysTag;
import com.flossom.common.core.domain.entity.WxScriptTag;
import com.flossom.common.core.domain.entity.WxScriptTemplate;
import com.flossom.common.core.domain.vo.TreeSelect;
import com.flossom.common.core.enums.TagTypeStatusEnum;
import com.flossom.common.core.mapper.SysTagMapper;
import com.flossom.common.core.mapper.WxScriptTagMapper;
import com.flossom.common.core.mapper.WxScriptTemplateMapper;
import com.flossom.common.core.utils.DateUtils;
import com.flossom.common.core.utils.StringUtils;
import com.flossom.common.security.utils.SecurityUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.flossom.system.service.IWxScriptTemplateService;
import org.springframework.util.CollectionUtils;

/**
 * 话术模板Service业务层处理
 *
 * @author flossom
 * @date 2023-12-18
 */
@Service
public class WxScriptTemplateServiceImpl implements IWxScriptTemplateService {
    @Autowired
    private WxScriptTemplateMapper wxScriptTemplateMapper;
    @Autowired
    private WxScriptTagMapper wxScriptTagMapper;
    @Autowired
    private SysTagMapper sysTagMapper;

    /**
     * 查询话术模板
     *
     * @param id 话术模板主键
     * @return 话术模板
     */
    @Override
    public WxScriptTemplate selectWxScriptTemplateById(Long id) {
        WxScriptTemplate scriptTemplate = wxScriptTemplateMapper.selectWxScriptTemplateById(id);
        // 处理标签关系
        List<Long> wechatTagList = Lists.newArrayList();
        List<Long> companyTagList = Lists.newArrayList();
        WxScriptTag scriptTag = new WxScriptTag();
        scriptTag.setScriptId(id);
        // 获取所有的标签
        List<WxScriptTag> wxScriptTagList = wxScriptTagMapper.selectWxScriptTagList(scriptTag);
        for (WxScriptTag wxScriptTag: wxScriptTagList) {
            SysTag sysTag = sysTagMapper.selectDeptById(wxScriptTag.getTagId());
            if (TagTypeStatusEnum.MINI_PROGRAM.getCode().toString().equals(sysTag.getType())){
                wechatTagList.add(sysTag.getId());
            } else {
                companyTagList.add(sysTag.getId());
            }
        }
        scriptTemplate.setTagIdArray(wechatTagList);
        scriptTemplate.setCompanyIdArray(companyTagList);
        return scriptTemplate;
    }

    /**
     * 查询话术模板列表
     *
     * @param wxScriptTemplate 话术模板
     * @return 话术模板
     */
    @Override
    public List<WxScriptTemplate> selectWxScriptTemplateList(WxScriptTemplate wxScriptTemplate) {
        List<WxScriptTemplate> templateList = wxScriptTemplateMapper.selectWxScriptTemplateList(wxScriptTemplate);
        // 处理标签关系
        for (WxScriptTemplate scriptTemplate : templateList) {
            List<SysTag> wechatTagList = Lists.newArrayList();
            List<SysTag> companyTagList = Lists.newArrayList();
            Long id = scriptTemplate.getId();
            WxScriptTag scriptTag = new WxScriptTag();
            scriptTag.setScriptId(id);
            // 获取所有的标签
            List<WxScriptTag> wxScriptTagList = wxScriptTagMapper.selectWxScriptTagList(scriptTag);
            for (WxScriptTag wxScriptTag: wxScriptTagList) {
                SysTag sysTag = sysTagMapper.selectDeptById(wxScriptTag.getTagId());
                if (Objects.nonNull(sysTag)) {
                    if (String.valueOf(TagTypeStatusEnum.MINI_PROGRAM.getCode()).equals(sysTag.getType())){
                        wechatTagList.add(sysTag);
                    } else {
                        companyTagList.add(sysTag);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(wechatTagList)){
                String wechatNames = wechatTagList.stream().map(SysTag::getTagName).collect(Collectors.joining(","));
                scriptTemplate.setTagNames(wechatNames);
            }
            if (!CollectionUtils.isEmpty(companyTagList)){
                String companyTagsNames = companyTagList.stream().map(SysTag::getTagName).collect(Collectors.joining(","));
                scriptTemplate.setCompanyTagNames(companyTagsNames);
            }
//            scriptTemplate.setTagIdArray(wechatTagList);
//            scriptTemplate.setCompanyIdArray(companyTagList);
        }
        return templateList;
    }

    /**
     * 新增话术模板
     *
     * @param wxScriptTemplate 话术模板
     * @return 结果
     */
    @Override
    public int insertWxScriptTemplate(WxScriptTemplate wxScriptTemplate) {
        wxScriptTemplate.setCreateTime(DateUtils.getNowDate());
        wxScriptTemplate.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        List<SysTag> sysTags = Lists.newArrayList();
        // 处理标签在字段的展示
        List<Long> tagIds = wxScriptTemplate.getTagIdArray();
        if (!CollectionUtils.isEmpty(tagIds)) {
            for (long tagId : tagIds) {
                SysTag sysTag = sysTagMapper.selectDeptById(tagId);
                if (Objects.nonNull(sysTag)) {
                    sysTags.add(sysTag);
                }
            }
        }
        List<Long> companyIdArray = wxScriptTemplate.getCompanyIdArray();
        if (!CollectionUtils.isEmpty(companyIdArray)) {
            for (long tagId : companyIdArray) {
                SysTag sysTag = sysTagMapper.selectDeptById(tagId);
                if (Objects.nonNull(sysTag)) {
                    sysTags.add(sysTag);
                }
            }
        }
//        if (!CollectionUtils.isEmpty(sysTags)) {
//            String tagNames = sysTags.stream().map(SysTag::getTagName).collect(Collectors.joining(","));
//            wxScriptTemplate.setTagNames(tagNames);
//            List<Long> resultList = sysTags.stream().map(SysTag::getId).collect(Collectors.toList());
//            String ids = StringUtils.join(resultList, ",");
//            wxScriptTemplate.setTagIds(ids);
//        }

        int i = wxScriptTemplateMapper.insertWxScriptTemplate(wxScriptTemplate);

        for (SysTag tag : sysTags) {
            // 增加关联关系
            WxScriptTag scriptTag = new WxScriptTag();
            scriptTag.setScriptId(wxScriptTemplate.getId());
            scriptTag.setTagId(tag.getId());
            if(TagTypeStatusEnum.MINI_PROGRAM.getCode() == wxScriptTemplate.getLevel().intValue()) {
                scriptTag.setTagType(TagTypeStatusEnum.MINI_PROGRAM.getCode());
            } else {
                scriptTag.setTagType(TagTypeStatusEnum.ENTERPRISE_WECHAT.getCode());
            }
            scriptTag.setStatus(0l);
            scriptTag.setCreateBy(SecurityUtils.getLoginUser().getUsername());
            scriptTag.setCreateTime(DateUtils.getNowDate());
            wxScriptTagMapper.insertWxScriptTag(scriptTag);
        }
        return i;
    }

    /**
     * 修改话术模板
     *
     * @param wxScriptTemplate 话术模板
     * @return 结果
     */
    @Override
    public int updateWxScriptTemplate(WxScriptTemplate wxScriptTemplate) {
        wxScriptTemplate.setUpdateTime(DateUtils.getNowDate());
        wxScriptTemplate.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
        wxScriptTemplate.setTagIds("");
        wxScriptTemplate.setTagNames("");
        List<SysTag> sysTags = Lists.newArrayList();
        // 处理标签在字段的展示
        List<Long> tagIds = wxScriptTemplate.getTagIdArray();
        if (!CollectionUtils.isEmpty(tagIds)) {
            for (long tagId : tagIds) {
                SysTag sysTag = sysTagMapper.selectDeptById(tagId);
                if (Objects.nonNull(sysTag)) {
                    sysTags.add(sysTag);
                }
            }
        }
        List<Long> companyIdArray = wxScriptTemplate.getCompanyIdArray();
        if (!CollectionUtils.isEmpty(companyIdArray)) {
            for (long tagId : companyIdArray) {
                SysTag sysTag = sysTagMapper.selectDeptById(tagId);
                if (Objects.nonNull(sysTag)) {
                    sysTags.add(sysTag);
                }
            }
        }
//        if (!CollectionUtils.isEmpty(sysTags)) {
//            String tagNames = sysTags.stream().map(SysTag::getTagName).collect(Collectors.joining(","));
//            wxScriptTemplate.setTagNames(tagNames);
//            List<Long> resultList = sysTags.stream().map(SysTag::getId).collect(Collectors.toList());
//            String ids = StringUtils.join(resultList, ",");
//            wxScriptTemplate.setTagIds(ids);
//        }

        // 先删除原本的关系
        wxScriptTagMapper.deleteWxScriptByScriptId(wxScriptTemplate.getId());

        for (SysTag tag : sysTags) {
            // 增加关联关系
            WxScriptTag scriptTag = new WxScriptTag();
            scriptTag.setScriptId(wxScriptTemplate.getId());
            scriptTag.setTagId(tag.getId());
            if(TagTypeStatusEnum.MINI_PROGRAM.getCode() == Integer.valueOf(tag.getType())) {
                scriptTag.setTagType(TagTypeStatusEnum.MINI_PROGRAM.getCode());
            } else {
                scriptTag.setTagType(TagTypeStatusEnum.ENTERPRISE_WECHAT.getCode());
            }
            scriptTag.setStatus(0l);
            scriptTag.setCreateBy(SecurityUtils.getLoginUser().getUsername());
            scriptTag.setCreateTime(DateUtils.getNowDate());
            wxScriptTagMapper.insertWxScriptTag(scriptTag);
        }
        return wxScriptTemplateMapper.updateWxScriptTemplate(wxScriptTemplate);
    }

    /**
     * 批量删除话术模板
     *
     * @param ids 需要删除的话术模板主键
     * @return 结果
     */
    @Override
    public int deleteWxScriptTemplateByIds(Long[] ids) {
        return wxScriptTemplateMapper.deleteWxScriptTemplateByIds(ids);
    }

    /**
     * 删除话术模板信息
     *
     * @param id 话术模板主键
     * @return 结果
     */
    @Override
    public int deleteWxScriptTemplateById(Long id) {
        // 先删除原本的关系
        int i = wxScriptTagMapper.deleteWxScriptByScriptId(id);
        return wxScriptTemplateMapper.deleteWxScriptTemplateById(id);
    }

    @Override
    public boolean hasChildByScriptId(Long id) {
        int result = wxScriptTemplateMapper.hasChildByScriptId(id);
        return result > 0;
    }

    @Override
    public List<TreeSelect> scriptTree(WxScriptTemplate wxScriptTemplate) {
        List<WxScriptTemplate> wxScriptTemplateList = this.selectWxScriptTemplateList(wxScriptTemplate);
        return buildTree(wxScriptTemplateList);
    }

    public List<TreeSelect> buildTree(List<WxScriptTemplate> wxScriptTemplateList) {
        List<WxScriptTemplate> deptTrees = buildDeptTree(wxScriptTemplateList);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    public List<WxScriptTemplate> buildDeptTree(List<WxScriptTemplate> wxScriptTemplateList) {
        List<WxScriptTemplate> returnList = new ArrayList<>();
        List<Long> tempList = wxScriptTemplateList.stream().map(WxScriptTemplate::getId).collect(Collectors.toList());
        for (WxScriptTemplate wxScriptTemplate : wxScriptTemplateList) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(wxScriptTemplate.getParentId())) {
                recursionFn(wxScriptTemplateList, wxScriptTemplate);
                returnList.add(wxScriptTemplate);
            }
        }
        if (returnList.isEmpty()) {
            returnList = wxScriptTemplateList;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<WxScriptTemplate> list, WxScriptTemplate t) {
        // 得到子节点列表
        List<WxScriptTemplate> childList = getChildList(list, t);
        t.setScriptTemplateChildren(childList);
        for (WxScriptTemplate tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<WxScriptTemplate> getChildList(List<WxScriptTemplate> list, WxScriptTemplate t) {
        List<WxScriptTemplate> tlist = new ArrayList<>();
        Iterator<WxScriptTemplate> it = list.iterator();
        while (it.hasNext()) {
            WxScriptTemplate n = (WxScriptTemplate) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<WxScriptTemplate> list, WxScriptTemplate t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }

}
