package pwc.taxtech.atms.controller;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import pwc.taxtech.atms.dpo.OrgBasicDto;
import pwc.taxtech.atms.dpo.OrgInfoDto;
import pwc.taxtech.atms.dpo.OrganizationDto;
import pwc.taxtech.atms.dpo.OrganizationExtraDto;
import pwc.taxtech.atms.dto.AreaOrganizationStatistics;
import pwc.taxtech.atms.dto.IndustryDto;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.OrganizationValidateDto;
import pwc.taxtech.atms.dto.dimension.DimensionOrgDtoDashboard;
import pwc.taxtech.atms.dto.dimension.OrgDashboardParams;
import pwc.taxtech.atms.dto.navtree.DevTreeDto;
import pwc.taxtech.atms.dto.navtree.NavTreeDto;
import pwc.taxtech.atms.dto.organization.DimensionRoleDto;
import pwc.taxtech.atms.dto.organization.OrgDto;
import pwc.taxtech.atms.dto.organization.OrgGeneralInfoDto;
import pwc.taxtech.atms.dto.organization.UpdateOrgDimensionDto;
import pwc.taxtech.atms.dto.vatdto.JsonExportDto;
import pwc.taxtech.atms.service.impl.OrganizationServiceImpl;
import pwc.taxtech.atms.service.impl.UserRoleServiceImpl;
import pwc.taxtech.atms.service.impl.UserServiceImpl;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
import static javax.servlet.http.HttpServletResponse.SC_OK;

@RestController
@RequestMapping("/api/v1/org/")
public class OrganizationController {

    private static Logger logger = LoggerFactory.getLogger(OrganizationController.class);

    @Autowired
    OrganizationServiceImpl organizationService;
    @Autowired
    UserRoleServiceImpl userRoleService;
    @Autowired
    UserServiceImpl userService;

//    @ApiOperation(value = "根据使用的方式获取机构的列表")
    @RequestMapping(value = "getjson", method = RequestMethod.GET)
    public @ResponseBody
    List<NavTreeDto> getOrgListToJson(@RequestParam("useType") Integer useType) {
        return organizationService.getOrgListToJson(useType);
    }

//    @ApiOperation(value = "获取根据机构筛选的属性和机构名称")
    @RequestMapping(value = "getOrganizationFilterList", method = RequestMethod.GET)
    public @ResponseBody
    List<OrganizationDto> getOrganizationFilterList() {
        return organizationService.getOrganizationFilterList();
    }

//    @ApiOperation(value = "根据使用的方式获取机构的展示列表")
    @RequestMapping(value = "display", method = RequestMethod.GET)
    public @ResponseBody
    List<OrganizationDto> getOrgList(@RequestParam("useType") Integer useType) {
        return organizationService.getOrgList(useType);
    }

//    @ApiOperation(value = "获取行业列表")
    @RequestMapping(value = "getProjectIndustrys", method = RequestMethod.GET)
    public @ResponseBody
    List<IndustryDto> getProjectIndustry() {
        logger.info("GET /api/v1/org/getProjectIndustrys");
        return organizationService.getProjectIndustryList();
    }

//    @ApiOperation(value = "层级显示机构列表_列表显示")
    @RequestMapping(value = "getOrgListLevel", method = RequestMethod.GET)
    public @ResponseBody
    List<OrgBasicDto> getOrgListLevel() {
        logger.info("GET /api/v1/org/getOrgListLevel");
        return organizationService.getOrgListLevel();
    }

    //    @ApiOperation(value = "层级显示机构列表_列表显示")
    @RequestMapping(value = "getOrgInfoList", method = RequestMethod.GET)
    public @ResponseBody
    List<OrgInfoDto> getOrgInfoList() {
        logger.info("GET /api/v1/org/getOrgInfoList");
        return organizationService.getOrgInfo();
    }

//    @ApiOperation(value = "纳税人识别号唯一性验证")
    @RequestMapping(value = "taxPayerNumberUniqueValidate", method = RequestMethod.POST)
    public @ResponseBody
    Boolean taxPayerNumberUniqueValidate(@RequestBody OrganizationValidateDto validateDto) {
        logger.info("POST /api/v1/org/taxPayerNumberUniqueValidate");
        return organizationService.taxPayerNumberUniqueValidate(validateDto);
    }

//    @ApiOperation(value = "获取机构展示面板(Dashboard)")
    @RequestMapping(value = "getOrgDashboard", method = RequestMethod.POST)
    public @ResponseBody
    List<DimensionOrgDtoDashboard> getOrgDashboardPost(
            @RequestBody(required = false) List<String> expandedOrgList,
            @RequestParam("dimensionID") String dimensionId, @RequestParam("parentOrgID") String parentOrgId) {
        logger.info("POST /api/v1/org/getOrgDashboard");
        OrgDashboardParams param = new OrgDashboardParams();
        param.setExpandedOrgList(expandedOrgList);
        return organizationService.getOrgDashboard(dimensionId, parentOrgId, param);
    }

//    @ApiOperation(value = "获取单个机构展示面板(Dashboard)")
    @RequestMapping(value = "getOrgDashboardOnly", method = RequestMethod.GET)
    public @ResponseBody
    List<DimensionOrgDtoDashboard> getOrgDashboard(@RequestParam("dimensionId") String dimensionId,
                                                   @RequestParam("parentOrgId") String parentOrgId, @RequestParam("filterFlag") String filterFlag) {
        logger.info("POST /api/v1/org/getOrgDashboardOnly");
        OrgDashboardParams param = new OrgDashboardParams();
        param.setFilterFlag(filterFlag);
        return organizationService.getOrgDashboard(dimensionId, parentOrgId, param);
    }

//    @ApiOperation(value = "显示覆盖区域统计数据")
    @RequestMapping(value = "getAreaStatistics", method = RequestMethod.GET)
    public AreaOrganizationStatistics getAreaStatistics() {
        logger.info("POST /api/v1/org/getAreaStatistics");
        return organizationService.getAreaStatistics();
    }

//    @ApiOperation(value = "获取机构上层维度")
    @RequestMapping(value = "getOrgBuAreaIndustryUser", method = RequestMethod.GET)
    public @ResponseBody
    List<DimensionRoleDto> getOrgBuAreaIndustryUser(@RequestParam("userID") String userId) {
        logger.info("POST /api/v1/org/getOrgBuAreaIndustryUser");
        return userRoleService.getOrgBuAreaIndustryUser(userId);
    }

//    @ApiOperation(value = "显示覆盖区域统计数据")
    @RequestMapping(value = "getOrgCustomDashbord", method = RequestMethod.GET)
    public OrgDto getOrgCustomDashbord(
            @RequestParam(value = "dimensionValueId", required = false) String dimensionValueId,
            @RequestParam(value = "parentDimensionId", required = false) String parentDimensionId,
            @RequestParam(value = "attributeId", required = false) String attributeId) {
        logger.info("POST /api/v1/org/getOrgCustomDashbord");
        return organizationService.getOrgCustomDashbord(dimensionValueId, parentDimensionId, attributeId);
    }

//    @ApiOperation(value = "获取区域下的所有机构")
    @RequestMapping(value = "getOrganizationListByAreaId", method = RequestMethod.GET)
    public List<OrganizationDto> getOrganizationListByAreaId(
            @RequestParam(value = "areaId", required = true) String areaId,
            @RequestParam(value = "attributeId", required = true) String attributeId) {
        logger.info("GET /api/v1/org/getOrganizationListByAreaId");
        return organizationService.getOrganizationListByAreaId(areaId, attributeId);
    }

    @SuppressWarnings("rawtypes")
//    @ApiOperation(value = "禁用选中机构信息")
    @RequestMapping(value = "disableOrgs", method = RequestMethod.POST)
    public @ResponseBody
    OperationResultDto disableOrgs(@RequestBody List<String> orgIds) {
        logger.info("POST /api/v1/org/disableOrgs");
        return organizationService.disableOrgs(orgIds);
    }

    @SuppressWarnings("rawtypes")
//    @ApiOperation(value = "启用选中机构信息")
    @RequestMapping(value = "enableOrgs", method = RequestMethod.GET)
    public @ResponseBody
    OperationResultDto enableOrgs(@RequestParam("orgId") String orgId) {
        logger.info("POST /api/v1/org/enableOrgs");
        return organizationService.enableOrgs(orgId);
    }

//    @ApiOperation(value = "通过orgId获取一个组织的信息")
    @RequestMapping(value = "displaySingle", method = RequestMethod.GET)
    public @ResponseBody
    OrganizationDto getSingleOrgByOrgId(@RequestParam("orgId") String orgId) {
        logger.info("POST /api/v1/org/displaySingle");
        return organizationService.getSingleOrgByOrgId(orgId);
    }

//    @ApiOperation(value = "通过orgId获取一个组织的其他信息")
    @RequestMapping(value = "displaySingleExtra", method = RequestMethod.GET)
    public @ResponseBody
    OrganizationExtraDto getSingleExtraOrgByOrgId(@RequestParam("orgId") String orgId) {
        logger.info("POST /api/v1/org/displaySingleExtra");
        return organizationService.getSingleOrgExtraByOrgId(orgId);
    }

//    @ApiOperation(value = "机构代码唯一性验证")
    @RequestMapping(value = "codeUniqueValidate", method = RequestMethod.POST)
    public @ResponseBody
    Boolean codeUniqueValidate(@RequestBody OrganizationValidateDto validateDto) {
        logger.info("POST /api/v1/org/codeUniqueValidate");
        return validateDto != null && organizationService.codeUniqueValidate(validateDto);
    }

    @SuppressWarnings("rawtypes")
//    @ApiOperation(value = "为当前的维度添加现有的机构,可以批量的添加", notes = "机构管理>卡片视角>点击机构+>关联现有机构>确定")
    @RequestMapping(value = "updateOrgToDimension", method = RequestMethod.POST)
    public @ResponseBody
    OperationResultDto updateOrgToDimension(@RequestBody UpdateOrgDimensionDto dto) {
        return organizationService.updateOrgToDimension(dto.getDimensionValueId(), dto.getDimensionId(),
                dto.getOrgDtoList());
    }

//    @ApiOperation(value = "增加机构信息")
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public @ResponseBody
    OperationResultDto<Object> addOrg(@RequestBody OrganizationDto orgDto) {
        logger.info("POST /api/v1/org/add");
        if (StringUtils.isBlank(orgDto.getClientCode()) && StringUtils.isNotBlank(orgDto.getCode())) {
            orgDto.setClientCode(orgDto.getCode());
        }
        return organizationService.addOrg(orgDto);
    }

//    @ApiOperation(value = "更新机构信息")
    @RequestMapping(value = "update", method = RequestMethod.PUT)
    public @ResponseBody
    OperationResultDto<Object> updateOrg(@RequestBody OrganizationDto orgDto) {
        logger.info("PUT /api/v1/org/update");
        if (StringUtils.isBlank(orgDto.getClientCode()) && StringUtils.isNotBlank(orgDto.getCode())) {
            orgDto.setClientCode(orgDto.getCode());
        }
        return organizationService.updateOrg(orgDto);
    }

//    @ApiOperation(value = "更新机构-其他信息")
    @RequestMapping(value = "updateExtra", method = RequestMethod.PUT)
    public @ResponseBody
    OperationResultDto<Object> updateOrgExtraInfo(@RequestBody OrganizationExtraDto orgExtraDto) {
        logger.info("PUT /api/v1/org/updateExtra");
        return organizationService.updateOrgExtra(orgExtraDto);
    }

//    @ApiOperation(value = "删除用户维度权限设置")
    @RequestMapping(value = "deleteUserDimensionValue", method = RequestMethod.POST)
    public @ResponseBody
    Boolean deleteUserDimensionValue(@RequestBody DimensionRoleDto dto,
                                     @RequestParam("userId") String userId) {
        userService.deleteUserDimensionValue(dto, userId);
        return true;
    }

//    @ApiOperation(value = "获取机构通用信息", notes = "机构管理>卡片视角>机构视图>点击机构灰色区域文字")
    @RequestMapping(value = "getGeneralInfo", method = RequestMethod.GET)
    public @ResponseBody
    OrgGeneralInfoDto getGeneralInfo(@RequestParam("orgId") String orgId) {
        logger.info("POST /api/v1/org/getGeneralInfo");
        return organizationService.getGeneralInfo(orgId);
    }

    @ResponseBody
//    @ApiOperation(value = "获取机构树信息", notes = "科目对应>复制对应关系>弹出层")
    @RequestMapping(value = "getOrgIvhTreeList", method = RequestMethod.GET)
    public List<DevTreeDto> getOrgIvhTreeList(@RequestParam("useType") Integer useType,
                                              @RequestParam("orgSetID") String orgSetId) {
        return organizationService.getOrgIvhTreeList(useType, orgSetId);
    }

    @RequestMapping(value = "downloadOrgListData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void downloadOrgListData(@RequestBody JsonExportDto exportData,HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.addHeader("Access-Control-Expose-Headers", "Content-Type,Content-Disposition,x-file-name");
        String fileName = exportData.getType() + "-" + new Date();
        response.setCharacterEncoding("UTF-8");
        OutputStream os = null;
        try {
            response.addHeader("Content-Disposition", "attachment;filename="
                    + UUID.randomUUID() + ".xls");
            response.addHeader("x-file-name", fileName);
            os = response.getOutputStream();
            int count = organizationService.getDownloadFilePath(exportData, os);
            if (count == 0) {
                response.setStatus(SC_NO_CONTENT);
            } else {
                response.setStatus(SC_OK);
            }
        } catch (IOException e) {
            logger.error(String.format("下载机构列表异常: %s",e.getMessage()));
        }
    }

}