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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.admin.system.entity.AccountGroup;
import com.huimv.admin.system.entity.AppSysAccountGroup;
import com.huimv.admin.system.entity.ScreenSysAccountGroup;
import com.huimv.admin.system.entity.SysAccountMultilevel;
import com.huimv.admin.system.entity.dto.SysAccountMultilevelDto;
import com.huimv.admin.system.entity.dto.SysAccountMultilevelVo;
import com.huimv.admin.system.mapper.AccountGroupMapper;
import com.huimv.admin.system.mapper.AppAccountGroupMapper;
import com.huimv.admin.system.mapper.ScreenAccountGroupMapper;
import com.huimv.admin.system.mapper.SysAccountMultilevelMapper;
import com.huimv.admin.system.service.*;
import com.huimv.common.utils.Result;
import com.huimv.common.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author astupidcoder
 * @since 2021-10-14
 */
@Service
public class SysAccountMultilevelServiceImpl extends ServiceImpl<SysAccountMultilevelMapper, SysAccountMultilevel> implements ISysAccountMultilevelService {

    @Autowired
    private SysAccountMultilevelMapper accountMultilevelMapper;


    @Autowired
    AppAccountGroupMapper appAccountGroupMapper;

    @Autowired
    AccountGroupMapper pcAccountGroupMapper;

    @Autowired
    ScreenAccountGroupMapper screenAccountGroupMapper;

    @Override
    public Result findUserAccount(String searchStr, int pageNum, int pageSize, Integer userId) {

        QueryWrapper<SysAccountMultilevel> wrapper = new QueryWrapper<>();
        wrapper.like("pids",userId).or().eq("id",userId);
        IPage<SysAccountMultilevel> page = this.page(new Page<>(pageNum, pageSize), wrapper);
        return new Result(ResultCode.SUCCESS,page);
    }

    @Override
    public Result add(SysAccountMultilevel sysAccountMultilevel, Integer userId) {

        int account = this.count(new QueryWrapper<SysAccountMultilevel>().eq("account", sysAccountMultilevel.getAccount()));
        if (account > 0 ){
            return new Result(10001,"该账号已经存在，请重新创建",false);

        }

        SysAccountMultilevel byId = this.getById(userId);


        sysAccountMultilevel.setPid(userId);
        sysAccountMultilevel.setPids(byId.getPids()+","+userId);
        accountMultilevelMapper.insert(sysAccountMultilevel);
        return  new Result( 10000,"添加成功",true);
    }

    @Override
    public Result setAccountStatus(List<Integer> ids, Integer status) {
        try {
            for (Integer id : ids) {
                SysAccountMultilevel account= new SysAccountMultilevel();
                account.setId(id);
                account.setAccountStatus(status);
                this.updateById(account);
            }
        }catch (Exception e){
            return new Result(10001,"插入失败",false);
        }
        String message = "";
        if(status == 1){
            message = "你选择的账号已经启用。";
        }else{
            message = "你选择的账号已经暂停启用。";
        }
        return new Result(10000,message,true);
    }

    @Override
    public List<Integer> getAllChildId(Integer userId) {
        List<SysAccountMultilevel> pids = this.list(new QueryWrapper<SysAccountMultilevel>().like("pids", userId + ""));
        List<Integer> list = new ArrayList<>();
        for (SysAccountMultilevel pid : pids) {
            list.add(pid.getId());
        }
        list.add(userId);
        return list;
    }

    @Override
    public Result listSubordinate(String searchStr, int pageNum, int pageSize, Integer userId) {

        QueryWrapper<SysAccountMultilevel> wrapper = new QueryWrapper<>();
        wrapper.like("pids",userId);
        if (StringUtils.isNotBlank(searchStr)){
            wrapper.like("user_name",searchStr);
        }

        IPage<SysAccountMultilevel> page = this.page(new Page<>(pageNum, pageSize), wrapper);
        List<SysAccountMultilevel> records = page.getRecords();
        List<SysAccountMultilevelVo> list = new ArrayList<>();
        for (SysAccountMultilevel record : records) {
            SysAccountMultilevelVo accountMultilevelVo = new SysAccountMultilevelVo();
            BeanUtil.copyProperties(record,accountMultilevelVo);
            Integer id = record.getId();


            List<AccountGroup> accountGroups = pcAccountGroupMapper.selectList(new QueryWrapper<AccountGroup>().eq("account_id", id));
            List<Integer> pcGroupId = accountGroups.stream().map(AccountGroup::getGroupId).collect(Collectors.toList());
            accountMultilevelVo.setPcGroupId(pcGroupId);

            List<Integer> appGroupId = appAccountGroupMapper.selectList(new QueryWrapper<AppSysAccountGroup>().eq("account_id", id))
                    .stream().map(AppSysAccountGroup::getGroupId).collect(Collectors.toList());
            accountMultilevelVo.setAppGroupId(appGroupId);

            List<Integer> screenGroupId = screenAccountGroupMapper.selectList(new QueryWrapper<ScreenSysAccountGroup>().eq("account_id", id))
                    .stream().map(ScreenSysAccountGroup::getGroupId).collect(Collectors.toList());
            accountMultilevelVo.setScreenGroupId(screenGroupId);

            list.add(accountMultilevelVo);
        }

        IPage<SysAccountMultilevelVo>  endPage = new Page<SysAccountMultilevelVo>();
        endPage.setRecords(list);
        endPage.setSize(page.getSize());
        endPage.setTotal(page.getTotal());
        endPage.setPages(page.getPages());
        endPage.setCurrent(page.getCurrent());

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

    @Override
    public Result getLastFarmId(Integer userId) {
        SysAccountMultilevel sysAccountMultilevel = accountMultilevelMapper.selectById(userId);
        Integer lastFarmId = sysAccountMultilevel.getLastFarmId();
        String farmIds = sysAccountMultilevel.getFarmIds();
        if (farmIds == null){
            return new Result(10001,"该账号没有绑定牧场",true);
        }
        if (lastFarmId == null){
            String[] split = farmIds.split(",");
            String s = split[0];
            sysAccountMultilevel.setLastFarmId(Integer.valueOf(s));
            accountMultilevelMapper.updateById(sysAccountMultilevel);
            return new Result(ResultCode.SUCCESS,s);
        }
        return new Result(ResultCode.SUCCESS,lastFarmId);
    }

    @Autowired
    IAppAuthorizeService iAppAuthorizeService;


    @Autowired
    IAuthorizeService iAuthorizeService;

    @Autowired
    IScreenAuthorizeService iScreenAuthorizeService;



    @Override
    @Transactional
    public Result addApp(SysAccountMultilevelDto sysAccountMultilevel, Integer userId) {
        int account = this.count(new QueryWrapper<SysAccountMultilevel>().eq("account", sysAccountMultilevel.getAccount()));
        if (account > 0 ){
            return new Result(10001,"该账号已经存在，请重新创建",false);

        }

        SysAccountMultilevel byId = this.getById(userId);


        sysAccountMultilevel.setPid(userId);
        sysAccountMultilevel.setPids(byId.getPids()+","+userId);

        SysAccountMultilevel sysAccountMultilevel1 = new SysAccountMultilevel();
        BeanUtil.copyProperties(sysAccountMultilevel,sysAccountMultilevel1);

        accountMultilevelMapper.insert(sysAccountMultilevel1);
        Integer accountId = sysAccountMultilevel1.getId();

        //后台
        List<Integer> pcGroupId = sysAccountMultilevel.getPcGroupId();
        String collect = pcGroupId.stream().map(String::valueOf).collect(Collectors.joining(","));
        iAuthorizeService.saveAccountGroupNew(accountId,collect);


        //app
        List<Integer> appGroupId = sysAccountMultilevel.getAppGroupId();
        String collect1 = appGroupId.stream().map(String::valueOf).collect(Collectors.joining(","));
        iAppAuthorizeService.saveAccountGroupNew(accountId,collect1);


        //大屏
//        List<Integer> screenGroupId = sysAccountMultilevel.getScreenGroupId();
//        String collect2 = screenGroupId.stream().map(String::valueOf).collect(Collectors.joining(","));
//        iScreenAuthorizeService.saveAccountGroupNew(accountId,collect2);

        return  new Result( 10000,"添加成功",true);
    }

    @Transactional
    @Override
    public void updateApp(SysAccountMultilevelDto sysAccountMultilevel) {
        //修改账号表
        SysAccountMultilevel sysAccountMultilevel1 = new SysAccountMultilevel();
        BeanUtil.copyProperties(sysAccountMultilevel,sysAccountMultilevel1);
        this.updateById(sysAccountMultilevel1);
        Integer accountId = sysAccountMultilevel.getId();

        //后台
        List<Integer> pcGroupId = sysAccountMultilevel.getPcGroupId();
        String collect = pcGroupId.stream().map(String::valueOf).collect(Collectors.joining(","));
        iAuthorizeService.saveAccountGroupNew(accountId,collect);



        //app
        List<Integer> appGroupId = sysAccountMultilevel.getAppGroupId();
        String collect1 = appGroupId.stream().map(String::valueOf).collect(Collectors.joining(","));
        iAppAuthorizeService.saveAccountGroupNew(accountId,collect1);


        //大屏
        List<Integer> screenGroupId = sysAccountMultilevel.getScreenGroupId();
        String collect2 = screenGroupId.stream().map(String::valueOf).collect(Collectors.joining(","));
        iScreenAuthorizeService.saveAccountGroupNew(accountId,collect2);
    }

}
