package com.xunmei.sync.controller;

import com.xunmei.common.core.web.domain.AjaxResult;
import com.xunmei.sync.dto.fjnxsync.SyncFileDto;
import com.xunmei.sync.dto.fjnxsync.SyncResponseDto;
import com.xunmei.sync.service.IFJNXSyncService;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 *
 */
@Slf4j
@Api(description = "机构")
@Controller
@ApiOperation(value = "同步机构")
@RequestMapping("/fjnx")
class FjnxSyncController {

//    @Autowired
//    private OrgService orgService;

    @Autowired
    private IFJNXSyncService ifjnxSyncService;

    @GetMapping("/org")
    @ResponseBody
    AjaxResult SyncOrg() throws IOException {
        try {
            String resultMsg= ifjnxSyncService.SyncOrgInfo();
            if(StringUtil.isNullOrEmpty(resultMsg)){
                return AjaxResult.success("同步成功");
            }
            else
            {
                return AjaxResult.error("同步失败："+resultMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("机构同步失败" + e.getMessage());
        }
    }

    @GetMapping("/user")
    @ResponseBody
    AjaxResult SyncUser() throws Exception {

        try {
            String resultMsg=ifjnxSyncService.SyncUserInfo();
            if(StringUtil.isNullOrEmpty(resultMsg)){
                return AjaxResult.success("同步成功");
            }
            else
            {
                return AjaxResult.error("同步失败："+resultMsg);
            }
        } catch (Exception e) {
            return AjaxResult.error("人员同步失败" + e.getMessage());
        }
    }

    @GetMapping("/organduser")
    @ResponseBody
    AjaxResult SyncOrgAndUser(final MultipartFile file) throws IOException {

        try {
            ifjnxSyncService.SyncOrgAndUserInfo();
            return AjaxResult.success("同步成功");
        } catch (Exception e) {
            return AjaxResult.error("机构人员同步失败" + e.getMessage());
        }
    }

//    @GetMapping("/refresh/orgbusinesspath")
//    @ResponseBody
//    JsonResponse<String> refreshBusinesspath() throws IOException {
//        try {
//            ifjnxSyncService.RefreshBusinessPath();
//            return JsonResponse.success("刷新机构业务Path成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return JsonResponse.fail("刷新机构业务Path失败" + e.getMessage());
//        }
//    }

//    @GetMapping("/refresh/orgpath")
//    @ResponseBody
//    JsonResponse<String> refreshPath() throws IOException {
//        try {
//            List<Org> topOrgList = this.orgService.getTopOrg();
//            topOrgList.forEach(topOrg -> {
//                updateChild(topOrg.getId());
//            });
//            return JsonResponse.success("刷新机构path成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return JsonResponse.fail("刷新机构path失败" + e.getMessage());
//        }
//    }
//
//    private void updateChild(Long parentOrgId) {
//        List<Org> children = this.orgService.children(parentOrgId);
//        for (final Org org : children) {
//            this.orgService.resetPath(org);
//            this.updateChild(org.getId());
//        }
//    }


    /**
     * 同步机构测试接口
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/mock/orgfileInfo")
    @ResponseBody
    Object SyncOrgTest() throws IOException {
        try {
//          String a="{\n" +
//                  "    \"code\": 0,\n" +
//                  "    \"total\": 0,\n" +
//                  "    \"message\": null,\n" +
//                  "    \"level\": null,\n" +
//                  "    \"data\": {\n" +
//                  "        \"fileName\": \"Users20230525000100444107.xml\",\n" +
//                  "        \"fileId\": \"8d604f4a6c4c4bela6b777e09286d084\"\n" +
//                  "    },\n" +
//                  "    \"i18nData\": null\n" +
//                  "}";
            SyncResponseDto syncResponseDto = new SyncResponseDto();
            syncResponseDto.setCode(0);
            syncResponseDto.setTotal(0);
            SyncFileDto fileDto = new SyncFileDto();
            fileDto.setFileId("8d604f4a6c4c4bela6b777e09286d084");
            fileDto.setFileName("Users20230525000100444107.xml");
            syncResponseDto.setData(fileDto);
            return syncResponseDto;
        } catch (Exception e) {
            return AjaxResult.error("机构同步失败" + e.getMessage());
        }
    }

    @ApiOperation(value = "模拟返回机构数据接口")
    @GetMapping("/mock/orgxmldata")
    public void orgxmldata(HttpServletResponse response, HttpServletRequest request) {
        try {
            FileInputStream in = null;
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-disposition", "attachment;filename=file.xml");

            try {
                String path = this.getClass().getClassLoader().getResource("fjnxorg.xml").getPath();
                in = new FileInputStream(path);
                byte[] a = new byte[1024];
                int b;
                while ((b = in.read(a)) != -1) {
                    response.getOutputStream().write(a, 0, b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (null != in) {
                    try {
                        in.close();
                    } catch (IOException e2) {
                        System.out.println("关闭输入流错误");
                    }
                    try {
                        response.getOutputStream().close();
                    } catch (IOException e) {
                        System.out.println("输出流关闭错误");
                    }
                }
            }
        } catch (Exception ex) {
            log.error("Exception", ex);
            throw new RuntimeException("导出时发生异常");
        }
    }


    @ApiOperation(value = "模拟返回机构数据接口")
    @GetMapping("/mock/userxmldata")
    public void userxmldata(HttpServletResponse response, HttpServletRequest request) {
        try {
            FileInputStream in = null;
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-disposition", "attachment;filename=file.xml");

            try {
                String path = this.getClass().getClassLoader().getResource("fjnxuser.xml").getPath();
                in = new FileInputStream(path);
                byte[] a = new byte[1024];
                int b;
                while ((b = in.read(a)) != -1) {
                    response.getOutputStream().write(a, 0, b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (null != in) {
                    try {
                        in.close();
                    } catch (IOException e2) {
                        System.out.println("关闭输入流错误");
                    }
                    try {
                        response.getOutputStream().close();
                    } catch (IOException e) {
                        System.out.println("输出流关闭错误");
                    }
                }
            }
        } catch (Exception ex) {
            log.error("Exception", ex);
            throw new RuntimeException("导出时发生异常");
        }
    }


}