package com.ningdatech.pmapi.ding.controller;

import com.alibaba.fastjson.JSON;
import com.ningdatech.irs.service.IRefreshTokenService;
import com.ningdatech.pmapi.common.util.CryptUtils;
import com.ningdatech.pmapi.common.util.RefreshKeyUtil;
import com.ningdatech.pmapi.ding.task.EmployeeBatchGetTask;
import com.ningdatech.pmapi.ding.task.GovBusinessStripsTask;
import com.ningdatech.pmapi.ding.task.OrganizationBatchGetTask;
import com.ningdatech.pmapi.irs.manage.AppIrsManage;
import com.ningdatech.pmapi.organization.manage.ProcDefManage;
import com.ningdatech.pmapi.projectlib.model.dto.ProjectDTO;
import com.ningdatech.pmapi.projectlib.model.entity.Project;
import com.ningdatech.pmapi.projectlib.service.IProjectService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

/**
 * <p>
 * PullDingInfoController
 * </p>
 *
 * @author WendyYang
 * @since 2023/6/2
 **/
@RestController
@RequestMapping("/api/v1/zwdd/pull")
@RequiredArgsConstructor
@Slf4j
public class DingInfoPullController {

    private final EmployeeBatchGetTask employeeBatchGetTask;
    private final GovBusinessStripsTask businessStripsTask;
    private final OrganizationBatchGetTask organizationBatchGetTask;

    private final ProcDefManage procDefManage;

    @Resource(name = "refreshToken")
    private IRefreshTokenService refreshTokenService;

    @Value("${irs.interface-refresh.request-token-url}")
    private String govRequestTokenUrl;
    @Value("${irs.interface-refresh.refresh-token-url}")
    private String govRefreshTokenUrl;

    private final AppIrsManage appIrsManage;

    private final IProjectService projectService;

    @GetMapping("/employee")
    public void employeeBatchGet() {
        employeeBatchGetTask.batchGetEmployeeTask();
    }

    @GetMapping("/businessStrips")
    public void businessStripsBatchGet() {
        businessStripsTask.batchGetGovBusinessStripsTask();
    }

    @GetMapping("/organization")
    public void organizationBatchGet() {
        organizationBatchGetTask.batchGetOrganizationTask();
    }

    @GetMapping("/employeeByRegionCode/{regionCode}")
    public void employeeBatchGetByRegionCode(@PathVariable String regionCode) {
        employeeBatchGetTask.batchGetEmployeeTaskByRegionCode(regionCode);
    }

    @GetMapping("/employeeByOrdCode/{orgCode}")
    public void employeeBatchGetByOrdCode(@PathVariable String orgCode) {
        employeeBatchGetTask.batchGetEmployeeTaskByOrdCode(orgCode);
    }

    @GetMapping("/getEmployeeByCode/{empCode}")
    public void getEmployeeByCode(@PathVariable String empCode) {
        employeeBatchGetTask.getEmployeeByCode(empCode);
    }

    @GetMapping("/getBatchEmployeeByCode/{orgCode}")
    public void getBatchEmployeeByCode(@PathVariable String orgCode) {
        employeeBatchGetTask.getBatchEmployeeByCode(orgCode);
    }

    @GetMapping("/getToken")
    public String getToken() {
       return employeeBatchGetTask.getToken();
    }

    @GetMapping("/getAuthToken")
    public String getAuthToken() {
        return employeeBatchGetTask.getAuthToken();
    }

    @ApiOperation(value = "系统流程配置初始化", notes = "系统流程配置初始化")
    @GetMapping("/init")
    public String init() {
        return procDefManage.init();
    }

    @ApiOperation(value = "系统流程配置初始化按区域", notes = "系统流程配置初始化按区域")
    @GetMapping("/init/{areaCode}")
    public String initByArea(@PathVariable String areaCode) {
        return procDefManage.initByArea(areaCode);
    }

    @ApiOperation(value = "项目详情推送", notes = "项目详情推送")
    @GetMapping("/push-project")
    public String pushProject() throws Exception {
        File f = new File("/temp/遂昌归集项目信息（需补）.xlsx");
//        File f = new File("C:\\Users\\PoffyZhang\\Desktop\\遂昌归集项目信息（需补）.xlsx");
        Workbook wb = readExcel(new FileInputStream(f),f.getName());
        Assert.notNull(wb,"文件流为空");
        Row row;
        Integer sucessNum = 0;
        if(wb != null){
            //获取第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            //获取最大列数
            for (int i = 1; i<rownum; i++) {
                row = sheet.getRow(i);
                if(Objects.isNull(row) || Objects.isNull(row.getCell(0))){
                    //取不到数据了 停止
                    log.info("数据取完");
                    break;
                }
                ProjectDTO projectDto = new ProjectDTO();

                projectDto.setProjectCode(row.getCell(0).toString());
                projectDto.setProjectName(row.getCell(1).toString());
                projectDto.setArea(row.getCell(2).toString());
                projectDto.setAreaCode(row.getCell(3).toString());
                String baseProjType = String.valueOf(row.getCell(4));
                if(StringUtils.isNotBlank(baseProjType) && baseProjType.contains(".")){
                    baseProjType = baseProjType.substring(0,
                            baseProjType.indexOf("."));
                }
                projectDto.setBaseProjType(baseProjType);
                projectDto.setBaseConstructionType(String.valueOf(row.getCell(5)));
                projectDto.setBaseProjConsClass(String.valueOf(row.getCell(6)));
                projectDto.setBaseLowestLevel(String.valueOf(row.getCell(7)));
                projectDto.setProjectYear(Integer.valueOf(String.valueOf(row.getCell(8))));
                projectDto.setBaseProjBasis(String.valueOf(row.getCell(9)));
                projectDto.setBuildBasis(String.valueOf(row.getCell(10)));
                String baseProjSerProg = String.valueOf(row.getCell(12));
                if(StringUtils.isNotBlank(baseProjSerProg) && baseProjSerProg.contains(".")){
                    baseProjSerProg = baseProjSerProg.substring(0,
                            baseProjSerProg.indexOf("."));
                }
                projectDto.setBaseProjSetProg(baseProjSerProg);
                projectDto.setResponsibleMan(String.valueOf(row.getCell(13)));
                projectDto.setResponsibleManMobile(String.valueOf(row.getCell(14)));
                projectDto.setContactName(String.valueOf(row.getCell(15)));
                projectDto.setContactPhone(String.valueOf(row.getCell(16)));
                projectDto.setBuildOrgName(String.valueOf(row.getCell(18)));
                projectDto.setBuildOrgCode(String.valueOf(row.getCell(19)));
                projectDto.setSuperOrg(String.valueOf(row.getCell(21)));
                projectDto.setSuperOrgCode(String.valueOf(row.getCell(22)));
                projectDto.setHigherSuperOrg(String.valueOf(row.getCell(24)));
                projectDto.setHigherSuperOrgCode(String.valueOf(row.getCell(25)));

                log.info("projectDto :{}",JSON.toJSONString(projectDto));

                if(StringUtils.isNotBlank(appIrsManage.pushProjectDetail(projectDto))){
                    sucessNum ++;
                }
            }
        }

        return "推送IRS项目详情成功数量:" + sucessNum;
    }

    @ApiOperation(value = "应用和项目关系推送", notes = "应用和项目关系推送")
    @GetMapping("/push-app-project")
    public String pushAppProject() throws Exception {
        long timestamp = System.currentTimeMillis();
        String areaCode = "331123";
        String appKey = "A331101453557202109017383";
        String appScret = "496f0f2a19994f76b4fd9dae087366c7";
        String baseProjSys = "初次建设的应用21";
        String baseProjSysCode = "A331123467587202307014177";
        String baseProjName = "遂昌县-nsl-项目测试004";
        String baseProjId = "331123230130123412186";
        String requestSecret = RefreshKeyUtil.getRequestSecret(appKey, appScret);
        String capCode = CryptUtils.encryptHMAC(timestamp + areaCode,"bcb4fc0f517fc168ee543fcf4d231f3b");
        String capTime = String.valueOf(timestamp);
        String sign = CryptUtils.MD5Encode(appKey + requestSecret + timestamp);
        String url = "https://interface.zjzwfw.gov.cn/gateway/api/proxy/001003001029/dataSharing/94wbaL1I1Pbz0648.htm?requestTime=" + timestamp +
                "&sign=" + sign + "&appKey=" + appKey + "&capCode=" + capCode + "&capTime=" + capTime +
                "&baseProjSys=" + baseProjSys + "&areaCode=331123&baseProjName=" + baseProjName + "&baseProjId=" +  baseProjId +
                "&isEffective=1&baseProjSysCode=" + baseProjSysCode;
        RestTemplate restTemplate = new RestTemplate();
        log.info("url :{}",url);
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);

        log.info(JSON.toJSONString(forEntity));

        return forEntity.getBody();
    }

    @ApiOperation(value = "项目详情推送", notes = "项目详情推送")
    @GetMapping("/push-project-detail")
    public String pushProjectDetail() throws NoSuchAlgorithmException {
        Project project = projectService.getById(189L);
        ProjectDTO projectDto = new ProjectDTO();

        projectDto.setProjectCode(project.getProjectCode());
        projectDto.setProjectName(project.getProjectName());
        projectDto.setArea(project.getArea());
        projectDto.setAreaCode(project.getAreaCode());
        projectDto.setBaseProjType("1");
        projectDto.setBaseConstructionType("03");
        projectDto.setBaseProjConsClass("C");
        projectDto.setBaseLowestLevel("C");
        projectDto.setProjectYear(project.getProjectYear());
        projectDto.setBaseProjBasis("1");
        projectDto.setBuildBasis("01");
        projectDto.setBaseProjSetProg("05");
        projectDto.setResponsibleMan(project.getResponsibleMan());
        projectDto.setResponsibleManMobile(project.getResponsibleManMobile());
        projectDto.setContactName(project.getContactName());
        projectDto.setContactPhone(project.getContactPhone());
        projectDto.setBuildOrgName(project.getBuildOrgName());
        projectDto.setBuildOrgCode(project.getBuildOrgCode());
        projectDto.setSuperOrg(project.getSuperOrg());
        projectDto.setSuperOrgCode(project.getSuperOrgCode());
        projectDto.setHigherSuperOrg(project.getHigherSuperOrg());
        projectDto.setHigherSuperOrgCode(project.getHigherSuperOrgCode());

        log.info("projectDto :{}",JSON.toJSONString(projectDto));

        if(StringUtils.isNotBlank(appIrsManage.pushProjectDetail(projectDto))){
            return "推送成功";
        }
        return "推送失败";
    }

    public static Workbook readExcel(InputStream is, String extString){
        Workbook wb = null;

        extString = extString.substring(extString.lastIndexOf("."));
        try {
            if(".xls".equals(extString)){
                return wb = new HSSFWorkbook(is);
            }else if(".xlsx".equals(extString)){
                return wb = new XSSFWorkbook(is);
            }else {
                return wb = null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }
}
