package cn.iocoder.yudao.module.crm.service.crmflow;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.crm.controller.admin.crmflow.vo.CrmFlowPageReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.crmflow.vo.CrmFlowSaveReqVO;
import cn.iocoder.yudao.module.crm.dal.dataobject.crmflow.CrmFlowDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.crmflow.CrmFlowStepDO;
import cn.iocoder.yudao.module.crm.dal.mysql.crmflow.CrmFlowMapper;
import cn.iocoder.yudao.module.crm.dal.mysql.crmflow.CrmFlowStepMapper;
import cn.iocoder.yudao.module.hrm.enums.FlowStepEnum;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserApiDTO;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserApiVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.hrm.enums.ErrorCodeConstants.FLOW_NOT_EXISTS;

/**
 * 审批流程 Service 实现类
 *
 * @author yshop
 */
@Service
@Validated
public class CrmFlowServiceImpl implements CrmFlowService {

    @Resource
    private CrmFlowMapper flowMapper;
    @Resource
    private CrmFlowStepMapper flowStepMapper;
    @Resource
    private AdminUserApi adminUserApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createFlow(CrmFlowSaveReqVO createReqVO) {
        // 插入
        CrmFlowDO flow = BeanUtils.toBean(createReqVO, CrmFlowDO.class);
        flowMapper.insert(flow);

        // 插入子表
        createFlowStepList(flow.getId(), createReqVO.getFlowSteps());
        // 返回
        return flow.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFlow(CrmFlowSaveReqVO updateReqVO) {
        // 校验存在
        validateFlowExists(updateReqVO.getId());
        // 更新
        CrmFlowDO updateObj = BeanUtils.toBean(updateReqVO, CrmFlowDO.class);
        flowMapper.updateById(updateObj);

        // 更新子表
        updateFlowStepList(updateReqVO.getId(), updateReqVO.getFlowSteps());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFlow(Long id) {
        // 校验存在
        validateFlowExists(id);
        // 删除
        flowMapper.deleteById(id);

        // 删除子表
        deleteFlowStepByFlowId(id);
    }

    private void validateFlowExists(Long id) {
        if (flowMapper.selectById(id) == null) {
            throw exception(FLOW_NOT_EXISTS);
        }
    }

    @Override
    public CrmFlowDO getFlow(Long id) {
        return flowMapper.selectById(id);
    }

    @Override
    public PageResult<CrmFlowDO> getFlowPage(CrmFlowPageReqVO pageReqVO) {
        return flowMapper.selectPage(pageReqVO);
    }

    // ==================== 子表（审批步骤） ====================

    @Override
    public List<CrmFlowStepDO> getFlowStepListByFlowId(Long flowId) {
        return flowStepMapper.selectListByFlowId(flowId);
    }

    @Override
    public List<Long> getFlowUserIds(String flowType) {
        List<Long> list = new ArrayList<>();
        CrmFlowDO crmFlowDO = flowMapper.selectOne(new LambdaQueryWrapper<CrmFlowDO>()
                .eq(CrmFlowDO::getTypes, flowType)
                .orderByDesc(CrmFlowDO::getId)
                .last("limit 1"));
        if (crmFlowDO == null) {
            return list;
        }
        CrmFlowStepDO crmFlowStepDO = flowStepMapper.selectOne(new LambdaQueryWrapper<CrmFlowStepDO>()
                .eq(CrmFlowStepDO::getFlowId, crmFlowDO.getId())
                .orderByAsc(CrmFlowStepDO::getId)
                .last("limit 1"));
        if (FlowStepEnum.TYPE_2.getValue().equals(crmFlowStepDO.getType())) {
            list.add(crmFlowStepDO.getAdminIds());
        } else if (FlowStepEnum.TYPE_3.getValue().equals(crmFlowStepDO.getType())) {
            List<AdminUserApiVO> adminUserDOS = adminUserApi.getUserList(new AdminUserApiDTO().setDeptId(crmFlowStepDO.getAdminIds()).setNextDept(1)).getCheckedData();
            list = adminUserDOS.stream().map(AdminUserApiVO::getId).collect(Collectors.toList());
        }

        return list;
    }

    private void createFlowStepList(Long flowId, List<CrmFlowStepDO> list) {
        int i = 1;
        for (CrmFlowStepDO o : list) {
            o.setFlowId(flowId);
            o.setRelation(i);
            i++;
        }
        flowStepMapper.insertBatch(list);
    }

    private void updateFlowStepList(Long flowId, List<CrmFlowStepDO> list) {
        deleteFlowStepByFlowId(flowId);
        list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createFlowStepList(flowId, list);
    }

    private void deleteFlowStepByFlowId(Long flowId) {
        flowStepMapper.deleteByFlowId(flowId);
    }

}
