package com.casic.missiles.service.Impl.meter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.meter.OrganizeListRequest;
import com.casic.missiles.dto.meter.ParentDeptRequest;
import com.casic.missiles.dto.meter.ParentDeptResponse;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.PrefixCodeEnum;
import com.casic.missiles.enums.meter.MeterDeptTypeEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.meter.MeterOrganizeMapper;
import com.casic.missiles.model.meter.MeterOrganize;
import com.casic.missiles.modular.system.model.Dept;
import com.casic.missiles.modular.system.service.IDeptService;
import com.casic.missiles.service.meter.IMeterOrganizeService;
import com.casic.missiles.utils.DictCodeUtils;
import com.casic.missiles.utils.NumberGeneratorUtil;
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 org.springframework.util.CollectionUtils;

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

/**
 * <p>
 * 计量管理-计量组织-部门管理/科室管理/工程组管理 服务实现类
 * </p>
 *
 * @author wangpeng
 * @since 2022-11-27
 */
@Service
public class MeterOrganizeServiceImpl extends ServiceImpl<MeterOrganizeMapper, MeterOrganize> implements IMeterOrganizeService {
    @Autowired
    private MeterOrganizeMapper organizeMapper;
    @Autowired
    private IDeptService deptService;

    @Override
    public Page<MeterOrganize> listPage(Page<MeterOrganize> page, OrganizeListRequest request) throws Exception {
        DictCodeUtils.validDictCode(request);
        QueryWrapper<MeterOrganize> wrapper = getWrapper(request);
        Page<MeterOrganize> organizePage = organizeMapper.selectPage(page, wrapper);
        if(CollectionUtils.isEmpty(organizePage.getRecords())){
            return new Page<>();
        }
        for (MeterOrganize record : organizePage.getRecords()) {
            DictCodeUtils.convertDictCodeToName(record);
            if(Objects.nonNull(record.getPDeptId())){
                //获取父部门名称及负责人
                QueryWrapper<MeterOrganize> queryWrapper = new QueryWrapper();
                queryWrapper.eq("dept_id", record.getPDeptId());
                MeterOrganize meterOrganize = organizeMapper.selectOne(queryWrapper);
                if(Objects.nonNull(meterOrganize)){
                    record.setPDeptName(meterOrganize.getOrganizeName());
                    record.setPDeptDirector(meterOrganize.getDirector());
                }
            }
        }
        return organizePage;
    }

    @Override
    public List<MeterOrganize> list(OrganizeListRequest request) throws Exception {
        QueryWrapper<MeterOrganize> wrapper = getWrapper(request);
        List<MeterOrganize> meterOrganizes = organizeMapper.selectList(wrapper);
        if(CollectionUtils.isEmpty(meterOrganizes)){
            return new ArrayList<>();
        }
        for (MeterOrganize record : meterOrganizes) {
            DictCodeUtils.convertDictCodeToName(record);
            if(Objects.nonNull(record.getPDeptId())){
                //获取父部门名称及负责人
                QueryWrapper<MeterOrganize> queryWrapper = new QueryWrapper();
                queryWrapper.eq("dept_id", record.getPDeptId());
                MeterOrganize meterOrganize = organizeMapper.selectOne(queryWrapper);
                record.setPDeptName(meterOrganize.getOrganizeName());
                record.setPDeptDirector(meterOrganize.getDirector());
            }
        }
        return meterOrganizes;
    }

    @Override
    public ParentDeptResponse deptInfo(ParentDeptRequest request) {
        Long deptId = request.getDeptId();
        QueryWrapper<MeterOrganize> wrapper = new QueryWrapper<>();
        wrapper.eq("dept_id", deptId);
        MeterOrganize meterOrganize = organizeMapper.selectOne(wrapper);

        QueryWrapper<MeterOrganize> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("dept_id", meterOrganize.getPDeptId());
        MeterOrganize meterPOrganize = organizeMapper.selectOne(wrapper1);

        ParentDeptResponse response = new ParentDeptResponse();
        response.setDeptId(deptId);
        response.setDeptName(meterOrganize.getOrganizeName());
        response.setOrganizeNo(meterOrganize.getOrganizeNo());
        response.setPDeptId(meterOrganize.getPDeptId());
        if(!Objects.isNull(meterPOrganize)){
            response.setPDeptName(meterPOrganize.getOrganizeName());
            response.setPOrganizeNo(meterPOrganize.getOrganizeNo());
        }
        return response;
    }

    @Override
    @Transactional
    public int addOrganize(Dept dept) {
        //生成组织编号
        Long maxNo = organizeMapper.selectMaxOrganizeNo();
        String organizeNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.ORGANIZE_PREFIX, maxNo);
        MeterOrganize meterOrganize = new MeterOrganize();
        meterOrganize.setDeptId(dept.getId());
        meterOrganize.setPDeptId(dept.getPid());
        meterOrganize.setOrganizeNo(organizeNo);
        meterOrganize.setOrganizeName(dept.getSimpleName());
        meterOrganize.setOrganizeType(dept.getDeptType());
        return organizeMapper.insert(meterOrganize);
    }

    @Override
    @Transactional
    public int updateByDept(Dept dept) {
        List<String> collect = Arrays.stream(MeterDeptTypeEnum.values()).map(MeterDeptTypeEnum::getCode).collect(Collectors.toList());
        if(!collect.contains(dept.getDeptType())){
            QueryWrapper<MeterOrganize> wrapper = new QueryWrapper<>();
            wrapper.eq("dept_id", dept.getId());
            //非计量组织
            if(Objects.isNull(organizeMapper.selectOne(wrapper))){
                return 1;
            }
            //组织类型变更为非计量组织中的组织，移除该计量组织
            QueryWrapper<MeterOrganize> delWrapper = new QueryWrapper<>();
            delWrapper.eq("dept_id", dept.getId());
            return organizeMapper.delete(wrapper);
        }
        MeterOrganize meterOrganize = new MeterOrganize();
        //父组织id
        meterOrganize.setPDeptId(dept.getPid());
        meterOrganize.setOrganizeName(dept.getSimpleName());
        meterOrganize.setOrganizeType(dept.getDeptType());
        UpdateWrapper<MeterOrganize> wrapper = new UpdateWrapper<>();
        //已删除数据mp该update方法无法更新
        wrapper.eq("dept_id", dept.getId());
        return organizeMapper.update(meterOrganize, wrapper);
    }

    @Override
    @Transactional
    public int deleteByDeptId(Long id) {
        QueryWrapper<MeterOrganize> wrapper = new QueryWrapper<>();
        wrapper.eq("dept_id", id);
        return organizeMapper.delete(wrapper);
    }

    @Override
    @Transactional
    public ReturnDTO updateOrganize(MeterOrganize meterOrganize) {
        //更新组织名称同步更新sys_dept
        Dept dept = new Dept();
        dept.setId(meterOrganize.getDeptId());
        dept.setSimpleName(meterOrganize.getOrganizeName());
        boolean success = deptService.updateById(dept);
        if(organizeMapper.updateById(meterOrganize) > 0 && success){
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    private QueryWrapper<MeterOrganize> getWrapper(OrganizeListRequest request) {
        QueryWrapper<MeterOrganize> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(request.getOrganizeNo()), "organize_no", request.getOrganizeNo());
        wrapper.like(StringUtils.isNotBlank(request.getOrganizeName()), "organize_name", request.getOrganizeName());
        wrapper.like(StringUtils.isNotBlank(request.getDirector()), "director", request.getDirector());
        wrapper.like(StringUtils.isNotBlank(request.getMeterMajor()), "meter_major", request.getMeterMajor());
        wrapper.like(StringUtils.isNotBlank(request.getOrganizeType()), "organize_type", request.getOrganizeType());
        wrapper.eq(!Objects.isNull(request.getPDeptId()), "p_dept_id", request.getPDeptId());
        wrapper.eq(!Objects.isNull(request.getIsLab()), "is_lab", request.getIsLab());
        wrapper.apply(StringUtils.isNotBlank(request.getCreateStartTime()),//apply方法传入参数名不能为空
                "{0} <= DATE_FORMAT(create_time,'%Y-%m-%d')", request.getCreateStartTime().split(" ")[0]);
        wrapper.apply(StringUtils.isNotBlank(request.getCreateEndTime()),
                "{0} >= DATE_FORMAT(create_time,'%Y-%m-%d')", request.getCreateEndTime().split(" ")[0]);
        wrapper.eq("is_del", 0);
        wrapper.orderByDesc("create_time");
        return wrapper;
    }
}
