package com.mortals.xhx.busiz.web;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.ILogService;
import com.mortals.framework.service.impl.FileLogServiceImpl;
import com.mortals.xhx.base.system.resource.model.ResourceEntity;
import com.mortals.xhx.busiz.req.TestReq;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.busiz.rsp.DeviceResp;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import com.mortals.xhx.common.utils.ControllerScanUtil;
import com.mortals.xhx.common.utils.ImgUtils;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.model.DeviceQuery;
import com.mortals.xhx.module.device.service.DeviceService;
import com.mortals.xhx.module.product.model.ProductEntity;
import com.mortals.xhx.module.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备
 *
 * @author: zxfei
 * @date: 2021/8/24 20:28
 */
@RestController
@Slf4j
@RequestMapping("test")
public class TestSendMsgController {
    @Autowired
    protected ILogService logService = FileLogServiceImpl.getInstance();
    @Autowired
    private ProductService productService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ICacheService cacheService;

    /**
     * 发送日志消息
     *
     * @param req
     * @return
     */
    @PostMapping("log")
    public String register(@RequestBody TestReq req) {
        log.info("【测试消息】【请求体】-->  " + JSONObject.toJSONString(req));
        ApiResp<DeviceResp> rsp = new ApiResp<>();
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());


        log.info("响应【设备注册】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return JSON.toJSONString(rsp);
    }

    @GetMapping("updateDevice")
    public Rest<Void> updateDevice() {
        List<DeviceEntity> updateProductCodeList = deviceService.find(new DeviceQuery());

        for (DeviceEntity deviceEntity : updateProductCodeList) {
            deviceService.update(deviceEntity);
        }

        return Rest.ok();
    }


    @GetMapping("reDeviceProductCode")
    public String reDeviceProductCode() {
        log.info("刷新设备的产品编码");
        ApiResp<DeviceResp> rsp = new ApiResp<>();
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        List<DeviceEntity> updateProductCodeList = deviceService.find(new DeviceQuery()).stream().map(deviceEntity -> {
            if (ObjectUtils.isEmpty(deviceEntity.getProductCode()) && !ObjectUtils.isEmpty(deviceEntity.getProductId())) {
                ProductEntity cache = productService.getCache(deviceEntity.getProductId().toString());
                if (!ObjectUtils.isEmpty(cache)) {
                    deviceEntity.setProductCode(cache.getProductCode());
                    DeviceEntity temp = new DeviceEntity();
                    temp.setId(deviceEntity.getId());
                    temp.setProductCode(cache.getProductCode());
                    temp.setUpdateTime(new Date());
                    return temp;
                }
            }
            return null;
        }).filter(f -> f != null).collect(Collectors.toList());

        if (!ObjectUtils.isEmpty(updateProductCodeList)) {
            log.info("更新设备产品列表，size:{}，str:{}", updateProductCodeList.size(), JSON.toJSONString(updateProductCodeList));
            deviceService.getDeviceDao().updateBatch(updateProductCodeList);
        }
        return JSON.toJSONString(rsp);
    }


    @GetMapping("reDevicePerson")
    public String reDevicePerson() {
        log.info("刷新人员");
        ApiResp<DeviceResp> rsp = new ApiResp<>();
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());

        List<DeviceEntity> updateList = deviceService.find(new DeviceQuery()).stream().map(device -> {
            Boolean bool = false;
            if ("周杨".equals(device.getLeadingOfficial())) {
                device.setLeadingOfficial("文浩辰");
                bool = true;
            }

            if ("13265985698".equals(device.getLeadingOfficialTelephone())) {
                device.setLeadingOfficialTelephone("15775958217");
                bool = true;
            }
            if ("15108243162".equals(device.getLeadingOfficialTelephone())) {
                device.setLeadingOfficialTelephone("15775958217");
                bool = true;
            }
            if (bool) {
                return device;
            }
            return null;

        }).filter(f -> f != null).collect(Collectors.toList());

        if (!ObjectUtils.isEmpty(updateList)) {
            log.info("更新设备产品列表，size:{}，str:{}", updateList.size(), JSON.toJSONString(updateList));
            deviceService.update(updateList, null);
        }
        return JSON.toJSONString(rsp);
    }


    @RequestMapping(value = "{key}/{value}", method = RequestMethod.GET)
    public String setData(@PathVariable("key") String key,
                          @PathVariable("value") String value) {
        cacheService.set(key, value);
        String s = cacheService.get(key);
        return s;
    }


    @PostMapping("scan")
    @UnAuth
    public String scan() {
        List<Class<?>> classList = ControllerScanUtil.getAllClassByPackageName("com.mortals.xhx");
        //System.out.println(classList); //获取到了所有的类
        List<ResourceEntity> list = ControllerScanUtil.getAnnotationInfo(classList);
        return JSON.toJSONString(list);

    }


    public static void main(String[] args) {

        String resp = HttpUtil.get("http://59.225.206.13:8331/oauth-pro/admin-pro/sys/randomImage/1675827431800?_t=1675827431");
        JSONObject jsonObject = JSON.parseObject(resp);

        //  log.info("resp:{}",resp);
        log.info("result:{}", jsonObject.get("result"));
        String OriginalImg = "F:\\pics\\2.jpg";
        String ocrResult = "F:\\pics\\2-1.jpg";
        Base64.decodeToFile(StrUtil.replace(jsonObject.get("result").toString(), "data:image/jpg;base64,", ""), new File(OriginalImg));
        ImgUtils.removeBackground(OriginalImg, ocrResult);

        // log.info(code);
/*

        //原始验证码地址

        //识别样本输出地址
        String ocrResult = "F:\\pics\\2.jpg";

        //测试登录
        //获取并识别验证码
        ImgUtils.removeBackground(OriginalImg, ocrResult);
*/


    }


}
