package com.tuoheng.admin.service.inspection.update;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.conver.InspectionConverMapper;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.entity.Channel;
import com.tuoheng.admin.entity.Leg;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.InspectionExecutionStatusEnum;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.DataPermissionEnum;
import com.tuoheng.admin.enums.code.inspection.EditInspectionCodeEnum;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.mapper.ChannelMapper;
import com.tuoheng.admin.mapper.LegMapper;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.request.inspection.EditInspectionRequest;
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;

/**
 * 修改任务业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-11-24
 */
@Slf4j
@Service
public class UpdateInspectionService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private ChannelMapper channelMapper;

    @Autowired
    private LegMapper legMapper;

    /**
     * 修改任务
     *  1、机场任务：
     *      1）、只有本部门管理员（上上级部门管理员不可编辑）和创建用户才能编辑；
     *      2）、待执行任务，执行后不可编辑；
     *      3）、编辑信息包括，任务地点，航段，巡检机场，巡检路线，巡检时间，执行时间
     *  2、飞手任务不能编辑。
     *
     * @return
     */
    public JsonResult update(EditInspectionRequest editInspectionRequest) {
        log.info("进入修改任务业务接口");
        User user = CurrentUserUtil.getUserInfo();
        String tenantId = user.getTenantId();
        JsonResult result = this.check(tenantId, editInspectionRequest);
        if (0 != result.getCode()) {
            log.info("修改任务业务接口：校验失败：{}", result.getMsg());
            return result;
        }
        Inspection inspectionOld = (Inspection) result.getData();
        result = checkPermissions(user, inspectionOld.getCreateUser());
        if (0 != result.getCode()) {
            log.info("修改任务业务接口：校验权限失败：{}", result.getMsg());
            return result;
        }

        Inspection inspection = InspectionConverMapper.INSTANCE.fromEditInspectionRequestToInspection(editInspectionRequest);
        inspection.setUpdateUser(user.getId());
        inspection.setUpdateTime(DateUtils.now());

        Integer rowId = inspectionMapper.update(inspection);
        if (rowId <= 0) {
            log.info("修改任务业务接口：修改任务失败：{}", result.getMsg());
            return JsonResult.error(EditInspectionCodeEnum.EDIT_IS_FAILED.getCode(), EditInspectionCodeEnum.EDIT_IS_FAILED.getMsg());
        }

        log.info("修改任务业务接口：修改任务成功:{}", inspection);
        return JsonResult.success();
    }

    /**
     * 检查参数
     * @param tenantId
     * @param editInspectionRequest
     * @return
     */
    private JsonResult check(String tenantId, EditInspectionRequest editInspectionRequest) {
        if (StringUtils.isEmpty(editInspectionRequest.getId())) {
            return JsonResult.error(EditInspectionCodeEnum.ID_IS_NULL.getCode(), EditInspectionCodeEnum.ID_IS_NULL.getMsg());
        }

        if (null == editInspectionRequest.getChannelId() || StringUtils.isEmpty(editInspectionRequest.getChannelName())) {
            return JsonResult.error(EditInspectionCodeEnum.ROAD_IS_NULL.getCode(), EditInspectionCodeEnum.ROAD_IS_NULL.getMsg());
        }

        if (null == editInspectionRequest.getLegId() || StringUtils.isEmpty(editInspectionRequest.getLegName()) ) {
            return JsonResult.error(EditInspectionCodeEnum.SECTION_IS_NULL.getCode(), EditInspectionCodeEnum.SECTION_IS_NULL.getMsg());
        }

        if (null == editInspectionRequest.getAirportId() || StringUtils.isEmpty(editInspectionRequest.getAirportName())) {
            return JsonResult.error(EditInspectionCodeEnum.AIRPORT_IS_NULL.getCode(), EditInspectionCodeEnum.AIRPORT_IS_NULL.getMsg());
        }

        if (null == editInspectionRequest.getInspectionLine() || StringUtils.isEmpty(editInspectionRequest.getInspectionLineName())) {
            return JsonResult.error(EditInspectionCodeEnum.INSPECTION_LINE_IS_NULL.getCode(), EditInspectionCodeEnum.INSPECTION_LINE_IS_NULL.getMsg());
        }
        if (null == editInspectionRequest.getInspectionTime()) {
            return JsonResult.error(EditInspectionCodeEnum.INSPECTION_TIME_IS_NULL.getCode(), EditInspectionCodeEnum.INSPECTION_TIME_IS_NULL.getMsg());
        }
        int timaDiff = DateUtils.compareToDate(editInspectionRequest.getInspectionTime(), DateUtils.now());
        if (2 != timaDiff) {
            return JsonResult.error(EditInspectionCodeEnum.INSPECTION_TIME_NOT_AFTER_THAN_CURRENT_TIME.getCode(), EditInspectionCodeEnum.INSPECTION_TIME_NOT_AFTER_THAN_CURRENT_TIME.getMsg());
        }

        //查询当前对应的任务
        Inspection inspection = inspectionMapper.selectOne(Wrappers.<Inspection>lambdaQuery()
                                    .eq(Inspection::getId, editInspectionRequest.getId())
                                    .eq(Inspection::getTenantId,tenantId)
                                    .eq(Inspection::getMark, MarkEnum.VALID.getCode()));
        if (ObjectUtil.isNull(inspection)) {
            return JsonResult.error(EditInspectionCodeEnum.INSPECTION_IS_NOT_EXIST.getCode(), EditInspectionCodeEnum.INSPECTION_IS_NOT_EXIST.getMsg());
        }
        if (InspectionStatusEnum.WAIT_FLIGHT.getCode() != inspection.getStatus()) {
            return JsonResult.error(EditInspectionCodeEnum.INSPECTION_IS_NOT_WAIT_FLIGHT.getCode(), EditInspectionCodeEnum.INSPECTION_IS_NOT_WAIT_FLIGHT.getMsg());
        }
        if (InspectionExecutionStatusEnum.EXECUTED.getCode() == inspection.getExecutionStatus()) {
            return JsonResult.error(EditInspectionCodeEnum.INSPECTION_IS_EXECUTED.getCode(), EditInspectionCodeEnum.INSPECTION_IS_EXECUTED.getMsg());
        }

        Integer count = channelMapper.selectCount(Wrappers.<Channel>lambdaQuery()
                            .eq(Channel::getTenantId, tenantId)
                            .eq(Channel::getId, editInspectionRequest.getChannelId())
                            .eq(Channel::getMark, MarkEnum.VALID.getCode()));

        if (count <= 0) {
            return JsonResult.error(EditInspectionCodeEnum.ROAD_IS_NOT_EXIST.getCode(), EditInspectionCodeEnum.ROAD_IS_NOT_EXIST.getMsg());
        }
        count = legMapper.selectCount(Wrappers.<Leg>lambdaQuery()
                                .eq(Leg::getTenantId, tenantId)
                                .eq(Leg::getId, editInspectionRequest.getLegId())
                                .eq(Leg::getMark, MarkEnum.VALID.getCode()));
        if (count <= 0) {
            return JsonResult.error(EditInspectionCodeEnum.SECTION_IS_NOT_EXIST.getCode(), EditInspectionCodeEnum.SECTION_IS_NOT_EXIST.getMsg());
        }
        return JsonResult.success(inspection);
    }

    /**
     * 检查权限
     *  只有本部门管理员（上上级部门管理员不可编辑）和创建用户才能修改
     *
     * @param user
     * @param createUser
     * @return
     */
    private JsonResult checkPermissions(User user, String createUser) {
        if (user.getId().equals(createUser)) {
            // 是自己创建的，可修改
            return JsonResult.success();
        }
        // 查询部门管理员，若是部门管理员可修改，非部门管理员不能修改
        User userTmp = userMapper.selectOne(new LambdaQueryWrapper<User>()
                        .eq(User::getDeptId, user.getDeptId())
                        .eq(User::getDataPermission, DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode())
                        .eq(User::getMark, MarkEnum.VALID.getCode()));
        if (ObjectUtil.isNull(userTmp)) {
            return JsonResult.error(EditInspectionCodeEnum.NON_DEPT_ADMIN_NOT_EDIT.getCode(), EditInspectionCodeEnum.NON_DEPT_ADMIN_NOT_EDIT.getMsg());
        }
        if (!user.getId().equals(userTmp.getId())) {
            return JsonResult.error(EditInspectionCodeEnum.NON_DEPT_ADMIN_NOT_EDIT.getCode(), EditInspectionCodeEnum.NON_DEPT_ADMIN_NOT_EDIT.getMsg());
        }
        return JsonResult.success();
    }
}
