package com.yunfeiyun.agmp.pts.controller;

import com.alibaba.fastjson2.JSON;
import com.google.gson.Gson;
import com.yunfeiyun.agmp.common.annotation.Log;
import com.yunfeiyun.agmp.common.constant.Constants;
import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.constant.ResConstants;
import com.yunfeiyun.agmp.common.core.controller.BaseController;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.core.domain.model.AbstractTheme;
import com.yunfeiyun.agmp.common.core.domain.model.IBaseTheme;
import com.yunfeiyun.agmp.common.core.domain.model.PortalTheme;
import com.yunfeiyun.agmp.common.enums.BusinessType;
import com.yunfeiyun.agmp.common.exception.BizException;
import com.yunfeiyun.agmp.common.framework.manager.ResManager;
import com.yunfeiyun.agmp.common.framework.web.domain.UploadParam;
import com.yunfeiyun.agmp.common.utils.ConfigUtils;
import com.yunfeiyun.agmp.common.utils.DateUtils;
import com.yunfeiyun.agmp.common.web.system.domain.SysConfig;
import com.yunfeiyun.agmp.common.web.system.domain.SysRes;
import com.yunfeiyun.agmp.common.web.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 主题Controller
 * 
 * @author 杨晓辉
 * @date 2023-05-23
 */
@RestController
@RequestMapping("/system/theme")
public class PtsThemeController extends BaseController
{
    protected static Logger log = LoggerFactory.getLogger(PtsThemeController.class);

    @Autowired
    private ISysConfigService configService;

    @Autowired
    ResManager resManager;
    /**
     * 获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:theme:query')")
    @GetMapping(value = "/info")
    public AjaxResult getInfo()
    {
        SysConfig sysConfig = configService.selectConfigByKey(ConfigUtils.ConfigKeyEnum.PORTAL_THEME.getKey(),1);
        if(null != sysConfig && null != sysConfig.getConfigValue() && !"".equalsIgnoreCase(sysConfig.getConfigValue())){
            IBaseTheme portalTheme = new Gson().fromJson(sysConfig.getConfigValue(), PortalTheme.class);
            return success(portalTheme);
        }else{
            IBaseTheme portalTheme = new PortalTheme();
            portalTheme.setThemeId( null != sysConfig ? sysConfig.getConfigId(): null );
            portalTheme.setThemeName(Constants.PLATFORM_APP_THEME_V1);
            portalTheme.setCopyright(ConfigUtils.ConfigKeyEnum.PORTAL_THEME.getKey());
            portalTheme.setSystemName(Constants.PLATFORM_APP_SYSTEM_NAME);
            return success(portalTheme);
        }
    }

    /**
     * 增加
     */
    @PreAuthorize("@ss.hasPermi('system:theme:add')")
    @Log(title = "主题", businessType = BusinessType.UPDATE)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody AbstractTheme baseTheme)
    {
        SysConfig sysConfig = new SysConfig();
        sysConfig.setConfigId(sysConfig.getId());
        sysConfig.setConfigKey(ConfigUtils.ConfigKeyEnum.PORTAL_THEME.getKey());
        sysConfig.setConfigName(ConfigUtils.ConfigKeyEnum.PORTAL_THEME.getLabel());
        sysConfig.setConfigType("N");
        sysConfig.setConfigCreator(getUserId());
        sysConfig.setConfigCreateddate(DateUtils.dateTimeNow());
        baseTheme.setThemeId( baseTheme.getId() );
        sysConfig.setConfigValue(JSON.toJSONString(PortalTheme.build(baseTheme)));
        sysConfig.setConfigRemark(ConfigUtils.ConfigKeyEnum.PORTAL_THEME.getLabel());
        if (!configService.checkConfigKeyUnique(sysConfig))
        {
            throw new BizException(ErrorCode.ADD_CONF_NAME_ERROR.getCode(),ErrorCode.ADD_CONF_NAME_ERROR.getMessage());
        }
        sysConfig.setConfigCreator(getUserId());
        int n = configService.insertConfig(sysConfig);
//        //更新资源
//        if(portalTheme.getUploadRes() !=null && portalTheme.getUploadRes().size() >0){
//            UploadRes uploadRes = portalTheme.getUploadRes().get(0);
//            if("1".equals(uploadRes.getMode()) &&  !"-1".equals(uploadRes.getBusId())){
//                resManager.updateRes(uploadRes.getResId(),uploadRes.getBusId());
//            }
//        }
        return toAjax(n);
    }


    /**
     * 修改
     */
    @PreAuthorize("@ss.hasPermi('system:theme:edit')")
    @Log(title = "主题", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody AbstractTheme baseTheme)
    {
        SysConfig sysConfig = new SysConfig();
        sysConfig.setConfigId(baseTheme.getThemeId());
        sysConfig.setConfigKey(ConfigUtils.ConfigKeyEnum.PORTAL_THEME.getKey());
        sysConfig.setConfigName(ConfigUtils.ConfigKeyEnum.PORTAL_THEME.getLabel());
        sysConfig.setConfigType("N");
        sysConfig.setConfigModifier(getUserId());
        sysConfig.setConfigModifieddate(DateUtils.dateTimeNow());
        sysConfig.setConfigRemark(ConfigUtils.ConfigKeyEnum.PORTAL_THEME.getLabel());
        PortalTheme portalTheme = PortalTheme.build(baseTheme);
        List<SysRes> resList = resManager.queryRes(baseTheme.getThemeId() ,  ResConstants.BizType.SYSTHEME.getKey());
        SysRes linkIcon = resList !=null && resList.size() > 0 ? resList.get(0): new SysRes();
        portalTheme.setLogoUrl(linkIcon.getResUrl() );
        sysConfig.setConfigValue(JSON.toJSONString(portalTheme));
        int n = configService.updateConfig(sysConfig);
        return toAjax(n);
    }

    /**
     * 首页图片上传
     */
    @Log(title = "首页图片上传", businessType = BusinessType.UPDATE)
    @PostMapping("/preview/upload")
    public AjaxResult uploadThemePreview(MultipartFile file, HttpServletRequest request) throws Exception
    {
        if (!file.isEmpty())
        {
//            String UploadParam = request.getParameter("UploadParam");
//            com.yunfeiyun.agmp.common.framework.web.domain.UploadParam uploadParam = new Gson().fromJson(UploadParam, UploadParam.class);
//            ResConstants.mediaType mediaType = uploadParam.getResMediatype() != null ? ResConstants.mediaType.getKey(uploadParam.getResMediatype()) : ResConstants.mediaType.VIDEO;
//            String resBusId = uploadParam.getResBusId() == null || !SysRes.valid(uploadParam.getResBusId()) ? "-1" : uploadParam.getResBusId();
            UploadParam uploadParam = UploadParam.parse(request);
            if(uploadParam == null) return error(ErrorCode.UPLOAD_FAIL.getCode());
            SysRes sysRes  = resManager.uploadRes( ResConstants.BizType.SYSTHEME, ResConstants.mediaType.IMG, uploadParam.getResBusId(), file,getLoginUser());
            AjaxResult ajax = AjaxResult.success();
            ajax.put("data" ,sysRes );
            return ajax;
        }
        return error(ErrorCode.UPLOAD_FAIL.getCode());
    }

}
