
package com.huimv.eartag2.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.eartag2.admin.entity.SysAccountMultilevel;
import com.huimv.eartag2.admin.entity.SysOrg;
import com.huimv.eartag2.admin.mapper.SysAccountMultilevelMapper;
import com.huimv.eartag2.admin.mapper.SysOrgMapper;
import com.huimv.eartag2.admin.service.SysOrgService;
import com.huimv.eartag2.common.common.token.TokenSign;
import com.huimv.eartag2.common.utils.Result;
import com.huimv.eartag2.common.utils.ResultCode;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SysOrgServiceImpl extends ServiceImpl<SysOrgMapper, SysOrg> implements SysOrgService {

    @Autowired
    private SysAccountMultilevelMapper multilevelMapper ;

    @Autowired
    private SysAccountMultilevelMapper accountMultilevelMapper ;


    @Override
    public Result page(Map<String,String> map, Integer userId) {
        String pageNum = map.get("pageNum");
        String pageSize = map.get("pageSize");
        String name = map.get("name");
        String orgId = map.get("orgId");

        if (StringUtils.isBlank(pageNum)){
            pageNum ="1";
        }
        if (StringUtils.isBlank(pageSize)){
            pageSize ="10";
        }

        QueryWrapper<SysOrg> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(name),"name",name);
        wrapper.eq("audit",0);
        if (StringUtils.isBlank(orgId)){
            if ( userId != 1){
                SysAccountMultilevel sysAccountMultilevel = multilevelMapper.selectById(userId);
                Long orgId1 = sysAccountMultilevel.getOrgId();
                wrapper.like("pids",orgId1).or().eq("id",orgId1);
            }
        }else {
            wrapper.like("pids",orgId).or().eq("id",orgId);
        }



        wrapper.orderByAsc("sort");
        Page<SysOrg> page = this.page(new Page<>(Long.parseLong(pageNum), Long.parseLong(pageSize)), wrapper);


        return new Result(ResultCode.SUCCESS,page);
    }

    @Override
    public Result list(HttpServletRequest request) {
        Integer userId = TokenSign.getMemberIdByJwtToken(request);
        List<SysOrg> collect;
        //管理员
        if (userId == 1){
            List<SysOrg> list = this.list( new QueryWrapper<SysOrg>().eq("audit",0));

            collect = list.stream()
                    .filter(o -> o.getParentId() == 0)
                    .peek(o -> o.setChildren(getChildrens(o, list)))
                    .collect(Collectors.toList());

        }else {
            SysAccountMultilevel sysAccountMultilevel = multilevelMapper.selectById(userId);
            Long orgId = sysAccountMultilevel.getOrgId();
            QueryWrapper<SysOrg> wrapper = new QueryWrapper<>();

            wrapper.eq("audit",0).like("pids",orgId).or().eq("id",orgId);
            List<SysOrg> list = this.list(wrapper);

            collect = list.stream()
                    .filter(o -> o.getId().equals( orgId))
                    .peek(o -> o.setChildren(getChildrens(o, list)))
                    .collect(Collectors.toList());


        }

        return new Result(ResultCode.SUCCESS,collect);
    }

    private List<SysOrg> getChildrens(SysOrg o, List<SysOrg> list) {

        return list.stream()
                .filter(m -> m.getParentId().equals( o.getId()))
                .peek(m -> m.setChildren(getChildrens(m, list)))
                .collect(Collectors.toList());
    }

    @Override
    public void add(SysOrg sysOrg) {
        Long pid = sysOrg.getParentId();
        SysOrg byId = this.getById(pid);
        if (ObjectUtil.isNotEmpty(byId)){
            String   pids =   byId.getPids();
            sysOrg.setPids(pids+","+pid);
        }else {
            sysOrg.setPids(pid+"");
        }
        this.save(sysOrg);
    }

    @Override
    public void update(SysOrg sysOrg) {

        Long pid = sysOrg.getParentId();
        SysOrg byId = this.getById(pid);
        if (ObjectUtil.isNotEmpty(byId)){
            String   pids =   byId.getPids();
            sysOrg.setPids(pids+","+pid);
        }else {
            sysOrg.setPids(pid+"");
        }
        this.updateById(sysOrg);
    }

    @Override
    public void approval(Map map, HttpServletRequest request) {
        Integer userId = TokenSign.getMemberIdByJwtToken(request);

        String ids = (String)map.get("ids");
        Integer audit = (Integer)map.get("audit");

        String userName = accountMultilevelMapper.selectById(userId).getUserName();
        Date date = new Date();

        for (String s : ids.split(",")) {
            SysOrg sysOrg = new SysOrg();
            sysOrg.setId(Long.parseLong(s));
            sysOrg.setAudit(audit);
            sysOrg.setApprovalId(userId);
            sysOrg.setApprovalName(userName);
            sysOrg.setPassTime(date);
            this.updateById(sysOrg);
        }



    }

    @Override
    @Transactional
    public Result remove(String orgId) {
        for (String s : orgId.split(",")) {
            Integer countUser = multilevelMapper.selectCount(new QueryWrapper<SysAccountMultilevel>().eq("org_id", orgId)).intValue();

            if (countUser>0){
                return new Result(10001,"删除失败，该组织已绑定账号",false);
            }
            //判断组织
//            int pids = this.count(new QueryWrapper<SysOrg>().like("pids", orgId));
//            if (pids >0 ){
//                return new Result(10001,"删除失败，该组织有下属组织",false);
//            }
            this.removeById(s);

        }

        return new Result(10000,"删除成功",false);
    }

    @Override
    public Result page1(Map<String, String> map, Integer userId) {
        String pageNum = map.get("pageNum");
        String pageSize = map.get("pageSize");
        String name = map.get("name");
        String orgId = map.get("orgId");
        String audit = map.get("audit");

        if (StringUtils.isBlank(pageNum)){
            pageNum ="1";
        }
        if (StringUtils.isBlank(pageSize)){
            pageSize ="10";
        }

        QueryWrapper<SysOrg> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(name),"name",name);
        wrapper.eq(StringUtils.isNotBlank(audit),"audit",audit);
        if (StringUtils.isBlank(orgId)){
            if ( userId != 1){
                SysAccountMultilevel sysAccountMultilevel = multilevelMapper.selectById(userId);
                wrapper.like("pids",sysAccountMultilevel.getOrgId());
            }
        }else {
            wrapper.like("pids",orgId).or().eq("id",orgId);
        }



        wrapper.orderByAsc("sort");
        Page<SysOrg> page = this.page(new Page<>(Long.parseLong(pageNum), Long.parseLong(pageSize)), wrapper);


        return new Result(ResultCode.SUCCESS,page);
    }


}
