package com.ruoyi.web.work.api;

import com.google.code.kaptcha.Producer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.web.work.api.config.BaseController;
import com.ruoyi.web.work.api.util.AppUtil;
import com.ruoyi.web.work.domain.Column;
import com.ruoyi.web.work.domain.Platform;
import com.ruoyi.web.work.domain.dto.OcrDto;
import com.ruoyi.web.work.service.IColumnService;
import com.ruoyi.web.work.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/app/common")
public class Api_CommonController extends BaseController {

    @Autowired
    private RedisCache redisCache;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private IColumnService columnService;

    @Autowired
    IUserService userService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/type/{dictType}")
    public AjaxResult dictType(@PathVariable String dictType) {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data)) {
            data = new ArrayList<>();
        }
        return AjaxResult.success(data);
    }

    @GetMapping(value = "/agreement/{title}")
    public AjaxResult agreement(@PathVariable String title) {
        Platform platform = redisCache.getCacheObject(CacheConstants.APP_PLATFORM);
        if (title.equals("用户协议")) {
            return AjaxResult.success(platform.getAgreement());
        }
        if (title.equals("隐私政策")) {
            return AjaxResult.success(platform.getPrivacy());
        }
        return AjaxResult.error();
    }

    //图片上传
    @PostMapping("/upload")
    public AjaxResult upload(MultipartHttpServletRequest multiReq) {
        try {
            AjaxResult ajax = AjaxResult.success();
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            String fileName = FileUploadUtils.upload(filePath, multiReq.getFile("file"));
            ajax.put("fileName", fileName);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/ocr")
    public AjaxResult ocr(@Validated @RequestBody OcrDto dto) {
        return AjaxResult.success(AppUtil.idCard(dto.getImageUrl(), dto.getSide()));
    }

    @GetMapping("/column/list")
    public AjaxResult list(@Validated Column column) {
        String key = CacheConstants.APP_COLUMN_KEY + "-" + column.getType();
        if (redisCache.getCacheObject(key) == null) {
            List<Map<String, Object>> all = columnService.treeJson(column);
            List<Map<String, Object>> list = all.stream().filter(r -> r.get("parentId") == null).collect(Collectors.toList());
            for (Map record : list) {
                List<Map<String, Object>> list2 = all.stream().filter(r -> r.get("parentId") != null && r.get("parentId").equals(record.get("id"))).collect(Collectors.toList());
                record.put("children", list2);
                for (Map record2 : list2) {
                    List<Map<String, Object>> list3 = all.stream().filter(r -> r.get("parentId") != null && r.get("parentId").equals(record2.get("id"))).collect(Collectors.toList());
                    record2.put("children", list3);
                }
            }
            redisCache.setCacheObject(key, list, 365, TimeUnit.DAYS);
            return AjaxResult.success(list);
        } else {
            List<Map<String, Object>> list = redisCache.getCacheObject(key);
            return AjaxResult.success(list);
        }
    }

    //所有区域列表
    @GetMapping("/column/city/all")
    public AjaxResult city_all() {
        String key = CacheConstants.APP_COLUMN_KEY + "-region-all";
        if (redisCache.getCacheObject(key) == null) {
            List<Map<String, Object>> all = columnService.selectCityAll();
            redisCache.setCacheObject(key, all, 365, TimeUnit.DAYS);
            return AjaxResult.success(all);
        } else {
            List<Map<String, Object>> all = redisCache.getCacheObject(key);
            return AjaxResult.success(all);
        }

    }

    @GetMapping("/column/search")
    public AjaxResult search(@Validated Column column) {
        if (column.getType().equals("position")) {
            column.setLevel(3);
        }
        List<Map<String, Object>> list = columnService.selectByTitle(column);
        return AjaxResult.success(list);
    }

    //图形验证码
    @GetMapping("/captcha")
    public AjaxResult captcha() {
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        // 生成验证码
        String capText = captchaProducerMath.createText();
        String capStr = capText.substring(0, capText.lastIndexOf("@"));
        String code = capText.substring(capText.lastIndexOf("@") + 1);
        BufferedImage image = captchaProducerMath.createImage(capStr);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
            redisCache.setCacheObject(verifyKey, code, 2, TimeUnit.MINUTES);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("uuid", uuid);
        ajax.put("img", "data:image/gif;base64," + Base64.encode(os.toByteArray()));
        return AjaxResult.success(ajax);
    }
}

