package com.yeejoin.amos.boot.module.hygf.biz.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.hygf.api.Enum.AcceptanceStatusEnum;
import com.yeejoin.amos.boot.module.hygf.api.dto.AcceptanceDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.UserUnitInformationDto;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PersonnelBusinessMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IAcceptanceService;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "验收管理")
@RequestMapping(value = "/acceptance")
public class AcceptanceController  extends BaseController {

    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;
    @Autowired
    private IAcceptanceService acceptanceService;

    @PostMapping(value = "/page")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "Get", value = "获取验收单列表", notes = "获取验收单列表")
    public ResponseModel<IPage<AcceptanceDto>> page(
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "size", required = false, defaultValue = "20") Integer size,
            @RequestBody AcceptanceDto param
    ) {
        UserUnitInformationDto userUnitInformationDto = personnelBusinessMapper.getUserUnitInformationDto(getUserInfo().getUserId());

        param.setRegionCompanyId(userUnitInformationDto.getRegionalCompaniesSeq());
        param.setAmosDealerId(userUnitInformationDto.getAmosDealerId());

        // 获取用户权限
        Set<String> roles = new HashSet<>();
        try {
            FeignClientResult<AgencyUserModel> response = Privilege.agencyUserClient.getme();
            if (response.getStatus() == 200) {
                AgencyUserModel agencyUser = response.getResult();
                Map<Long, List<RoleModel>> orgRoles = agencyUser.getOrgRoles();
                orgRoles.values().forEach(roleModels -> roles.addAll(roleModels.stream().map(RoleModel::getRoleTypeName).collect(Collectors.toSet())));
            } else {
                throw new RuntimeException("获取用户权限失败");
            }
        } catch (RuntimeException e) {
            throw new RuntimeException(e.getMessage());
        }
        Set<String> acceptanceStatusSet = this.getFullAcceptanceStatus();
        // 用户光伏-法务：看不到未通过投融审核的电站
        if (roles.contains("户用光伏-法务") || roles.contains("户用光伏-经销商-法务")) {
            acceptanceStatusSet.remove(String.valueOf(AcceptanceStatusEnum.待提交验收.getCode()));
            acceptanceStatusSet.remove(String.valueOf(AcceptanceStatusEnum.待投融验收.getCode()));
            acceptanceStatusSet.remove(String.valueOf(AcceptanceStatusEnum.投融验收不通过.getCode()));
        }
        // 用户光伏-工程： 看不到未通过法务审核的电站
        else if (roles.contains("户用光伏-工程") || roles.contains("户用光伏-经销商-工程")) {
            acceptanceStatusSet.remove(String.valueOf(AcceptanceStatusEnum.待提交验收.getCode()));
            acceptanceStatusSet.remove(String.valueOf(AcceptanceStatusEnum.待投融验收.getCode()));
            acceptanceStatusSet.remove(String.valueOf(AcceptanceStatusEnum.投融验收不通过.getCode()));
            acceptanceStatusSet.remove(String.valueOf(AcceptanceStatusEnum.待法务验收.getCode()));
            acceptanceStatusSet.remove(String.valueOf(AcceptanceStatusEnum.法务验收不通过.getCode()));
        }

        IPage<AcceptanceDto> page = new Page<>(current, size);
        if (StringUtils.hasText(param.getAcceptanceStatus())) {
            if (acceptanceStatusSet.contains(param.getAcceptanceStatus())) {
                acceptanceStatusSet = new HashSet<>(Collections.singletonList(param.getAcceptanceStatus()));
            } else {
                return ResponseHelper.buildResponse(page);
            }
        }
        param.setAcceptanceStatus(String.join(",", acceptanceStatusSet));

        page = acceptanceService.page(page, param);

        return ResponseHelper.buildResponse(page);
    }

    @GetMapping("/offline-acceptance-details")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "Get", value = "获取验收单列表", notes = "获取验收单列表")
    public ResponseModel<Map<String, Object>> offlineAcceptanceDetails(@RequestParam("sequenceNbr") Long sequenceNbr) {
        return ResponseHelper.buildResponse(acceptanceService.offlineAcceptanceDetails(sequenceNbr));
    }

    private Set<String> getFullAcceptanceStatus() {
        String[] array = new String[AcceptanceStatusEnum.验收完成.getCode() + 1];
        for (int i = AcceptanceStatusEnum.待提交验收.getCode(); i <= AcceptanceStatusEnum.验收完成.getCode(); i++) {
            array[i] = String.valueOf(i);
        }
        return Arrays.stream(array).filter(Objects::nonNull).collect(Collectors.toSet());
    }
}
