package com.tofly.watermeter.custom.controller.foreign;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.core.util.IpUtil;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.watermeter.config.ComConstans;
import com.tofly.watermeter.config.ForeignConfig;
import com.tofly.watermeter.custom.dto.*;
import com.tofly.watermeter.custom.vo.ForeignYhQyQdVo;
import com.tofly.watermeter.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author FlashWJL
 * @date 2021/12/7 13:19
 */
@RestController
@RequestMapping("/foreign")
@Api(tags = "对外提供的接口")
@AllArgsConstructor
@Slf4j
public class ForeignController {


    private final ForeignConfig foreignConfig;
    /**
     * 远传表
     */
    private final ReadmetereashisService readmetereashisService;
    /**
     * 分区分区段
     */
    private final YhbingqyService yhbingqyService;
    /**
     * 用户信息
     */
    private final QfkhjbxxService qfkhjbxxService;
    /**
     * 用户信息变更
     */
    private final ReadupdateService readupdateService;

    private final BwhbdatailService bwhbdatailService;


    @GetMapping("/authLogin")
    @ApiOperation(value = "登录")
    public ResultRespone authLogin(String username , String password) {
        Map<String , Object> map = new HashMap<>();
        map.put("username",username);
        // 临时代码限制ip 192.168.15.3访问 后续加入到网关过滤
        HttpServletRequest request = ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String ipAddr = IpUtil.getIpAddr(request);
        log.info("第三方调用登录账户{},密码{},ip:{}",username,password,ipAddr);
        if("192.168.15.3".equals(ipAddr)){
            log.error("限制ip访问ip:{}",ipAddr);
            return ResultRespone.failed("限制ip访问ip: "+ipAddr);
        }
        map.put("password",password);
        String result= HttpUtil.post(foreignConfig.getUrl()+"/auth/oauth/token", map);
        if(StringUtils.isEmpty(result)){
            return ResultRespone.failed("登录异常");
        }
        JSONObject jsonObject = JSON.parseObject(result);
        String code = jsonObject.get("code").toString();
        if ("1".equals(code)){
            Map<String , Object> tokenmap = new HashMap<>();
            tokenmap.put("token",JSON.parseObject(jsonObject.get("result").toString()).get("accessToken"));
            ResultRespone rt = ResultRespone.success(tokenmap);
            rt.setCode(ComConstans.INT_ZERO);
            return rt;
        }else {
            ResultRespone rt = ResultRespone.failed(jsonObject.get("message").toString());
            rt.setCode(ComConstans.INT_TWO);
            return rt;
        }
    }

    @PostMapping("/updateClient")
    @ApiOperation(value = "客户信息变更")
    public ResultRespone updateClient(@Valid @RequestBody ForeignYhInfoDto dto){
        try {
            SecurityUtils.getUserId();
        }catch (Exception e){
            return ResultRespone.failed("请登录");
        }
        ResultRespone rr = null;
        Object obj = qfkhjbxxService.saveYhInfo(dto);
        if(obj instanceof String){
            rr = ResultRespone.failed(String.valueOf(obj));
        }else {
            rr = ResultRespone.success(obj);
            rr.setCode(ComConstans.INT_ZERO);
        }
        return rr;
    }


    @PostMapping("/updateAmountOrWater")
    @ApiOperation(value = "客户金额或上次水量变更")
    public ResultRespone updateAmountOrWaterVolume(@Valid @RequestBody AmountOrWaterVolumeDto dto){
        try {
            SecurityUtils.getUserId();
        }catch (Exception e){
            return ResultRespone.failed("请登录");
        }
        ResultRespone rr = null;
        Object obj =  qfkhjbxxService.updateYhAmountOrWaterVolume(dto);
        if(obj instanceof String){
            rr = ResultRespone.failed(String.valueOf(obj));
        }else {
            rr = ResultRespone.success(obj);
            rr.setCode(ComConstans.INT_ZERO);
        }
        return rr;
    }


    @PostMapping("/updateChangeTable")
    @ApiOperation(value = "换表")
    public ResultRespone updateChangeTable(@Valid @RequestBody ChangeTableDto dto){
        try {
            SecurityUtils.getUserId();
        }catch (Exception e){
            return ResultRespone.failed("请登录");
        }
        ResultRespone rr = null;
        Object obj = bwhbdatailService.saveChangeTable(dto);
        if(obj instanceof String){
            rr = ResultRespone.failed(String.valueOf(obj));
        }else {
            rr = ResultRespone.success(obj);
            rr.setCode(ComConstans.INT_ZERO);
        }
        return rr;
    }


    @PostMapping("/updateWater")
    @ApiOperation(value = "水量信息变更")
    public ResultRespone updateWater(@Valid @RequestBody ForeignReadInfoDto dto){
        try {
            SecurityUtils.getUserId();
        }catch (Exception e){
            return ResultRespone.failed("请登录");
        }
        for (ForeignReadUpdateDto dt: dto.getDatas()) {
            Date date = cn.hutool.core.date.DateUtil.parse(dt.getMonth(),"yyyyMM");
        }
        boolean jg = readupdateService.saveReadupdate(dto);
        ResultRespone rr = null;
        if(jg){
            rr = ResultRespone.success(jg);
            rr.setCode(ComConstans.INT_ZERO);
        }else {
            rr = ResultRespone.failed(jg);
        }
        return rr;
    }

    @GetMapping("/getArea")
    @ApiOperation(value = "获取区域区域段用户绑定数据")
    public ResultRespone getArea(Page page, ForeignYhQyQdDto dto){
        try {
            SecurityUtils.getUserId();
        }catch (Exception e){
            return ResultRespone.failed("请登录");
        }
        Page<ForeignYhQyQdVo> vos= yhbingqyService.getUserQy(page,dto);
        ResultRespone rr = ResultRespone.success(vos);
        rr.setCode(ComConstans.INT_ZERO);
        return rr;
    }

    @PostMapping("/readFar")
    @ApiOperation(value = "远传表推送")
    public ResultRespone readFar(@Valid @RequestBody ForeignReadFarDo dto){
        try {
            SecurityUtils.getUserId();
        }catch (Exception e){
            return ResultRespone.failed("请登录");
        }
        HttpServletRequest request = ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String ipAddr = IpUtil.getIpAddr(request);
        log.error("ip访问ip:{},时间{}",ipAddr, DateUtil.getDateFormat(new Date(),DateUtil.DATETIME_DEFAULT_FORMAT));
        if("192.168.15.3".equals(ipAddr)){
            log.error("限制ip访问ip:{}",ipAddr);
            return ResultRespone.failed("限制ip访问ip: "+ipAddr);
        }
        boolean rt = readmetereashisService.saveBatchReadFar(dto);
        ResultRespone rr;
        if(rt){
            rr = ResultRespone.success(rt);
            rr.setCode(ComConstans.INT_ZERO);
        }else {
            rr = ResultRespone.failed(rt);
        }
        return rr;
    }

}
