package com.hr.controller;


import com.alibaba.fastjson2.JSONObject;

import com.hr.dto.*;

import com.hr.fegin.dto.MyDemoDto;
import com.hr.repository.jpa.TestJpa;
import com.hr.repository.domain.TestEntity;
import com.hr.repository.service.DemoService;
import com.hr.repository.service.TransServer;
import com.github.pagehelper.PageHelper;

import com.hr.system.api.domain.SysDictData;
import com.yy.basedevelop.common.data.BasePageResult;
import com.yy.basedevelop.common.data.BaseReturnDto;


import com.yy.basedevelop.common.http.config.RedisService;

import com.yy.basedevelop.common.http.config.TokenUtil;
import com.yy.basedevelop.common.util.DictUtil;
import com.yy.basedevelop.common.util.ExcelUtil;
import com.yy.basedevelop.common.util.HttpClientUtils;
import com.yy.basedevelop.common.util.OSSUtil;
import com.yy.basedevelop.dto.LoginUser;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.codec.multipart.FilePart;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.random.RandomGenerator;


@Slf4j
@RestController
@RequestMapping("/test")
public class DemoController {

    @Autowired
    private TestJpa testJpa;
    @Autowired
    private DemoService sv;

    @Autowired
    private TransServer transServer;
    @Autowired
    private DemoService demoService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private OSSUtil oSSUtil;

    @GetMapping("aa")
    public Mono<MyDto> aa(ServerHttpRequest request) {

        sv.savee();
        LoginUser u= TokenUtil.getUser();
        if(u==null){
            throw new RuntimeException("没有找到用户");
        }
        return  Mono.just(MyDto.success(u));
    }

    @PostMapping("listdict")
    public TestDemoDto listdict(@RequestBody TestDemoDto dto) {
        log.info("listdict=:{}", dto);

        TestDemoDto dto1 = new TestDemoDto();
        //将中文的 字典类型，字典标签转换为字典的value
        //比如 用户性别,男 转换为 1
        dto1.setDictValue(DictUtil.getDictCodeStr(dto.getDictTypeNameCn(),dto.getDictNameCn()));
        Integer val=DictUtil.getDictCodeInt(dto.getDictTypeNameCn(),dto.getDictNameCn());
        log.info("val=:{}", val);
        return dto1;
    }

    @PostMapping("listoss")
    public TestDemoDto listoss(@RequestPart("file") FilePart filePart,
                               @RequestPart("description") String description,
                               @RequestPart("path") String path) {
        log.info("接收的listoss=:{},path={}", description,path);


        String ossstr=oSSUtil.upLoadInputStream(filePart, "esgin" + path);


        TestDemoDto dto1 = new TestDemoDto();
        dto1.setName("返回名字oss");
        dto1.setAge(25);
        dto1.setOssUrl(ossstr);
        return dto1;
    }

    @PostMapping("listname7")
    public Mono<TestDemoDto> list566d(@RequestBody TestDemoDto dto) {
        log.info("接收的DTO777=:{}", dto);


        TestDemoDto dto1 = new TestDemoDto();
        dto1.setName("返回的名字1");
        dto1.setAge(18);
        return Mono.just(dto1);
    }

    @PostMapping("listname8")
    public Mono<TestDemoDto> list5668(@RequestBody TestDemoDto dto) {
        log.info("接收的DTO8=:{}", dto);

        Boolean baaa=redisService.hasKey("aaa");
        log.info("在redis中aaa的key是否存在={}", baaa);

        TestDemoDto dto1 = new TestDemoDto();
        dto1.setName("直接返回Dto");
        dto1.setAge(26);
        return Mono.just(dto1);
    }

    @GetMapping("listname6")
    public Mono<TestDemoDto> listname6(ServerHttpResponse response) {
        JSONObject json = new JSONObject();
        json.put("name", "传输名字");
        json.put("age", "20");



        Mono<TestDemoDto> js=HttpClientUtils.post("http://localhost:9700/test/listname7",json,TestDemoDto.class);
        js.subscribe(js1->{
           log.info("当前返回的Dto:{}",js1);
        });
        TestDemoDto d=js.block();
        log.info("在Mono外部打印日志,返回值:{}",d);

        String returnstr=HttpClientUtils.post("http://localhost:9700/test/listname8",json);
        log.info("直接返回String:{}",returnstr);


        return js;

    }

    @GetMapping("listname5")
    public Mono<Void> export(ServerHttpResponse response) {
        LoginUser u= TokenUtil.getUser();
        log.info("user:{}",u);
        ExcelUtil<DemoExcelDto> util = new ExcelUtil<DemoExcelDto>(DemoExcelDto.class);
        List<DemoExcelDto> list = new ArrayList<>();
        DemoExcelDto d1 = new DemoExcelDto();
        d1.setName("名字1");
        d1.setTestCode("test1");
        d1.setMydate(new Date());
        d1.setSex("1");
        list.add(d1);
        DemoExcelDto d2 = new DemoExcelDto();
        d2.setName("名字2");
        d2.setTestCode("test2");
        d2.setMydate(new Date());
        d2.setSex("2");
        list.add(d2);
        DemoExcelDto d3 = new DemoExcelDto();
        d3.setName("名字3");
        d3.setTestCode("test3");
        d3.setMydate(new Date());
        d3.setSex("2");
        list.add(d3);

        DemoExcelDto d4 = new DemoExcelDto();
        d4.setName("名字4");
        d4.setTestCode("test4");//没有值则导出来是空白
        d4.setMydate(new Date());
        d4.setSex("2");
        list.add(d4);

        return util.exportExcel(response, list, "字典数据");
    }

    @PostMapping("listname3")
    public BaseReturnDto list222(@RequestBody SysDictData sysDictData) {

        List<SysDictData> list=DictUtil.getSysDictDataByKey(sysDictData.getDictType());
        return BaseReturnDto.success(list);
    }

    /***
     * 分页查询例子
     * @param dto
     * @return
     */
    @PostMapping("listname")
    public BasePageResult<MyDemoDto> queryname(@RequestBody QueryDto dto) {
        BasePageResult<MyDemoDto> lst=demoService.qyeryList(dto);

        return  lst.success();
    }

    /***
     * 分页查询例子,直接传Dto查询
     * @param dto
     * @return
     */
    @PostMapping("listpage2")
    public BasePageResult<MyDemoDto> listpage2(@RequestBody QueryDto dto) {
        BasePageResult<MyDemoDto> lst=demoService.qyeryList3(dto);

        return  lst.success();
    }


    @GetMapping("listname2")
    public BasePageResult<MyDemoDto> select1(@RequestParam("name") String name) {
        PageHelper.startPage(2, 10);
        return demoService.selectList1(name);
    }

    @GetMapping("calldemo2")
    public MyDto demo2() {


        return  MyDto.success();
    }

    @GetMapping("calldemo1")
    public MyDto demo1() {


        transServer.insertLog();


        return  MyDto.success();
    }
    @GetMapping("calldemo3")
    public MyDto demo3() {

        log.info("当前访问了calldemo3");
        transServer.testsubThread();


        return  MyDto.success();
    }

    @GetMapping("calldemo4")
    public MyDto demo4() {

        log.info("当前访问了calldemo4");



        return  MyDto.success();
    }

    @GetMapping("list1")
    public MyDto<JSONObject> list1() {

        log.info("list1");

        return MyDto.success(JSONObject.parseObject("{\"a\":1}"));
    }

    @PostMapping("/mothod1")
    public MyDto mothod1(@RequestBody MyParmDto dto) {
        log.info("当前访问了mothod1");


        transServer.method1(dto.getName());


        return   MyDto.success();
    }


    @GetMapping("username")
    public MyDto username(@RequestParam(value = "name", required = false) String name) {
        if (name == null || name.trim().isEmpty()) {
            JSONObject error = new JSONObject();
            error.put("error", "Name parameter is required and cannot be empty");
            MyDto d= MyDto.success(error);

            return  d;
        }


        JSONObject response = new JSONObject();
        response.put("name", name);
        MyDto d= MyDto.error(response);

        return d;
    }

    @GetMapping("anniu1")
    public BaseReturnDto<JSONObject> anniu1(){
        JSONObject response = new JSONObject();
        response.put("name", "按钮1,编辑权限");
        return BaseReturnDto.success(response);
    }

    @GetMapping("anniu2")
    public BaseReturnDto<JSONObject> anniu2(){
        JSONObject response = new JSONObject();
        response.put("name", "按钮2,删除权限");
        return BaseReturnDto.success(response);
    }

    @GetMapping("chaxun")
    public BaseReturnDto<JSONObject> chaxun(){
        JSONObject response = new JSONObject();
        response.put("name", "查询,没有设置权限");
        return BaseReturnDto.success(response);
    }

    @GetMapping("chaxun2")
    public BaseReturnDto<JSONObject> chaxun2(
            @RequestParam(value = "name", required = true) String name){
        JSONObject response = new JSONObject();
        response.put("name", "当前获取的name="+name);
        return BaseReturnDto.success(response);
    }

    @GetMapping("chaxun3")
    public BaseReturnDto chaxun3(
            @RequestParam(value = "name", required = true) String name){
        JSONObject response = new JSONObject();
        response.put("name", "当前获取的name="+name);
        return BaseReturnDto.success(response);
    }

    @GetMapping("query1")
    public BaseReturnDto<JSONObject> query1(
         @RequestParam(value = "name", required = true) String name){

        JSONObject response = new JSONObject();
        response.put("name", "查询,操作员权限pos:oper");
        try {

            int r= RandomGenerator.getDefault().nextInt(1,300);
            Thread.sleep(r);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        List<TestEntity> list=testJpa.findByName(name);
        log.info("===info1111111====byName="+JSONObject.toJSONString(list));

        PageHelper.startPage(1, 2);
        BasePageResult<TestEntity> pg1 =testJpa.queryMylist("111");
        log.info("===info1111111====size="+pg1.getTotal());
        log.info("===info1111111====name=");

        List<TestEntity> pg12 =testJpa.queryMylist2("sdaasdasd");
        log.info("===info1111111====size="+JSONObject.toJSONString(pg12));


        List<TestEntity> pg13 =testJpa.queryMylist3("sdaasdasd");
        log.info("===info1111111====size="+JSONObject.toJSONString(pg13));


        TestEntity tt1=new TestEntity();
        tt1.setName(name);
//        testJpa.save(tt1);

        return BaseReturnDto.success(response);
    }

    @GetMapping("query2")
    public BaseReturnDto<JSONObject> query2(){
        JSONObject response = new JSONObject();
        response.put("name", "查询,不在菜单范围内，没有设置权限字段");
        return BaseReturnDto.success(response);
    }

    @GetMapping("testSetaRmote1")
    public BaseReturnDto<JSONObject> testSetaRmote1(ServerWebExchange exchange,
                                                    @RequestParam(value = "name", required = true) String name){

        log.info("=========从demo2传入的值是:{}",name);

        JSONObject response = new JSONObject();
        response.put("msg", "远程调用成功!");
        sv.insertLog();
        log.info("=====调用成功g======");
        return BaseReturnDto.success(response).msg("操作成功");
    }

    @GetMapping("testSetaRmote2")
    public MyDto testSetaRmote2(ServerWebExchange exchange,
                                @RequestParam(value = "name", required = true) String name){
        MyDto dd= MyDto.success();
        JSONObject jj=new JSONObject();
        jj.put("mgs","好的");
        dd.setData(jj);
        log.info("=====调用成功testSetaRmote2======");
        return dd;
    }



}
