package com.tuoheng.admin.service.workorder.distribution;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.entity.WorkOrder;
import com.tuoheng.admin.enums.DataPermissionEnum;
import com.tuoheng.admin.enums.WorkOrderStatusEnum;
import com.tuoheng.admin.enums.code.workorder.DistributionWorkorderCodeEnum;
import com.tuoheng.admin.enums.code.workorder.GenerateWorkorderCodeEnum;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.mapper.WorkOrderMapper;
import com.tuoheng.admin.request.workorder.DistributionWorkorderRequest;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 分配工单业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-12-08
 */
@Slf4j
@Service
public class DistributionWorkorderService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkOrderMapper workOrderMapper;

    /**
     * 生成工单
     *
     * @param request
     * @return
     */
    @Transactional
    public JsonResult distribution(DistributionWorkorderRequest request) {
        log.info("进入分配工单业务， request:{}", request);
        JsonResult result = this.check(request);
        if (0 != result.getCode()) {
            log.info("进入分配工单业务：校验失败：{}", result.getMsg());
            return result;
        }
        User user = CurrentUserUtil.getUserInfo();
        String userId = user.getId();
        result = this.distributionWorkOrder(userId, request);
        if (0 != result.getCode()) {
            log.info("进入分配工单：分配工单失败：{}", result.getMsg());
            return result;
        }
        return JsonResult.success();
    }

    /**
     * 检查参数
     *
     * @param request
     * @return
     */
    private JsonResult check(DistributionWorkorderRequest request) {
        // 判断工单id是否为空
        if (StringUtils.isEmpty(request.getWorkorderId())) {
            return JsonResult.error(DistributionWorkorderCodeEnum.ID_LIST_IS_NULL.getCode(), DistributionWorkorderCodeEnum.ID_LIST_IS_NULL.getMsg());
        }

        // 判断指派部门ID是否为空
        if (StringUtils.isEmpty(request.getAssignDeptId())) {
            return JsonResult.error(DistributionWorkorderCodeEnum.ASSIGN_DEPT_ID_IS_NULL.getCode(), DistributionWorkorderCodeEnum.ASSIGN_DEPT_ID_IS_NULL.getMsg());
        }

        // 判断指派负责人是否为空
        if (StringUtils.isEmpty(request.getAssignUserIds())) {
            return JsonResult.error(DistributionWorkorderCodeEnum.ASSIGN_USER_ID_IS_NULL.getCode(), DistributionWorkorderCodeEnum.ASSIGN_USER_ID_IS_NULL.getMsg());
        }

        WorkOrder workOrder = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrder>()
                                .eq(WorkOrder::getId, request.getWorkorderId())
                                .eq(WorkOrder::getMark, 1));
        if (null == workOrder) {
            return JsonResult.error(DistributionWorkorderCodeEnum.WORK_ORDER_IS_NOT_EXIST.getCode(), DistributionWorkorderCodeEnum.WORK_ORDER_IS_NOT_EXIST.getMsg());
        }
        return JsonResult.success(workOrder);
    }

    /**
     * 判断是否有分配工单权限
     * 1）、超级管理员不能分配工单
     * 2）、部门管理员仅可分配本部门工单，无法分配子部门工单
     * 3）、普通用户不能分配工单
     *
     * 2023-05-11 角色权限功能改造为子定义，去除该检验
     *
     * @param userId
     * @param workOrder
     * @return
     */
    private JsonResult checkPermission(String userId, String tenantId, WorkOrder workOrder) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getId, userId)
                .eq(User::getTenantId, tenantId)
                .eq(User::getMark, 1));
        if (DataPermissionEnum.ALL.getCode() == user.getDataPermission()) {
            return JsonResult.error(DistributionWorkorderCodeEnum.ALL_NOT_DISTRIBUTION.getCode(), DistributionWorkorderCodeEnum.ALL_NOT_DISTRIBUTION.getMsg());
        } else if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == user.getDataPermission()) {
            if (!user.getDeptId().equals(workOrder.getDeptId())) {
                return JsonResult.error(DistributionWorkorderCodeEnum.ADMIN_NOT_DISTRIBUTION_CHILD_DEPT_WORK_ORDER.getCode(), DistributionWorkorderCodeEnum.ADMIN_NOT_DISTRIBUTION_CHILD_DEPT_WORK_ORDER.getMsg());
            }
            return JsonResult.success(user);
        } else if (DataPermissionEnum.DEPT.getCode() == user.getDataPermission()) {
            return JsonResult.error(DistributionWorkorderCodeEnum.ORDINARY_USER_NOT_DISTRIBUTION.getCode(), DistributionWorkorderCodeEnum.ORDINARY_USER_NOT_DISTRIBUTION.getMsg());
        }
        return JsonResult.error();
    }

    /**
     *
     *  分配工单
     *      1）、修改分配字段信息
     *      2）、修改工单状态
     *      3）、修改更新字段
     *
     * @param userId
     * @param request
     */
    private JsonResult distributionWorkOrder(String userId, DistributionWorkorderRequest request) {
        WorkOrder workOrder = new WorkOrder();
        workOrder.setId(request.getWorkorderId());
        workOrder.setUpdateUser(userId);
        workOrder.setUpdateTime(DateUtils.now());
        workOrder.setStatus(WorkOrderStatusEnum.PROCESSING.getCode());
        workOrder.setAssignDeptId(request.getAssignDeptId());
        workOrder.setAssignUser(request.getAssignUserIds());
        workOrder.setAssignTime(DateUtils.now());
        Integer rowCount = workOrderMapper.update(workOrder);
        if (rowCount <= 0) {
            log.info("修改工单状态， 确认失败");
            return JsonResult.error(GenerateWorkorderCodeEnum.GENERATE_IS_FAILED.getCode(), GenerateWorkorderCodeEnum.GENERATE_IS_FAILED.getMsg());
        }
        return JsonResult.success();
    }
}
