package com.malk.ruisi.controller;

/**
 * 错误抛出与拦截详见 CatchException
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.malk.ruisi.service.RSService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McException;
import com.malk.server.common.McR;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilServlet;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("dd")
public class DDController {

    @Autowired
    private RSService rsService;

    /**
     * 创建投资人用户
     */
    @PostMapping("user/sync")
    McR syncUser() {

        log.info("syncUser");
        rsService.syncDingTalk_exclusive();
        return McR.success();
    }

    /**
     * 重置密码流程
     */
    @PostMapping("reset")
    McR resetPwd(HttpServletRequest request) {

        Map data = UtilServlet.getParamMap(request);
        log.info("reset, {}", data);

        McException.assertParamException_Null(data, "userId", "password");
        rsService.resetPwd(data);
        return McR.success();
    }


    public void xxx() {
        portal_cache = new HashMap();

        _portalList("财务专区");
    }

    @Autowired
    private YDClient ydClient;

    /// 数据缓存 + 图片缓存, 10 分钟更新一次
    private Map portal_cache = new HashMap();

    /**
     * 工作台数据
     */
    private List<Map> _portalList(String type) {

        List<Map> pList = UtilMap.getList(portal_cache, type);

        if (pList.isEmpty()) {
            List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()
                    .formUuid("FORM-D46C46DACD644467B8F6902EBFD8FDFEYFOX")
                    .pageSize(5)
                    .searchFieldJson(JSONObject.toJSONString(UtilMap.map("selectField_m17kv4an", type)))
                    .build(), YDConf.FORM_QUERY.retrieve_search_form).getData();

            dataList.sort(Comparator.comparingInt(item -> UtilMap.getInt(item, "numberField_m17kv4ao"))); // 排序
            pList = dataList.stream().map(item -> {
                Map formData = UtilMap.getMap(item, "formData");

                Map row = UtilMap.map("title, source, link", UtilMap.getString(formData, "textField_m17kv4aq"), UtilMap.getString(formData, "textField_m17kv4as"), UtilMap.getString(formData, "textField_m17kv4at"));
                long date = UtilMap.getLong(formData, "dateField_m17kv4ar");
                if (date > 0L) {
                    row.put("dateTime", UtilDateTime.format(new Date(date), "yyyy-MM-dd HH:mm"));
                }
                // 图片免登处理
                String image = UtilMap.getString(formData, "imageField_m1abjxl0");
                if (StringUtils.isNotBlank(image)) {
                    List<Map> attas = (List<Map>) JSON.parse(image);
                    row.put("image", ydClient.convertTemporaryUrl(UtilMap.getString(attas.get(0), "url")));
                }
                return row;
            }).collect(Collectors.toList());

            portal_cache.put(type, pList);
        }

        return pList;
    }

    /**
     * 资讯卡片
     * 1. 接口格式为 formData, 宜搭服务注册一致
     * 2. 工作台页面不支持配置参数, 需要通过接口区分
     */
    @PostMapping("portal/cw")
    List<Map> portal(HttpServletRequest request) {

        Map data = UtilServlet.getParamMap(request);
        log.info("工作台数据, {}", data);
        return _portalList("财务专区");
    }


    @GetMapping("test")
    McR test() {

        ydClient.operateData(YDParam.builder()
                .formInstanceId("cc8b3153-3950-4fa5-b089-b28d1025ea7e")
                .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("departmentSelectField_lys0k6qb", Arrays.asList("155254332"))))
                .useLatestVersion(true)
                .build(), YDConf.FORM_OPERATION.update);

        return McR.success();
    }
}
