package com.zjrs.zwnw.bsdb.blo.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.mohrss.leaf.core.framework.domain.blo.impl.BLOImpl;
import org.mohrss.leaf.core.framework.persistens.PageResult;
import org.mohrss.leaf.core.framework.persistens.PageUtil;
import org.mohrss.leaf.core.framework.util.CurrentUser;
import org.mohrss.leaf.core.framework.web.exception.AppException;
import com.zjrs.zwnw.bsdb.blo.DbsxBLO;
import com.zjrs.zwnw.bsdb.dto.*;
import com.zjrs.zwnw.bsdb.entity.DbgzMapper;
import com.zjrs.zwnw.bsdb.entity.DbsxMapper;
import com.zjrs.zwnw.bsdb.po.RsBsdbDbgzPo;
import com.zjrs.zwnw.bsdb.po.RsBsdbDbsxPo;
import com.zjrs.zwnw.bsdb.util.AppUtils;
import com.zjrs.zwnw.portal.blo.InformationBLO;
import com.zjrs.zwnw.portal.dto.SendInformationDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DbsxBLOImpl extends BLOImpl implements DbsxBLO {

    private static String RS_BSDB_SXLX = "RS_BSDB_SXLX";

    private static String RS_BSDB_JDZT = "RS_BSDB_JDZT";

    private static String SX_SXLB = "SX_SXLB";

    private static String RS_SX_CONFIG_YWZT = "RS_SX_CONFIG_YWZT";

    @Resource
    DbsxMapper dbsxMapper;

    @Resource
    DbgzMapper dbgzMapper;

    @Resource
    private InformationBLO informationBLO;

    @Override
    public PageResult queryDbglWorkspaceDbList(DbglPageQueryDTO dto) {
        Page<DbglDTO> page = new Page<>(dto.getPagenum(), dto.getPagesize());
        CurrentUser user = getCurrentUser();
        dto.setBae002(user.getUserid());
        Page<DbglDTO> pageResult = (Page) dbsxMapper.queryDbglWorkspaceDbList(page, dto);
        return PageUtil.PageResult(pageResult);
    }

    @Override
    public PageResult queryDbglWorkspaceYbList(DbglPageQueryDTO dto) {
        Page<DbglDTO> page = new Page<>(dto.getPagenum(), dto.getPagesize());
        CurrentUser user = getCurrentUser();
        dto.setBae002(user.getUserid());
        Page<DbglDTO> pageResult = (Page) dbsxMapper.queryDbglWorkspaceYbList(page, dto);
        return PageUtil.PageResult(pageResult);
    }

    @Override
    public PageResult queryDbglTimeoutList(VRsSlxxRemaindatePageQueryDTO dto) {
        Page<VRsSlxxRemaindateDTO> page = new Page<>(dto.getPagenum(), dto.getPagesize());
        Page<VRsSlxxRemaindateDTO> pageResult = (Page) dbsxMapper.queryDbglTimeoutList(page, dto);
        return PageUtil.PageResult(pageResult);
    }

    @Override
    public PageResult queryDbglDbList(DbglPageQueryDTO dto) {
        CurrentUser user = getCurrentUser();
        dto.setBae002(user.getUserid());
        return this.queryDbglList(dto);
    }

    @Override
    public PageResult queryDbglYbList(DbglPageQueryDTO dto) {
        CurrentUser user = getCurrentUser();
        dto.setBae002(user.getUserid());
        return this.queryDbglList(dto);
    }

    @Override
    public PageResult queryDbglList(DbglPageQueryDTO dto) {
        Page<DbglDTO> page = new Page<>(dto.getPagenum(), dto.getPagesize());
        Page<DbglDTO> pageResult = (Page) dbsxMapper.queryDbglList(page, dto);
        return PageUtil.PageResult(pageResult);
    }

    @Override
    public RsBsdbDbsxDTO dbglQuery(DbglQueryDTO dto) {
        QueryWrapper<RsBsdbDbsxPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rs_bsdb_dbsx", dto.getRsbsdbdbsxlsh());

        RsBsdbDbsxPo rsBsdbDbsxPo = dbsxMapper.selectOne(queryWrapper);

        RsBsdbDbsxDTO rsBsdbDbsxDto = new RsBsdbDbsxDTO();
        BeanUtils.copyProperties(rsBsdbDbsxPo, rsBsdbDbsxDto);
        return rsBsdbDbsxDto;
    }

    @Override
    public RsBsdbDbsxDTO dbglSave(RsBsdbDbsxSaveDTO dto) {
        RsBsdbDbsxPo rsBsdbDbsxPo = new RsBsdbDbsxPo();
        BeanUtils.copyProperties(dto, rsBsdbDbsxPo);

        if (StringUtils.isBlank(dto.getRsbsdbdbsxlsh())) {
            rsBsdbDbsxPo.setYwlsh(this.getRsBsdbDbsxSeq());
            AppUtils.initParams(rsBsdbDbsxPo);
            dbsxMapper.insert(rsBsdbDbsxPo);
        } else {
            AppUtils.updateParams(rsBsdbDbsxPo);
            dbsxMapper.updateById(rsBsdbDbsxPo);
        }

        return getRtnRsBsdbDbsxDTO(rsBsdbDbsxPo.getRsbsdbdbsxlsh());
    }

    @Override
    public void dbglDelete(DbglDeleteDTO dto) {
        String[] rsbsdbdbsxlshs = dto.getRsbsdbdbsxlsh().split(",");

        RsBsdbDbsxPo rsBsdbDbsxPo = null;
        for(String rsbsdbdbsxlsh : rsbsdbdbsxlshs) {
            rsBsdbDbsxPo = new RsBsdbDbsxPo();
            rsBsdbDbsxPo.setRsbsdbdbsxlsh(rsbsdbdbsxlsh);
            rsBsdbDbsxPo.setTsyxbz("0");
            dbsxMapper.updateById(rsBsdbDbsxPo);
        }
    }

    @Override
    public void dbglPublish(DbglPublishDTO dto) {

        RsBsdbDbsxPo rsBsdbDbsxPo = new RsBsdbDbsxPo();
        rsBsdbDbsxPo.setRsbsdbdbsxlsh(dto.getRsbsdbdbsxlsh());
        rsBsdbDbsxPo.setRsbsdbfbzt(dto.getRsbsdbfbzt());
        dbsxMapper.updateById(rsBsdbDbsxPo);

        // 站内信息, 短信发送
        RsBsdbDbsxDTO rsBsdbDbsxDTO = getRtnRsBsdbDbsxDTO(dto.getRsbsdbdbsxlsh());
        SmsUserDTO smsUser = dbsxMapper.querySSgUser(rsBsdbDbsxDTO.getDbr());
        StringBuilder stringBuilder = new StringBuilder();

        this.sendMessage(smsUser, stringBuilder.toString());
    }

    @Override
    public void dbglUrge(DbglQueryDTO dto) {
        StringBuilder stringBuilder = new StringBuilder();
        List<String> userids = new ArrayList<>();
        SmsUserDTO smsUser = null;

        QueryWrapper<RsBsdbDbsxPo> queryWrapper = new QueryWrapper<>();
        RsBsdbDbsxPo rsBsdbDbsxPo = dbsxMapper.selectOne(queryWrapper);

        QueryWrapper<RsBsdbDbgzPo> queryWrapper01 = new QueryWrapper<>();
        RsBsdbDbgzPo rsBsdbDbgzPo = dbgzMapper.selectOne(queryWrapper01);

        // 如果未设置规则, 则催办督办人
        if(rsBsdbDbgzPo == null) {
            // 信息接受人流水号集合
            String dbr = rsBsdbDbsxPo.getDbr();
            userids.add(dbr);
            smsUser = dbsxMapper.querySSgUser(dbr);
            stringBuilder.append(smsUser.getUsername()).append("先生/女士, 您好, 您处理的").append(rsBsdbDbsxPo.getRsbsdbsxmc())
                    .append("事项, 请加快处理, 尽快制定规则派发给相关负责人处理！");
        } 

        this.sendMessage(smsUser, stringBuilder.toString());
    }

    @Override
    public void dbglFeedback(DbglFeedbackSaveDTO dto) {
        RsBsdbDbsxPo rsBsdbDbsxPo = new RsBsdbDbsxPo();
        BeanUtils.copyProperties(dto, rsBsdbDbsxPo);
        dbsxMapper.updateById(rsBsdbDbsxPo);
    }

    @Override
    public void dbglFeedbackSubmit(DbglFeedbackSaveDTO dto) {
        RsBsdbDbsxDTO rsBsdbDbsxDTO = getRtnRsBsdbDbsxDTO(dto.getRsbsdbdbsxlsh());

        RsBsdbDbsxPo rsBsdbDbsxPo = new RsBsdbDbsxPo();
        BeanUtils.copyProperties(dto, rsBsdbDbsxPo);
        rsBsdbDbsxPo.setRsbsdbfkzt("1");
        rsBsdbDbsxPo.setRsbsdbjdzt(Jdzt.YFK.getValue());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        rsBsdbDbsxPo.setRsbsdbfksj(df.format(new Date()));
        dbsxMapper.updateById(rsBsdbDbsxPo);

        SmsUserDTO smsUser = dbsxMapper.querySSgUser(rsBsdbDbsxDTO.getBae002());
        // 发送站内信息和短信
        StringBuilder stringBuilder = new StringBuilder();
        this.sendMessage(smsUser, stringBuilder.toString());
    }


    @Override
    public RsBsdbDbsxDTO dbglAppraise(DbglAppraiseSaveDTO dto) {

        RsBsdbDbsxDTO rsBsdbDbsxDTO = getRtnRsBsdbDbsxDTO(dto.getRsbsdbdbsxlsh());

        String rsbsdbfkzt = rsBsdbDbsxDTO.getRsbsdbfkzt();
        if(!StringUtils.equals("1", rsbsdbfkzt)) {
            throw new AppException("当前督办事项未进行反馈, 请核查");
        }
        // 保存评价信息
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dto.setRsbsdbpjr(getCurrentUser().getUserid());
        dto.setRsbsdbpjsj(df.format(new Date()));
        dto.setRsbsdbpjzt("1");
        dto.setRsbsdbjdzt(Jdzt.YJS.getValue());

        RsBsdbDbsxPo rsBsdbDbsxPo = new RsBsdbDbsxPo();
        BeanUtils.copyProperties(dto, rsBsdbDbsxPo);
        dbsxMapper.updateById(rsBsdbDbsxPo);

        SmsUserDTO smsUser = dbsxMapper.querySSgUser(rsBsdbDbsxDTO.getFzr());
        // 发送站内信息和短信
        StringBuilder stringBuilder = new StringBuilder();
        this.sendMessage(smsUser, stringBuilder.toString());

        SmsUserDTO smsUser02 = dbsxMapper.querySSgUser(rsBsdbDbsxDTO.getDbr());
        // 发送站内信息和短信
        StringBuilder stringBuilder02 = new StringBuilder();
        this.sendMessage(smsUser02, stringBuilder02.toString());

        return rsBsdbDbsxDTO;
    }

    @Override
    public PageResult queryReportformsList(DbglPageQueryDTO dto) {
        Page<DbglDTO> page = new Page<>(dto.getPagenum(), dto.getPagesize());
        Page<DbglDTO> pageResult = (Page) dbsxMapper.queryReportformsList(page, dto);
        return PageUtil.PageResult(pageResult);
    }

    @Override
    public Map<String, Object> queryReportforms(DbglReportFormsQueryDTO dto) {
        Map<String, Object> result = new HashMap<>();

        // 督办事项合计
        Map<String, Object> statis01Value = dbsxMapper.queryStatisForDbsxhj(dto);

        // 督办事项分类统计
        Map<String, String> dictParams = new HashMap<>();
        List<Map<String, Object>> statis02Value = dbsxMapper.queryStatisForDbsxfltj(dto);

        List<Map<String, Object>> dict_rsbsdbsxlx = dbsxMapper.queryGgfwDictForList(dictParams);
        // 督办事项状态统计
        List<Map<String, Object>> statis03Value = dbsxMapper.queryStatisForDbsxzttj(dto);

        List<Map<String, Object>> dict_rsbsdbjdzt = dbsxMapper.queryGgfwDictForList(dictParams);
        result.put("pie_charts_statis_02", list2ChartsResult(dict_rsbsdbjdzt, statis03Value));

        // 业务事项分类统计
        List<Map<String, Object>> statis04Value = dbsxMapper.queryStatisForYwsxfltj(dto);

        dictParams.put("aaa100", RS_SX_CONFIG_YWZT);
        List<Map<String, Object>> dict_rssxconfigywzt = dbsxMapper.queryGgfwDictForList(dictParams);
        List<Map<String, Object>> bar_charts_statis_01_result = list2ChartsResult(dict_rssxconfigywzt, statis04Value);


        // 负责单位事项统计
        List<Map<String, Object>> statis05Value = dbsxMapper.queryStatisForFzdwsxtj(dto);

//        dictParams.put("aaa100", SX_SXLB);
//        List<Map<String, Object>> dict_rsbsdbfzdw = dbsxMapper.queryGgfwDictForList(dictParams);
        List<Map<String, Object>> dict_rsbsdbfzdw = dbsxMapper.queryBsdbSysOrgForList(dictParams);
        result.put("bar_charts_statit", list2ChartsResult(dict_rsbsdbfzdw, statis05Value));

        return result;
    }

    @Override
    public Map<String, Object> queryStatisForFzdwsxtj(DbglReportFormsQueryDTO dto) {
        Map<String, Object> result = new HashMap<>();

        // 督办事项分类统计
        Map<String, String> dictParams = new HashMap<>();
        // 负责单位事项统计
        List<Map<String, Object>> statis05Value = dbsxMapper.queryStatisForFzdwsxtj(dto);

//        dictParams.put("aaa100", SX_SXLB);
//        List<Map<String, Object>> dict_rsbsdbfzdw = dbsxMapper.queryGgfwDictForList(dictParams);
        List<Map<String, Object>> dict_rsbsdbfzdw = dbsxMapper.queryBsdbSysOrgForList(dictParams);
        result.put("bar_charts_statist", list2ChartsResult(dict_rsbsdbfzdw, statis05Value));

        return result;
    }

    private List<Map<String, Object>> list2ChartsResult(List<Map<String, Object>> target, List<Map<String, Object>> source) {
        List<Map<String, Object>> chartResults = new ArrayList<>();
        Map<String, Object> result = null;
        for(Map<String, Object> t : target) {
            result = new HashMap<>();
            String t_name = MapUtils.getString(t, "name");
            result.put("type", t_name);
            chartResults.add(result);
        }
        return chartResults;
    }

    @Override
    public Map<String, String> queryProcess(DbglQueryDTO dto) {
        Map<String, String> result = new HashMap<>();

        QueryWrapper<RsBsdbDbsxPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rs_bsdb_dbsx", dto.getRsbsdbdbsxlsh());

        RsBsdbDbsxPo rsBsdbDbsxPo = dbsxMapper.selectOne(queryWrapper);

        QueryWrapper<RsBsdbDbgzPo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("rs_bsdb_dbsx", dto.getRsbsdbdbsxlsh());

        RsBsdbDbgzPo rsBsdbDbgzPo = dbgzMapper.selectOne(queryWrapper2);

        return result;
    }

    /**
     * 根据流水号获取督办事项信息
     * @param rsbsdbdbsxlsh
     * @return
     */
    private RsBsdbDbsxDTO getRtnRsBsdbDbsxDTO(String rsbsdbdbsxlsh) {
        RsBsdbDbsxDTO rsBsdbDbsxDto = new RsBsdbDbsxDTO();

        QueryWrapper<RsBsdbDbsxPo> queryWrapper = new QueryWrapper<>();

        RsBsdbDbsxPo rtnPo = dbsxMapper.selectOne(queryWrapper);
        BeanUtils.copyProperties(rtnPo, rsBsdbDbsxDto);

        return rsBsdbDbsxDto;
    }

    /**
     * 查询用户树
     * @param params
     * @return
     */
    public List<TreeNodeDTO> queryUserTree(Map<String, Object> params){
        List<TreeNodeDTO> userTree = new ArrayList<>();

        Map<String, Object> treeParams = new HashMap<>();
        // 一级单位节点查询
        List<TreeNodeDTO> firstOrgTreeNodeList = dbsxMapper.querySSgOrgList(treeParams);
        List<TreeNodeDTO> seconedOrgTreeNodeList = dbsxMapper.querySSgOrgList(treeParams);
        // 三级用户节点查询
        List<TreeNodeDTO> userTreeNodeList = dbsxMapper.querySSgUserList();

        for(TreeNodeDTO second : seconedOrgTreeNodeList) {
            String value = second.getValue();
            second.setDisabled(true);
            List<TreeNodeDTO> childrenTreeNode = new ArrayList<>();
            for(TreeNodeDTO user : userTreeNodeList) {
                String pid = user.getPid();
                if(value.equals(pid)) {
                    childrenTreeNode.add(user);
                }
            }
            if(CollectionUtils.size(childrenTreeNode) > 0) {
                second.setChildren(childrenTreeNode);
            }
        }

        for(TreeNodeDTO first : firstOrgTreeNodeList) {
            String value = first.getValue();
            first.setDisabled(true);
            List<TreeNodeDTO> childrenTreeNode = new ArrayList<>();
            for(TreeNodeDTO second : seconedOrgTreeNodeList) {
                String pid = second.getPid();
                if(value.equals(pid)) {
                    childrenTreeNode.add(second);
                }
            }
            if(CollectionUtils.size(childrenTreeNode) > 0) {
                first.setChildren(childrenTreeNode);
            }
        }

        userTree.addAll(firstOrgTreeNodeList);
        return userTree;
    }


    @Override
    public List<TreeNodeDTO> queryUserOrg(Map<String, Object> params) {
        CurrentUser user = getCurrentUser();
        String userOrgId = user.getOrgid();
        String areaId = dbsxMapper.queryUserAreaId(userOrgId);

        Map<String, Object> treeParams = new HashMap<>();
        if(StringUtils.isBlank(areaId)) {
            return new ArrayList<>();
        }

        // 一级单位节点查询
        List<TreeNodeDTO> firstOrgTreeNodeList = dbsxMapper.querySSgOrgList(treeParams);
        List<TreeNodeDTO> seconedOrgTreeNodeList = dbsxMapper.querySSgOrgList(treeParams);

        List<TreeNodeDTO> sysOrgTreeNode = new ArrayList<>();
        for(TreeNodeDTO first : firstOrgTreeNodeList) {
            String value = first.getValue();
            List<TreeNodeDTO> childrenTreeNode = new ArrayList<>();
            for(TreeNodeDTO second : seconedOrgTreeNodeList) {
                String pid = second.getPid();
                if(value.equals(pid)) {
                    childrenTreeNode.add(second);
                }
            }
        }

        sysOrgTreeNode.addAll(firstOrgTreeNodeList);

        return sysOrgTreeNode;
    }

    @Override
    public void dbglAssign(DbglAssignDTO dto) {
        String userid = dto.getUserid();
        RsBsdbDbsxPo po = new RsBsdbDbsxPo();
        po.setFzr(userid);
        po.setRsbsdbpfzt("1");
        po.setRsbsdbjdzt(Jdzt.CLZ.getValue());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        po.setRsbsdbpfsj(dateFormat.format(new Date()));
        po.setRsbsdbdbsxlsh(dto.getRsbsdbdbsxlsh());
        String org_id = dbsxMapper.querySSgUserOrgId(userid);
        po.setRsbsdbfzdw(org_id);
        dbsxMapper.updateById(po);
    }


    /**
     * 获取序号
     * @return
     */
    private String getRsBsdbDbsxSeq() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = dateFormat.format(new Date());
        return dateStr;
    }

    /**
     * 发送消息
     * @param smsUser
     * @param message
     */
    private void sendMessage(SmsUserDTO smsUser, String message) {
        CurrentUser currentUser = getCurrentUser();
        // 站内信息
        List<String> sjrid = new ArrayList<>();
        sjrid.add(smsUser.getId());
        SendInformationDTO infodto = new SendInformationDTO("督办事项", message, currentUser.getUserid(), sjrid);
        informationBLO.sendInfo(infodto);
    }
}
