package com.yeejoin.amos.boot.module.ugp.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.ugp.api.Enum.WeldCodeEnum;
import com.yeejoin.amos.boot.module.ugp.api.Enum.WeldMethodEnum;
import com.yeejoin.amos.boot.module.ugp.api.dto.WeldDto;
import com.yeejoin.amos.boot.module.ugp.api.entity.Project;
import com.yeejoin.amos.boot.module.ugp.api.entity.SuperviseRule;
import com.yeejoin.amos.boot.module.ugp.api.entity.Weld;
import com.yeejoin.amos.boot.module.ugp.api.mapper.ProjectMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.SuperviseRuleMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.WeldMapper;
import com.yeejoin.amos.boot.module.ugp.api.service.IWeldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 焊口信息表服务实现类
 *
 * @author system_generator
 * @date 2022-09-22
 */
@Service
public
class WeldServiceImpl extends BaseService<WeldDto, Weld, WeldMapper> implements IWeldService {

    @Autowired
    WeldMapper weldMapper;
    @Autowired
    ProjectMapper projectMapper;
    @Autowired
    OrgServiceImpl orgService;
    @Autowired
    SuperviseRuleMapper superviseRuleMapper;


//    Logger logger = LoggerFactory.getLogger(WeldServiceImpl.class);

    private final String 安装单位="INSTALL";

    private final String 监察单位="SUPERVISION";
    /**
     * 分页查询(安装单位管理员只能查看本单位项目所有焊口信息。
     *         监检机构管理员可查看所有项目焊口信息。)
     */
    public Page<WeldDto> queryForWeldPage(int current, int size) {
        Page<WeldDto> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        Page<WeldDto> weldDtoPage = this.queryForPage(page, null, false);

        for (WeldDto weldDto : weldDtoPage.getRecords()) {
            QueryWrapper<Project> wrapper = new QueryWrapper<>();
            wrapper.eq("sequence_nbr", weldDto.getProjectId());
            Project project = projectMapper.selectOne(wrapper);
            weldDto.setName(project.getName());

            QueryWrapper<Project> wrapperUnit = new QueryWrapper<>();
            wrapperUnit.eq("installation_unit_id", weldDto.getInstallCompany());

            List<Project> projects = projectMapper.selectList(wrapperUnit);
            for (Project project1 : projects) {
                weldDto.setInstallationUnit(project1.getInstallationUnit());
                weldDto.setCodingStatus(WeldCodeEnum.map.get(weldDto.getCodingStatus()));
                weldDto.setCodingMethod(WeldMethodEnum.map.get(weldDto.getCodingMethod()));
            }

        }

        //获取登录人信息
        OrgUsr orgUsr = orgService.getOrgUsr();
        //获取登录人企业下的所有焊口
        if (orgUsr.getOrgExpandAttr1() == 安装单位) {

            List<WeldDto> L = weldDtoPage.getRecords().stream().filter(b -> b.getInstallCompany().equals(orgUsr.getParentId())).collect(Collectors.toList());
            weldDtoPage.setRecords(L);
        }

        //根据 所在地 筛选焊口
        if (orgUsr.getOrgExpandAttr1() == 监察单位) {

            LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<SuperviseRule> eq = wrapper.eq(SuperviseRule::getSuperviseDeptId, orgUsr.getParentId());
            List<SuperviseRule> superviseRules = superviseRuleMapper.selectList(eq);
            for (SuperviseRule i : superviseRules) {

                List<WeldDto> L = weldDtoPage.getRecords().stream().filter(b -> b.getRegion().equals(i.getAdminRegion())).collect(Collectors.toList());
                weldDtoPage.setRecords(L);
            }
        }
        return weldDtoPage;
    }

    /**
     * 更新焊口编码任务状态
     */
    public String updateTask(Weld weld) {
        LambdaQueryWrapper<Weld> wrapper = new LambdaQueryWrapper<>();
        //根据焊口编码修改任务状态
        wrapper.eq(Weld::getCode, weld.getCode());
        int update = weldMapper.update(weld, wrapper);

        return "成功更新" + update + "条";

    }



    /**
     * 列表查询 示例
     */
    public List<WeldDto> queryForWeldList() {
        return this.queryForList("", false);
    }

    /**
     * 生成焊口编号保存并查询
     */
    // 静态变量存储最大值
    private static final AtomicInteger atomicNum = new AtomicInteger();
    // 初始化编号
    private final int INIT_CODE_NUM = 0;
    private final String FIRST_CHARACTER = "-HK";

    public synchronized List<Weld> getCode(Long sequenceNbr, int number) {

        List<Weld> welds = new ArrayList<>();
        Project project = projectMapper.selectById(sequenceNbr);
        QueryWrapper<Weld> wrapper = new QueryWrapper<>();
        //根据seq查询条件判断是否已经存在该项目的该焊口编码
        wrapper.eq("project_id", sequenceNbr).orderByDesc("code").last("limit 1");
        Weld weld1 = weldMapper.selectOne(wrapper);

        if (weld1 != null) {
            //存在时取后四位
            String substring = weld1.getCode().substring(weld1.getCode().length() - 4, weld1.getCode().length());
            atomicNum.set(Integer.parseInt(substring));
        } else {
            //不存在时将atomicNum初始化
            atomicNum.set(INIT_CODE_NUM);
        }
        for (int i = 0; i < number; i++) {
            Weld weld = new Weld();
            //生成四位数
            String i1 = String.format("%04d", atomicNum.incrementAndGet());
            //生成编码
            String code = (project.getCode()) + FIRST_CHARACTER + i1;
            weld.setRegion(project.getAddress());
            weld.setProjectId(Long.valueOf(project.getSequenceNbr()));
            weld.setInstallCompany(project.getInstallationUnitId());
            weld.setCode(code);
            weld.setRegion(project.getAddress());
            weld.setCodingMethod(WeldMethodEnum.自动赋码.getState());
            weld.setCodingStatus(WeldCodeEnum.已赋值.getState());
            weld.setCodingDate(new Date());
            welds.add(weld);
        }

        saveBatch(welds);
        return welds;
    }

    /**
     * 通过项目多个id获取数据
     * @param projectId
     * @return
     */
    public List<WeldDto> getProjectId(Long projectId){
        return weldMapper.select(projectId);
    }
}