package com.gxwebsoft.cms.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.cms.entity.CmsNavigation;
import com.gxwebsoft.cms.entity.CmsWebsiteField;
import com.gxwebsoft.cms.param.CmsNavigationParam;
import com.gxwebsoft.cms.service.CmsNavigationService;
import com.gxwebsoft.cms.service.CmsWebsiteFieldService;
import com.gxwebsoft.common.core.security.JwtUtil;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.cms.service.CmsWebsiteService;
import com.gxwebsoft.cms.entity.CmsWebsite;
import com.gxwebsoft.cms.param.CmsWebsiteParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.Company;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.CompanyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 网站信息记录表控制器
 *
 * @author 科技小王子
 * @since 2024-09-10 20:36:14
 */
@Api(tags = "网站信息记录表管理")
@RestController
@RequestMapping("/api/cms/cms-website")
public class CmsWebsiteController extends BaseController {
    @Resource
    private CmsWebsiteService cmsWebsiteService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private CmsWebsiteFieldService cmsWebsiteFieldService;
    @Resource
    private CmsNavigationService cmsNavigationService;
    @Resource
    private CompanyService companyService;

    @ApiOperation("分页查询网站信息记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<CmsWebsite>> page(CmsWebsiteParam param) {
        // 使用关联查询
        return success(cmsWebsiteService.pageRel(param));
    }

    @ApiOperation("查询全部网站信息记录表")
    @GetMapping()
    public ApiResult<List<CmsWebsite>> list(CmsWebsiteParam param) {
        PageParam<CmsWebsite, CmsWebsiteParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        return success(cmsWebsiteService.list(page.getOrderWrapper()));
        // 使用关联查询
        //return success(cmsWebsiteService.listRel(param));
    }

    @PreAuthorize("hasAuthority('cms:website:list')")
    @OperationLog
    @ApiOperation("根据id查询网站信息记录表")
    @GetMapping("/{id}")
    public ApiResult<CmsWebsite> get(@PathVariable("id") Integer id) {
        return success(cmsWebsiteService.getById(id));
        // 使用关联查询
        //return success(cmsWebsiteService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('cms:website:save')")
    @ApiOperation("添加网站信息记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody CmsWebsite cmsWebsite) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          cmsWebsite.setUserId(loginUser.getUserId());
        }
        if (cmsWebsiteService.save(cmsWebsite)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('cms:website:update')")
    @ApiOperation("修改网站信息记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody CmsWebsite cmsWebsite) {
        if (cmsWebsiteService.updateById(cmsWebsite)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('cms:website:remove')")
    @ApiOperation("删除网站信息记录表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (cmsWebsiteService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('cms:website:save')")
    @ApiOperation("批量添加网站信息记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<CmsWebsite> list) {
        if (cmsWebsiteService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('cms:website:update')")
    @ApiOperation("批量修改网站信息记录表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<CmsWebsite> batchParam) {
        if (batchParam.update(cmsWebsiteService, "website_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('cms:website:remove')")
    @ApiOperation("批量删除网站信息记录表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (cmsWebsiteService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

  @ApiOperation("网站基本信息")
  @GetMapping("/getSiteInfo")
  public ApiResult<CmsWebsite> getSiteInfo(HttpServletRequest request) {
    String key = "RootSiteInfo:".concat(getTenantId().toString());
    final String siteInfo = redisUtil.get(key);
    String access_token = JwtUtil.getAccessToken(request);

    // 从缓存读取信息
    if(StrUtil.isNotBlank(siteInfo)){
//      return success(JSONObject.parseObject(siteInfo,CmsWebsite.class));
    }
    // 判断是否存在
    if (cmsWebsiteService.count() == 0) {
      final Integer tenantId = getTenantId();
      final CmsWebsite cmsWebsite = new CmsWebsite();
      cmsWebsite.setTenantId(tenantId);
      final Company company = companyService.getOne(new LambdaQueryWrapper<Company>().last("limit 1"));
      if (ObjectUtil.isNotEmpty(company)) {
        cmsWebsite.setDomain(company.getDomain());
        cmsWebsite.setWebsiteName(company.getShortName());
        cmsWebsite.setWebsiteCode(company.getCompanyCode());
        cmsWebsite.setWebsiteIcon("/favicon.ico");
      }
//      System.out.println("cmsWebsite = " + cmsWebsite);
      final boolean save = cmsWebsiteService.save(cmsWebsite);
//      System.out.println("save = " + save);
      return fail("站点不存在",null);
    }

    // 获取站点信息
    final CmsWebsite website = cmsWebsiteService.getOne(new LambdaQueryWrapper<CmsWebsite>().eq(CmsWebsite::getDeleted, 0).last("limit 1"));
    System.out.println("website = " + website);

    // 站点配置参数
    HashMap<String, Object> config = new HashMap<>();
    final List<CmsWebsiteField> fields = cmsWebsiteFieldService.list(new LambdaQueryWrapper<CmsWebsiteField>().eq(CmsWebsiteField::getDeleted,0));
    fields.forEach(d -> {
      config.put(d.getName(), d.getValue());
    });
    config.put("Domain", redisUtil.get("Domain:"));
    config.put("SubDomain", redisUtil.get("Domain:".concat(website.getWebsiteCode()).concat("wsdns.cn")));
    website.setConfig(config);

    // 网站导航
    final CmsNavigationParam navigationParam = new CmsNavigationParam();
    navigationParam.setHide(0);
    navigationParam.setTop(0);
    navigationParam.setBottom(null);
    final List<CmsNavigation> topNavs = cmsNavigationService.listRel(navigationParam);
    // 顶部菜单
    website.setTopNavs(CommonUtil.toTreeData(topNavs, 0, CmsNavigation::getParentId, CmsNavigation::getNavigationId, CmsNavigation::setChildren));
    navigationParam.setTop(null);
    navigationParam.setBottom(0);
    final List<CmsNavigation> bottomNavs = cmsNavigationService.listRel(navigationParam);
    // 底部菜单
    website.setBottomNavs(CommonUtil.toTreeData(bottomNavs, 0, CmsNavigation::getParentId, CmsNavigation::getNavigationId, CmsNavigation::setChildren));

    // 当前登录用户
    if(access_token != null){
      final User loginUser = getLoginUser();
      website.setLoginUser(loginUser);
    }

    // 服务器时间
    HashMap<String, Object> serverTime = new HashMap<>();
    // 今天日期
    DateTime date = DateUtil.date();
    String today= DateUtil.today();
    // 明天日期
    final DateTime dateTime = DateUtil.tomorrow();
    String tomorrow = DateUtil.format(dateTime, "yyyy-MM-dd");
    // 后天日期
    final DateTime dateTime2 = DateUtil.offsetDay(date, 2);
    final String afterDay = DateUtil.format(dateTime2, "yyyy-MM-dd");
    // 今天星期几
    final int week = DateUtil.thisDayOfWeek();
    final DateTime nextWeek = DateUtil.nextWeek();
    serverTime.put("now",DateUtil.now());
    serverTime.put("today",today);
    serverTime.put("tomorrow",tomorrow);
    serverTime.put("afterDay",afterDay);
    serverTime.put("week",week);
    serverTime.put("nextWeek",nextWeek);
    website.setServerTime(serverTime);
    System.out.println("website = " + website);
    redisUtil.set(key,website,1L, TimeUnit.DAYS);

    return success(website);
  }

  @PreAuthorize("hasAuthority('cms:website:remove')")
  @ApiOperation("清除缓存")
  @DeleteMapping("/clearSiteInfo/{key}")
  public ApiResult<?> clearSiteInfo(@PathVariable("key") String key) {
    final String siteInfo = redisUtil.get(key);
      // 清除指定key
      redisUtil.delete(key);
      // 清除小程序缓存
      redisUtil.delete("MpInfo:".concat(getTenantId().toString()));
      // 清除网站缓存
      redisUtil.delete("RootSiteInfo:".concat(getTenantId().toString()));
      // 清除存储空间
      redisUtil.delete("StorageIsFull:".concat(getTenantId().toString()));
      // 选择支付方式
      redisUtil.delete("SelectPayment:".concat(getTenantId().toString()));
      return success("清除成功");
  }
}
