package jnpf.personnels.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import jnpf.model.personnels.dto.staff.field.FtbPersonnelsRegistrationFormTypeDto;
import jnpf.model.personnels.po.FtbPersonnelsRegistrationFormField;
import jnpf.model.personnels.po.FtbPersonnelsRegistrationFormType;
import jnpf.model.personnels.req.field.QueryRegistrationFormTypeListReq;
import jnpf.model.personnels.req.field.SaveRegistrationFormTypeReq;
import jnpf.personnels.mapper.FtbPersonnelsRegistrationFormTypeMapper;
import jnpf.personnels.service.FtbPersonnelsRegistrationFormFieldService;
import jnpf.personnels.service.FtbPersonnelsRegistrationFormTypeService;
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;

@Service
public class FtbPersonnelsRegistrationFormTypeServiceImpl extends ServiceImpl<FtbPersonnelsRegistrationFormTypeMapper, FtbPersonnelsRegistrationFormType> implements FtbPersonnelsRegistrationFormTypeService {

    @Autowired
    private FtbPersonnelsRegistrationFormFieldService registrationFormFieldService;

    @Override
    public PageInfo<FtbPersonnelsRegistrationFormTypeDto> getPageList(QueryRegistrationFormTypeListReq req) {

        Page<FtbPersonnelsRegistrationFormType> queryPage = baseMapper.selectPage(new Page(req.getCurrentPage(), req.getPageSize()), new LambdaQueryWrapper<FtbPersonnelsRegistrationFormType>().eq(FtbPersonnelsRegistrationFormType::getEnabledMark, 0).orderByAsc(FtbPersonnelsRegistrationFormType::getSorts));
        List<FtbPersonnelsRegistrationFormType> records = queryPage.getRecords();
        //转换查询对象
        List<FtbPersonnelsRegistrationFormTypeDto> list = new ArrayList<>();
        records.forEach(entity -> {
            FtbPersonnelsRegistrationFormTypeDto vo = BeanUtil.copyProperties(entity, FtbPersonnelsRegistrationFormTypeDto.class);
            //查询所有字段数量
            vo.setAllFieldNum(registrationFormFieldService.queryAllFieldNumForType(vo.getId()));
            //查询启用字段数量
            vo.setFieldNum(registrationFormFieldService.queryEnableFieldNumForType(vo.getId()));
            list.add(vo);
        });
        //构建分页返回数据
        PageInfo<FtbPersonnelsRegistrationFormTypeDto> pageInfo = new PageInfo<>();
        pageInfo.setList(list);
        pageInfo.setPageSize((int) queryPage.getSize());
        pageInfo.setPageNum((int) queryPage.getCurrent());
        pageInfo.setTotal((int) queryPage.getTotal());
        return pageInfo;
    }

    @Override
    public FtbPersonnelsRegistrationFormTypeDto getInfo(String id) {
        FtbPersonnelsRegistrationFormType entity = baseMapper.selectById(id);
        if (null == entity) {
            throw new RuntimeException("数据不存在");
        }
        if (entity.getEnabledMark() == 1) {
            throw new RuntimeException("数据已经删除");
        }
        return BeanUtil.copyProperties(entity, FtbPersonnelsRegistrationFormTypeDto.class);
    }

    @Override
    public String insertData(SaveRegistrationFormTypeReq req) {
        if(req.getSorts()==null){
            req.setSorts(0L);
        }
        //检测名称是否重复
        QueryWrapper<FtbPersonnelsRegistrationFormType> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(FtbPersonnelsRegistrationFormType::getName, req.getName()).eq(FtbPersonnelsRegistrationFormType::getEnabledMark, 0);
        Long count = baseMapper.selectCount(wrapper);
        if (null != count && count > 0) {
            throw new RuntimeException("类别名称已经存在");
        }
        //检测排序重复
        QueryWrapper<FtbPersonnelsRegistrationFormType> sortWrapper = new QueryWrapper<>();
        sortWrapper.lambda().eq(FtbPersonnelsRegistrationFormType::getSorts, req.getSorts()).eq(FtbPersonnelsRegistrationFormType::getEnabledMark, 0);
        Long sortCount = baseMapper.selectCount(sortWrapper);
        if (null != sortCount && sortCount > 0) {
            throw new RuntimeException("排序已经存在");
        }
        //添加
        FtbPersonnelsRegistrationFormType entity = BeanUtil.copyProperties(req, FtbPersonnelsRegistrationFormType.class);
        entity.setStatus(0);//0、启用  1、禁用
        entity.setSystemType(1);//0、系统类型 1、自定义类型
        baseMapper.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateData(SaveRegistrationFormTypeReq req) {
        //检测重复
        QueryWrapper<FtbPersonnelsRegistrationFormType> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(FtbPersonnelsRegistrationFormType::getName, req.getName()).ne(FtbPersonnelsRegistrationFormType::getId, req.getId()).eq(FtbPersonnelsRegistrationFormType::getEnabledMark, 0);
        Long count = baseMapper.selectCount(wrapper);
        if (null != count && count > 0) {
            throw new RuntimeException("类别名称已经存在");
        }
        //检测排序重复
        QueryWrapper<FtbPersonnelsRegistrationFormType> sortWrapper = new QueryWrapper<>();
        sortWrapper.lambda().eq(FtbPersonnelsRegistrationFormType::getSorts, req.getSorts()).ne(FtbPersonnelsRegistrationFormType::getId, req.getId()).eq(FtbPersonnelsRegistrationFormType::getEnabledMark, 0);
        Long sortCount = baseMapper.selectCount(sortWrapper);
        if (null != sortCount && sortCount > 0) {
            throw new RuntimeException("排序已经存在");
        }
        LambdaUpdateWrapper<FtbPersonnelsRegistrationFormType> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(FtbPersonnelsRegistrationFormType::getId, req.getId());
        updateWrapper.set(FtbPersonnelsRegistrationFormType::getSorts, req.getSorts());
        updateWrapper.set(FtbPersonnelsRegistrationFormType::getName, req.getName());
        baseMapper.update(new FtbPersonnelsRegistrationFormType(), updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteData(String id) {
        //检测是否是系统类别，系统类别不能删除
        FtbPersonnelsRegistrationFormTypeDto dto = getInfo(id);
        if (dto.getSystemType().equals(0)) {
            throw new RuntimeException("系统类别不能删除");
        }
        //删除类别
        FtbPersonnelsRegistrationFormType entity = new FtbPersonnelsRegistrationFormType();
        entity.setEnabledMark(1);
        entity.setId(id);
        baseMapper.updateById(entity);

        //删除字段
        UpdateWrapper<FtbPersonnelsRegistrationFormField> wrapper = new UpdateWrapper<>();
        wrapper.lambda().set(FtbPersonnelsRegistrationFormField::getEnabledMark, 1)
                .eq(FtbPersonnelsRegistrationFormField::getEnabledMark, 0)
                .eq(FtbPersonnelsRegistrationFormField::getFormTypeId, id);
        registrationFormFieldService.update(wrapper);
    }

    @Override
    public void switchStatus(String id, Integer status) {
        //检测是否是系统类别
        FtbPersonnelsRegistrationFormTypeDto dto = getInfo(id);
        if (dto.getStatus().equals(status)) {
            return;
        }

        //修改系统状态 启用和禁用
        FtbPersonnelsRegistrationFormType entity = new FtbPersonnelsRegistrationFormType();
        entity.setStatus(status);
        entity.setId(id);
        baseMapper.updateById(entity);
    }

    /**
     * 修改排序号
     *
     * @param id    主键
     * @param sorts 序号
     */
    @Override
    public void updateSorts(String id, Long sorts) {
        getInfo(id);
        FtbPersonnelsRegistrationFormType entity = new FtbPersonnelsRegistrationFormType();
        entity.setSorts(sorts);
        entity.setId(id);
        baseMapper.selectById(entity);
    }

    /**
     * 查询所有类别
     *
     * @return
     */
    @Override
    public List<FtbPersonnelsRegistrationFormTypeDto> listAll(Integer status) {
        // 排除合同类型，人事v1.2
        QueryWrapper<FtbPersonnelsRegistrationFormType> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(FtbPersonnelsRegistrationFormType::getEnabledMark, 0)
                .eq(status != null, FtbPersonnelsRegistrationFormType::getStatus, status)
                .ne(FtbPersonnelsRegistrationFormType::getId, "5")
                .orderByAsc(FtbPersonnelsRegistrationFormType::getSorts);
        List<FtbPersonnelsRegistrationFormType> formTypeList = baseMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(formTypeList)) {
            return BeanUtil.copyToList(formTypeList, FtbPersonnelsRegistrationFormTypeDto.class);
        }
        return CollectionUtil.newArrayList();
    }
}
