package com.zhiqiyun.open.mvc.manager.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhiqiyun.open.annotation.Permission;
import com.zhiqiyun.open.core.models.settings.SystemConfig;
import com.zhiqiyun.open.core.models.settings.SystemConfigItem;
import com.zhiqiyun.open.core.service.SystemConfigService;
import com.zhiqiyun.open.mvc.Result;
import com.zhiqiyun.open.mvc.manager.params.QuerySystemConfigParam;
import com.zhiqiyun.open.mvc.manager.params.SaveSystemConfigParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/setting/systemConfig")
public class SystemConfigController {

    @Autowired
    private SystemConfigService systemConfigService;

    @Permission(value = "system.config.find", tags = "系统参数查询")
    @PostMapping("/findPage")
    public Result findSettingPage(@RequestBody QuerySystemConfigParam params) {
        QueryWrapper<SystemConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("config_key", params.getConfigKey());
        Page<SystemConfig> resultData = this.systemConfigService.page(params.getPage());
        for (SystemConfig config : resultData.getRecords()) {
            List<SystemConfigItem> items = this.systemConfigService.findAllItems(config.getConfigKey());
            config.setItems(items);
        }
        return Result.instance(Result.Code.SUCCESS).setData(resultData);
    }


    @PostMapping("/updateById")
    @Permission(value = "system.config.edit", tags = "修改系统参数")
    public Result updateSettingById(String id, @Valid @RequestBody SaveSystemConfigParam param) throws Exception {
        if (StringUtils.isBlank(id)) {
            return Result.instance("数据异常，请刷新页面后再试");
        }
        SystemConfig config = new SystemConfig();
        config.setId(id);
        config.setName(param.getName());
        config.setRemark(param.getRemark());
        List<SystemConfigItem> listData = new ArrayList<>();
        for (SaveSystemConfigParam.SaveSystemConfigItemParam itemParam : param.getItems()) {
            SystemConfigItem configItem = new SystemConfigItem();
            configItem.setId(itemParam.getId());
            configItem.setItemValue(itemParam.getItemValue());
            listData.add(configItem);
        }
        this.systemConfigService.updateConfig(config, listData);
        return Result.instance(Result.Code.MESSAGE_SUCCESS);
    }
}
