package com.testor.module.fives.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.rule.service.SysRuleService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.common.constant.DefaultRule;
import com.testor.common.constant.StatusEnum;
import com.testor.module.fives.dao.TFivesToolUseDao;
import com.testor.module.fives.model.domain.TFivesToolUse;
import com.testor.module.fives.model.dto.TFivesToolUseParam;
import com.testor.module.fives.model.vo.TFivesToolUseListVO;
import com.testor.module.fives.service.TFivesToolUseService;
import com.testor.module.sys.model.domian.NewSysOrg;
import com.testor.module.sys.service.NewSysOrgService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.exceptions.ApiException;
import com.tongtech.tfw.backend.common.models.response.ResponseInfo;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 5s工具运用Service业务层处理
 *
 * @author testor-framework
 * @date 2022-07-21 15:56:55
 */
@Service
public class TFivesToolUseServiceImpl extends SuperServiceImpl<TFivesToolUseDao, TFivesToolUse> implements TFivesToolUseService {
    @Autowired(required = false)
    private TFivesToolUseDao tFivesToolUseDao;

    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private SysRuleService sysRuleService;

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private NewSysOrgService newSysOrgService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public TFivesToolUse addEntity(TFivesToolUse tFivesToolUse) {

        if (ObjectHelper.isEmpty(tFivesToolUse)) {
            throw new ApiException(new ResponseInfo(BaseStatusEnum.UN_DATA.code(), "5s工具主项为空"));
        }

        UserInfo curUser = ContextUtils.getLoginUser();
        if (StrUtil.isBlank(curUser.getOrgId())) {
            throw new ApiException(new ResponseInfo(BaseStatusEnum.UN_DATA.code(), "用户信息错误"));
        }

        QueryWrapper<TFivesToolUse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("serial_number", tFivesToolUse.getSerialNumber());
        queryWrapper.eq("status", StatusEnum.USE.getCode());
        TFivesToolUse tFivesToolUseOne = tFivesToolUseDao.selectOne(queryWrapper);
        if (ObjectHelper.isNotEmpty(tFivesToolUseOne)) {
            throw new ApiException(new ResponseInfo(BaseStatusEnum.UN_DATA.code(), "已存在相同编号数据，无法添加"));
        }
        String orgId = curUser.getOrgId();
        QueryWrapper<SysOrg> sysOrgQueryWrapper = new QueryWrapper<>();
        sysOrgQueryWrapper.eq("org_id", orgId);
        SysOrg sysOrg = sysOrgService.getOne(sysOrgQueryWrapper);
        if (ObjectHelper.isEmpty(sysOrg)) {
            throw new ApiException(new ResponseInfo(BaseStatusEnum.UN_DATA.code(), "当前用户所机构不存在"));
        }

        String treeLevel = newSysOrgService.getOrgNatureById(orgId);

        if ("1".equals(treeLevel)) {
            // 总部不会添加（跟产品已确认）
            throw new ApiException(new ResponseInfo(BaseStatusEnum.UN_DATA.code(), "当前用户层次级别异常"));
        } else if ("2".equals(treeLevel)) {
            // 大区
            tFivesToolUse.setAreaOrgId(orgId);
            tFivesToolUse.setGrainOrgId(orgId);
        } else if ("3".equals(treeLevel)) {
            // 经营部
            String parentId = sysOrg.getParentId();
            tFivesToolUse.setGrainOrgId(orgId);
            tFivesToolUse.setAreaOrgId(parentId);
        }else {
            // 基层企业
            String parentId = sysOrg.getParentId();
            tFivesToolUse.setGrainOrgId(orgId);
            tFivesToolUse.setAreaOrgId(parentId);
        }

        String id = IdHelper.getId32bit();
        tFivesToolUse.setId(id);
        boolean result = save(tFivesToolUse);
        if (result) {
            return tFivesToolUse;
        }
        return null;
    }

    @Override
    public IPage<TFivesToolUseListVO> selectToolUserLists(TFivesToolUseParam param) {
        Long page = StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit = StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TFivesToolUseListVO> resultPage = new Page<>(page, limit);
        // 获取工具运用的列表数据
        List<String> companyIds = param.getCompanyIds();
        if (CollectionUtils.isEmpty(companyIds)) {
            if (StringHelper.isNotEmpty(param.getToolList())) {
                companyIds =  getToolList();
            }else {
                // 获取权限id orgId 为1的为中粮推荐亮点数据 获取亮点展示的数据
                companyIds =  getAuthorityId();
            }
        }




        param.setCompanyIds(companyIds);
        if (StringHelper.isNotEmpty(param.getStartDate()) && StringHelper.isNotEmpty(param.getEndDate())) {
            param.setStartDate(param.getStartDate()+" 00:00:00");
            param.setEndDate(param.getEndDate()+" 23:59:59");
        }
        IPage<TFivesToolUseListVO> tFivesToolUseListVOIPage = tFivesToolUseDao.selectToolUserLists(resultPage,param);
        List<TFivesToolUseListVO> listVOIPageRecords = tFivesToolUseListVOIPage.getRecords();

        Map<String,String> map=new HashMap<>();

        for (TFivesToolUseListVO vo : listVOIPageRecords) {
            String createById = vo.getCreateBy();
            SysUser sysUser = sysUserService.getById(createById);
            if(ObjectHelper.isNotEmpty(sysUser)){
                vo.setCreateByName(sysUser.getUserName());
            }
            String orgId = vo.getOrgId();
            if (StringUtils.isNotBlank(orgId)) {
                String orgPathName = newSysOrgService.findOrgPathNameByOrgId(orgId);
                vo.setGrainOrgId(orgPathName);
            }

        }
        return tFivesToolUseListVOIPage;
    }

    /**
     * 获取工具运用列表权限id
     * @return
     */
    private List<String> getToolList() {
        QueryWrapper<SysOrg> queryWrapper = new QueryWrapper<>();
        String rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_SUB.name());
        // 获取本下级机构
        List<SysOrg> list = sysOrgService.list(queryWrapper.apply(rule));
        List<String> companyIds = new ArrayList<>();
        list.stream().forEach(item->{
            companyIds.add(item.getOrgId());
        });
        return companyIds;
    }

    /**
     * 获取列表权限id
     * @return
     */
    private List<String> getAuthorityId() {
        QueryWrapper<SysOrg> queryWrapper = new QueryWrapper<>();
        // 获取登录用户机构id
        String orgId = ContextUtils.getLoginUser().getOrgId();
        // 当前登录机构详细信息
        SysOrg sysOrg = sysOrgService.getById(orgId);
        String parentId = "";
        if (sysOrg.getTreeLevel().compareTo(BigDecimal.valueOf(3)) == 0) {
            // 获取当前登录用户的父id
            parentId = sysOrg.getParentId();
        }
        String rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_SUB.name());
        // 获取本下级机构
        List<SysOrg> list = sysOrgService.list(queryWrapper.apply(rule).or().eq(SysOrg.PARENT_ID,parentId).eq(SysOrg.IS_DEPT,"0"));
        List<String> companyIds = new ArrayList<>();
        list.stream().forEach(item->{
            companyIds.add(item.getOrgId());
        });
        companyIds.add("1");
        return companyIds;
    }

    public String orgName(Map<String,String> map,String orgId){

        String orgName = map.get(orgId);
        if(StrUtil.isEmpty(orgName)){
            QueryWrapper<SysOrg> sysOrgQueryWrapper = new QueryWrapper<>();
            sysOrgQueryWrapper.eq("org_id", orgId);
            SysOrg sysOrg = sysOrgService.getOne(sysOrgQueryWrapper);

            orgName = sysOrg.getOrgName();

            map.put(orgId,orgName);
        }

        return orgName;
    }
}
