package com.shkj.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.shkj.common.core.domain.Result;
import com.shkj.common.core.domain.entity.BaseBranch;
import com.shkj.common.core.domain.entity.SysDept;
import com.shkj.common.core.domain.entity.SysUser;
import com.shkj.common.core.page.BaseBranchResultVo;
import com.shkj.common.core.page.BaseBranchVo;
import com.shkj.common.enums.IsDelEnum;
import com.shkj.common.enums.IsUseEnum;
import com.shkj.common.exception.ServiceException;
import com.shkj.common.utils.SecurityUtils;
import com.shkj.common.utils.StringUtils;
import com.shkj.system.mapper.BaseBranchMapper;
import com.shkj.system.mapper.SysDeptMapper;
import com.shkj.system.service.IBaseBranchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 仓库信息Service业务层处理
 *
 * @author lch
 * @date 2022-03-26
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class BaseBranchServiceImpl extends ServiceImpl<BaseBranchMapper, BaseBranch> implements IBaseBranchService {


    @Autowired
    private SysDeptMapper deptMapper;


    /**
     * 分页列表
     *
     * @param baseBranch
     * @return
     */
    @Override
    public List<BaseBranchResultVo> queryList(BaseBranch baseBranch) {
        LambdaQueryWrapper<BaseBranch> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(baseBranch.getBranchCode()), BaseBranch::getBranchCode, baseBranch.getBranchCode());
        lqw.like(StrUtil.isNotBlank(baseBranch.getBranchName()), BaseBranch::getBranchName, baseBranch.getBranchName());

        lqw.eq(BaseBranch::getIsDel, IsDelEnum.NORMAL.getValue());
        lqw.eq(StrUtil.isNotBlank(baseBranch.getIsActivity()), BaseBranch::getIsActivity, baseBranch.getIsActivity());
        lqw.orderByDesc(BaseBranch::getCreateTime);
        List<BaseBranchResultVo> voList = entity2Vo(this.list(lqw));
        // 设置货主数量
        for (BaseBranchResultVo vo : voList) {
            vo.setConsignorNumber(this.baseMapper.getConsignorCount(vo.getId()));
        }
        return voList;

    }


    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<BaseBranchResultVo> entity2Vo(Collection<BaseBranch> collection) {
        List<BaseBranchResultVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, BaseBranchResultVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<BaseBranch> page = (Page<BaseBranch>) collection;
            Page<BaseBranchResultVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    /**
     * 全部
     *
     * @return
     */
    @Override
    public Result<List<BaseBranch>> selectBranchAll() {
        LambdaQueryWrapper<BaseBranch> lqw = Wrappers.lambdaQuery();
        lqw.eq(BaseBranch::getIsDel, IsDelEnum.NORMAL.getValue());
        lqw.eq(BaseBranch::getIsActivity, IsUseEnum.OPEN.getValue());
        lqw.orderByDesc(BaseBranch::getCreateTime);
        List<BaseBranch> voList = this.list(lqw);
        return Result.ok().data(voList);
    }

    /**
     * 删除
     *
     * @param BaseBranchIds
     * @return
     */
    @Override
    public Result deleteBranchByIds(Long[] BaseBranchIds) {
        for (Long baseBranchId : BaseBranchIds) {
            BaseBranch BaseBranch = getById(baseBranchId);
            if (baseMapper.countUserBranchById(baseBranchId) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", BaseBranch.getBranchName()));
            }
        }
        this.baseMapper.deleteBranchByIds(BaseBranchIds);
        return Result.ok();
    }

    /**
     * 更新
     *
     * @param baseBranch
     * @return
     */
    @Override
    public Result updateBranch(BaseBranch baseBranch) {
        if(StringUtils.isNumeric(baseBranch.getBranchCode())){
            return Result.err().msg("仓库code必须是字母加数字");
        }
        BaseBranch one = getById(baseBranch.getId());
        if (one == null) {
            return Result.err().msg("不存在");
        }
        BaseBranch branch = checkBaseBranch(baseBranch.getBranchCode());
        if (branch != null && !baseBranch.getId().equals(branch.getId())) {
            return Result.err().msg("仓库code已存在");
        }
        this.updateById(baseBranch);
        return Result.ok();
    }

    /**
     * 新增
     *
     * @param baseBranch
     * @return
     */
    @Override
    public Result insertBranch(BaseBranch baseBranch) {
        baseBranch.setId(null);
        if(StringUtils.isNumeric(baseBranch.getBranchCode())){
            return Result.err().msg("仓库code必须是字母加数字");
        }
        BaseBranch one = checkBaseBranch(baseBranch.getBranchCode());
        if (one != null) {
            return Result.err().msg("仓库code已存在");
        }
        baseBranch.setIsActivity("1");
        this.save(baseBranch);

        //添加系统必备配置
        toAddSystemConfig(baseBranch.getId());
        return Result.ok();
    }

    private void toAddSystemConfig(Long branchId) {
        try {
            baseMapper.copyDictTypeByBranch(branchId);
            baseMapper.copyDictDataByBranch(branchId);
            baseMapper.copyParameterByBranch(branchId);
            baseMapper.copySeqManaByBranch(branchId);
            SysDept dept = new SysDept();
            dept.setParentId(0L);
            dept.setAncestors("0");
            dept.setDeptName(UUID.randomUUID().toString());
            dept.setOrderNum("0");
            dept.setLeader(UUID.randomUUID().toString());
            dept.setStatus("0");
            dept.setDelFlag("0");
            dept.setBranchId(branchId);
            dept.setCreateTime(new Date());
            dept.setUpdateBy(SecurityUtils.getUsername());
            dept.setUpdateTime(new Date());
            deptMapper.insertDept(dept);
        } catch (Exception e) {
            log.error("branchId = {}  toAddSystemConfig = {}", branchId, e);
        }
    }

    /**
     * 根据code查询
     *
     * @param code
     * @return
     */
    public BaseBranch checkBaseBranch(String code) {
        LambdaQueryWrapper<BaseBranch> wrapper = new LambdaQueryWrapper<BaseBranch>().eq(BaseBranch::getIsDel, IsDelEnum.NORMAL.getValue())
                .eq(BaseBranch::getBranchCode, code);
        wrapper.last("limit 1");
        BaseBranch one = this.getOne(wrapper);
        return one;
    }

    /**
     * 根据id查询
     *
     * @param BaseBranchId
     * @return
     */
    @Override
    public Result<BaseBranch> selectBranchById(Long BaseBranchId) {
        return Result.ok().data(getById(BaseBranchId));
    }


    /**
     * 登陆时根据输入的用户名获取仓库选择框列表
     *
     * @param userName
     * @return
     */
    @Override
    public Result<BaseBranchVo> optionBranchByUserName(String userName) {
        BaseBranchVo vo = new BaseBranchVo();
        if (userName.equals("admin")) {
            vo.setStatus(1);
            return Result.ok().data(vo);
        }
        //当前用户账号对应的状态 1当前是超级管理员不需要选择仓库
        // 2没有仓库选择（账号错误或者系统用户） 3有仓库选择可以不选仓库 4有仓库选择并且必须选仓库
        List<SysUser> userList = this.baseMapper.getUserList(userName);
        if (CollectionUtils.isEmpty(userList)) {
            vo.setStatus(2);
            return Result.ok().data(vo);
        }

        List<BaseBranch> BaseBranch = this.baseMapper.optionBranchByUserName(userName);
        if (CollectionUtils.isEmpty(BaseBranch)) {
            vo.setStatus(2);
        } else {
            if (userList.stream().filter(x -> x.getIsSystemUser() != null && x.getIsSystemUser() == 1).findFirst().orElse(null) != null) {
                //是系统用户 可以不选
                vo.setStatus(3);
            } else {
                //不是系统用户 必须选择仓库
                vo.setStatus(4);
            }
            vo.setBaseBranchs(BaseBranch);
        }

        return Result.ok().data(vo);
    }

    @Override
    public Result<Boolean> switchStatus(Long id, String status) {
        BaseBranch branch = new BaseBranch();
        branch.setId(id).setIsActivity(status);
        return this.updateById(branch) ? Result.ok() : Result.err();
    }

    @Override
    public Result<BaseBranchVo> pdaOptionBranchByUserName(String userName) {
        BaseBranchVo vo = new BaseBranchVo();
        if (userName.equals("admin")) {
            return Result.err().msg("超级管理员不能登录设备");
        }
        //当前用户账号对应的状态 1当前是超级管理员不需要选择仓库
        // 2没有仓库选择（账号错误或者系统用户） 3有仓库选择可以不选仓库 4有仓库选择并且必须选仓库
        List<SysUser> userList = this.baseMapper.getUserList(userName);
        if (CollectionUtils.isEmpty(userList)) {
            return Result.err().msg("工号不存在");
        }
        if (userList.stream().filter(x -> Objects.equals(x.getIsDevice(), 1)).findFirst().orElse(null) == null) {
            return Result.err().msg("工号无设备权限");
        }

        List<BaseBranch> BaseBranch = this.baseMapper.optionBranchByUserName(userName);
        if (CollectionUtils.isEmpty(BaseBranch)) {
            vo.setStatus(2);
        } else {
            if (userList.stream().filter(x -> x.getIsSystemUser() != null && x.getIsSystemUser() == 1).findFirst().orElse(null) != null) {
                //是系统用户 可以不选
                vo.setStatus(3);
            } else {
                //不是系统用户 必须选择仓库
                vo.setStatus(4);
            }
            vo.setBaseBranchs(BaseBranch);
        }

        return Result.ok().data(vo);
    }
}
