package com.flossom.system.controller;

import com.flossom.common.core.constant.UserConstants;
import com.flossom.common.core.domain.R;
import com.flossom.common.core.domain.entity.SysTag;
import com.flossom.common.core.domain.entity.WxUserTag;
import com.flossom.common.core.enums.TagTypeStatusEnum;
import com.flossom.common.core.utils.DateUtils;
import com.flossom.common.core.utils.StringUtils;
import com.flossom.common.core.utils.poi.ExcelUtil;
import com.flossom.common.core.web.controller.BaseController;
import com.flossom.common.core.web.domain.AjaxResult;
import com.flossom.common.log.annotation.Log;
import com.flossom.common.log.enums.BusinessType;
import com.flossom.common.security.annotation.RequiresPermissions;
import com.flossom.common.security.utils.SecurityUtils;
import com.flossom.system.service.*;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * 标签信息
 *
 * @author flossom
 */
@RestController
@RequestMapping("/tagInfo")
public class SysTagController extends BaseController {
    @Autowired
    private ISysTagService tagService;
    @Autowired
    private IWxUserTagService wxUserTagService;
    @Autowired
    private IWxScriptTagService wxScriptTagService;
    @Autowired
    private IWxUserTagService userTagService;
    @Autowired
    private ISiteInfoService siteInfoService;
    @Autowired
    private IWxModeTagService wxModeTagService;
    /**
     * 获取标签列表
     */
    @RequiresPermissions("system:dept:list")
    @GetMapping("/list")
    public AjaxResult list(SysTag sysTag) {
        List<SysTag> tags = tagService.selectDeptList(sysTag);
        return success(tags);
    }

    /**
     * 查询标签列表（排除节点）
     */
    @RequiresPermissions("system:tagInfo:list")
    @GetMapping("/list/exclude/{id}")
    public AjaxResult excludeChild(@PathVariable(value = "id", required = false) Long id) {
        List<SysTag> tags = tagService.selectDeptList(new SysTag());
        tags.removeIf(d -> d.getId().intValue() == id || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), id + ""));
        return success(tags);
    }

    /**
     * 根据标签编号获取详细信息
     */
    @RequiresPermissions("system:tagInfo:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        tagService.checkDeptDataScope(id);
        return success(tagService.selectDeptById(id));
    }

    /**
     * 新增标签
     */
    @RequiresPermissions("system:tagInfo:add")
    @Log(title = "标签管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysTag tag) {
        if (!tagService.checkDeptNameUnique(tag)) {
            return error("新增标签'" + tag.getTagName() + "'失败，标签名称已存在");
        }
        // 获取到父标签，检查是否顶级标签
//        if (Objects.isNull(tag.getParentId())) {
//            return error("父标签不能为空");
//        }
//        SysTag sysParentTag = tagService.selectDeptById(tag.getParentId());
//        if (Objects.isNull(sysParentTag)) {
//            return error("父标签不存在");
//        }
//        if (!"0".equals(sysParentTag.getParentId().toString())) {
//            return error("创建子标签失败,目前只支持二级标签的创建");
//        }
        tag.setCreateBy(SecurityUtils.getUsername());
        return toAjax(tagService.insertDept(tag));
    }

    /**
     * 修改标签
     */
    @RequiresPermissions("system:tagInfo:edit")
    @Log(title = "标签管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysTag tag) {
        Long id = tag.getId();
        tagService.checkDeptDataScope(id);
        if (!tagService.checkDeptNameUnique(tag)) {
            return error("修改标签'" + tag.getTagName() + "'失败，标签名称已存在");
        } else if (tag.getParentId().equals(id)) {
            return error("修改标签'" + tag.getTagName() + "'失败，上级标签不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, tag.getStatus()) && tagService.selectNormalChildrenDeptById(id) > 0) {
            return error("该标签包含未停用的子标签！");
        }
        tag.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(tagService.updateDept(tag));
    }

    /**
     * 删除标签
     */
    @RequiresPermissions("system:dept:remove")
    @Log(title = "标签管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        if (tagService.hasChildByDeptId(id)) {
            return warn("存在下级标签,不允许删除");
        }
        // 删除用户标签
        wxUserTagService.deleteWxUserTagByTagId(id);
        // 删除话术关联标签
        wxScriptTagService.deleteWxScriptTagByTagId(id);
        // 删除站点关联标签
        siteInfoService.deleteSiteInfoByTagId(id);
        // 删除模式关联标签
        wxModeTagService.deleteWxModeTagByTagId(id);
//        if (tagService.checkDeptExistUser(id))
//        {
//            return warn("标签存在用户,不允许删除");
//        }
        tagService.checkDeptDataScope(id);
        return toAjax(tagService.deleteDeptById(id));

    }

    /**
     * 获取标签树列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/tagTree")
    public AjaxResult tagTree(SysTag tag) {
        return success(tagService.selectTagTreeList(tag));
    }

    /**
     * 获取小程序标签
     *
     * @return
     */
    @GetMapping("/getMiniProgramTags")
    public R getMiniProgramTags() {
        return R.ok(tagService.getMiniProgramTags());
    }

    /**
     * 获取外部标签
     *
     * @return
     */
    @GetMapping("/getWecomTags")
    public R getWecomTags() {
        return R.ok(tagService.getWecomTags());
    }

    /**
     * 导出标签信息数据信息
     */
    @RequiresPermissions("system:tagInfo:export")
    @Log(title = "标签信息数据信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysTag tag)
    {
        String sheetName = "";
        String s = DateUtils.dateTimeNow("yyyyMMddHHmmss");
        if (TagTypeStatusEnum.MINI_PROGRAM.getCode().toString().equals(tag.getType())) {
            sheetName += "小程序标签数据"+ s ;
        } else {
            sheetName += "外部标签数据"+ s ;
        }
        List<SysTag> list = tagService.selectDeptList(tag);
        for (SysTag sysTag: list) {
            if (TagTypeStatusEnum.MINI_PROGRAM.getCode().toString().equals(sysTag.getType())) {
                sysTag.setType("小程序标签");
            } else {
                sysTag.setType("外部标签");
            }
            if (0 == sysTag.getParentId()) {
                sysTag.setParentName(sysTag.getTagName());
                sysTag.setTagName("");
            }
            sysTag.setAddTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,sysTag.getCreateTime()));
            WxUserTag userTag = new WxUserTag();
            userTag.setTagId(sysTag.getId());
            List<WxUserTag> wxUserTags = userTagService.selectWxUserTagList(userTag);
            sysTag.setTagUsers(wxUserTags.size());
        }
        // 数据填充好后，处理排序
        List<SysTag> topTagList = Lists.newArrayList();
        List<SysTag> secondTagList = Lists.newArrayList();
        for (SysTag sysTag: list) {
            if(sysTag.getParentId() == 0) {
                topTagList.add(sysTag);
            } else {
                secondTagList.add(sysTag);
            }
        }
        // 构建新的数组
        List<SysTag> resultList = Lists.newArrayList();
        ExcelUtil<SysTag> util = new ExcelUtil<SysTag>(SysTag.class);
        for(SysTag topTag : topTagList) {
            resultList.add(topTag);
            for (SysTag secondTag : secondTagList) {
                if (String.valueOf(secondTag.getParentId()).equals(String.valueOf(topTag.getId())) ) {
                    resultList.add(secondTag);
                }
            }
        }
        util.exportExcel(response, resultList, sheetName);
    }
}
