package com.yunzhupaas.base.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import com.yunzhupaas.base.controller.SuperController;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.entity.EmailConfigEntity;
import com.yunzhupaas.base.entity.SysConfigEntity;
import com.yunzhupaas.base.model.systemconfig.EmailTestForm;
import com.yunzhupaas.base.model.systemconfig.SysConfigModel;
import com.yunzhupaas.base.service.SysconfigService;
import com.yunzhupaas.base.service.SystemConfigApi;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.exception.WorkFlowException;
import com.yunzhupaas.message.entity.QyWebChatModel;
import com.yunzhupaas.message.model.message.DingTalkModel;
import com.yunzhupaas.message.util.QyWebChatUtil;
import com.yunzhupaas.permission.model.user.form.UserUpAdminForm;
import com.yunzhupaas.permission.model.user.vo.UserAdminVO;
import com.yunzhupaas.permission.service.UserService;
import com.yunzhupaas.util.JsonUtil;
import com.yunzhupaas.util.RandomUtil;
import com.yunzhupaas.util.third.DingTalkUtil;
import com.yunzhupaas.util.wxutil.HttpUtil;
import com.yunzhupaas.workflow.service.TaskApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.*;

/**
 * 系统配置
 *
 * @author 云筑产品开发平台组
 * @version V3.1.0
 * @copyright 深圳市乐程软件有限公司
 * @date 2023/09/27
 */
@Tag(name = "系统配置", description = "SysConfig")
@RestController
@RequestMapping("/api/system/SysConfig")
public class SysConfigController extends SuperController<SysconfigService, SysConfigEntity> implements SystemConfigApi {

    @Autowired
    private SysconfigService sysconfigService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskApi taskApi;

    /**
     * 列表
     *
     * @return ignore
     */
    @Operation(summary = "列表")
    @GetMapping
    @SaCheckPermission("system.sysConfig")
    public ActionResult<SysConfigModel> list() {
        List<SysConfigEntity> list = sysconfigService.getList("SysConfig");
        HashMap<String, String> map = new HashMap<>(16);
        for (SysConfigEntity sys : list) {
            map.put(sys.getFkey(), sys.getValue());
        }
        SysConfigModel sysConfigModel = JsonUtil.getJsonToBean(map, SysConfigModel.class);
        return ActionResult.success(sysConfigModel);
    }

    /**
     * 保存设置
     *
     * @param sysConfigModel 系统配置模型
     * @return ignore
     */
    @Operation(summary = "更新系统配置")
    @Parameter(name = "sysConfigModel", description = "系统模型", required = true)
    @SaCheckPermission("system.sysConfig")
    @PutMapping
    public ActionResult save(@RequestBody SysConfigModel sysConfigModel) {
        if (Objects.nonNull(sysConfigModel.getVerificationCodeNumber())) {
            if (sysConfigModel.getVerificationCodeNumber() > 6) {
                return ActionResult.fail(MsgCode.SYS029.get());
            }
            if (sysConfigModel.getVerificationCodeNumber() < 3) {
                return ActionResult.fail(MsgCode.SYS030.get());
            }
        }
        String flowTodo = sysconfigService.getValueByKey("flowTodo");
        if (ObjectUtil.equals(flowTodo, "1") && ObjectUtil.equals(sysConfigModel.getFlowTodo(), 0)) {
            if (taskApi.checkTodo()) {
                return ActionResult.fail(MsgCode.WF141.get());
            }
        }
        String flowSign = sysconfigService.getValueByKey("flowSign");
        if (ObjectUtil.equals(flowSign, "1") && ObjectUtil.equals(sysConfigModel.getFlowSign(), 0)) {
            if (taskApi.checkSign()) {
                return ActionResult.fail(MsgCode.WF138.get());
            }
        }
        if (sysConfigModel.getAddSignLevel() > 6 || sysConfigModel.getAddSignLevel() < 1) {
            return ActionResult.fail("加签层级的范围不在1-6之间");
        }
        List<SysConfigEntity> entitys = new ArrayList<>();
        Map<String, Object> map = JsonUtil.entityToMap(sysConfigModel);
        map.put("isLog", "1");
        map.put("sysTheme", "1");
        map.put("pageSize", "30");
        map.put("lastLoginTime", 1);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            SysConfigEntity entity = new SysConfigEntity();
            entity.setId(RandomUtil.uuId());
            entity.setFkey(entry.getKey());
            entity.setValue(String.valueOf(entry.getValue()));
            entitys.add(entity);
        }
        sysconfigService.save(entitys);
        return ActionResult.success(MsgCode.SU005.get());
    }

    /**
     * 邮箱账户密码验证
     *
     * @param emailTestForm 邮箱测试模型
     * @return ignore
     */
    @Operation(summary = "邮箱连接测试")
    @Parameter(name = "emailTestForm", description = "邮箱测试模型", required = true)
    @SaCheckPermission("system.sysConfig")
    @PostMapping("/Email/Test")
    public ActionResult checkLogin(@RequestBody EmailTestForm emailTestForm) {
        EmailConfigEntity entity = JsonUtil.getJsonToBean(emailTestForm, EmailConfigEntity.class);
        entity.setEmailSsl(Integer.valueOf(emailTestForm.getSsl()));
        String result = sysconfigService.checkLogin(entity);
        if ("true".equals(result)) {
            return ActionResult.success(MsgCode.SU017.get());
        } else {
            return ActionResult.fail(result);
        }
    }


    //=====================================测试企业微信、钉钉的连接=====================================

    /**
     * 测试企业微信配置的连接功能
     *
     * @param type           0-发送消息,1-同步组织
     * @param qyWebChatModel 企业微信模型
     * @return ignore
     */
    @Operation(summary = "测试企业微信配置的连接")
    @Parameters({
            @Parameter(name = "type", description = "0-发送消息,1-同步组织", required = true),
            @Parameter(name = "qyWebChatModel", description = "企业微信模型", required = true)
    })
    @SaCheckPermission("system.sysConfig")
    @PostMapping("{type}/testQyWebChatConnect")
    public ActionResult testQyWebChatConnect(@PathVariable("type") String type, @RequestBody @Valid QyWebChatModel qyWebChatModel) {
        JSONObject retMsg = new JSONObject();
        // 测试发送消息、组织同步的连接
        String corpId = qyWebChatModel.getQyhCorpId();
        String agentSecret = qyWebChatModel.getQyhAgentSecret();
        String corpSecret = qyWebChatModel.getQyhCorpSecret();
        // 测试发送消息的连接
        if ("0".equals(type)) {
            retMsg = QyWebChatUtil.getAccessToken(corpId, agentSecret);
            if (HttpUtil.isWxError(retMsg)) {
                return ActionResult.fail(MsgCode.SYS031.get(retMsg.getString("errmsg")));
            }
            return ActionResult.success(MsgCode.SYS032.get());
        } else if ("1".equals(type)) {
            retMsg = QyWebChatUtil.getAccessToken(corpId, corpSecret);
            if (HttpUtil.isWxError(retMsg)) {
                return ActionResult.fail(MsgCode.SYS033.get(retMsg.getString("errmsg")));
            }
            return ActionResult.success(MsgCode.SYS034.get());
        }
        return ActionResult.fail(MsgCode.SYS035.get());
    }

    /**
     * 测试钉钉配置的连接功能
     *
     * @param dingTalkModel 钉钉模板
     * @return ignore
     */
    @Operation(summary = "测试钉钉配置的连接")
    @Parameters({
            @Parameter(name = "dingTalkModel", description = "钉钉模型", required = true)
    })
    @SaCheckPermission("system.sysConfig")
    @PostMapping("/testDingTalkConnect")
    public ActionResult testDingTalkConnect(@RequestBody @Valid DingTalkModel dingTalkModel) {
        JSONObject retMsg = new JSONObject();
        // 测试钉钉配置的连接
        String appKey = dingTalkModel.getDingSynAppKey();
        String appSecret = dingTalkModel.getDingSynAppSecret();
        ///
//        String agentId = dingTalkModel.getDingAgentId();
        // 测试钉钉的连接
        retMsg = DingTalkUtil.getAccessToken(appKey, appSecret);
        if (!retMsg.getBoolean("code")) {
            return ActionResult.fail(MsgCode.SYS036.get(retMsg.getString("error")));
        }

        return ActionResult.success(MsgCode.SYS037.get());
    }

    /**
     * 获取管理员集合
     *
     * @return
     */
    @Operation(summary = "获取管理员集合")
    @SaCheckPermission("system.sysConfig")
    @GetMapping("/getAdminList")
    public ActionResult<List<UserAdminVO>> getAdminList(){
        List<UserAdminVO> admins = JsonUtil.getJsonToList(userService.getAdminList(), UserAdminVO.class);
        return ActionResult.success(admins);
    }

    /**
     * 获取管理员集合
     *
     * @param userUpAdminForm 超级管理员设置表单参数
     * @return
     */
    @Operation(summary = "获取管理员集合")
    @Parameters({
            @Parameter(name = "userUpAdminForm", description = "超级管理员设置表单参数", required = true)
    })
    @SaCheckPermission("system.sysConfig")
    @PutMapping("/setAdminList")
    public ActionResult<String> setAdminList(@RequestBody UserUpAdminForm userUpAdminForm){
        userService.setAdminListByIds(userUpAdminForm.getAdminIds());
        return ActionResult.success(MsgCode.SU004.get());
    }

}

