package com.gxwebsoft.cms.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
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.*;
import com.gxwebsoft.cms.param.*;
import com.gxwebsoft.cms.service.*;
import com.gxwebsoft.common.core.exception.BusinessException;
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.*;
import com.gxwebsoft.common.system.entity.Dict;
import com.gxwebsoft.common.system.entity.DictData;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.DictDataService;
import com.gxwebsoft.common.system.service.DictService;
import com.gxwebsoft.oa.entity.Company;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.gxwebsoft.common.core.constants.WebsiteConstants.*;

/**
 * 网站信息记录表控制器
 *
 * @author 科技小王子
 * @since 2024-03-04 21:14:15
 */
@Api(tags = "网站")
@RestController
@RequestMapping("/api/cms/website")
public class WebsiteController extends BaseController {
    @Resource
    private WebsiteService websiteService;
    @Resource
    private WebsiteFieldService websiteFieldService;
    @Resource
    private DesignService designService;
    @Resource
    private NavigationService navigationService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private OrderService orderService;
    @Resource
    private DictService dictService;
    @Resource
    private DictDataService dictDataService;
    @Resource
    private DomainService domainService;

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

    @ApiOperation("查询全部网站信息记录表")
    @GetMapping()
    public ApiResult<List<Website>> list(WebsiteParam param) {
        // 使用关联查询
        return success(websiteService.listRel(param));
    }

    @ApiOperation("根据id查询网站信息记录表")
    @GetMapping("/{id}")
    public ApiResult<Website> get(@PathVariable("id") Integer id) {
      // 使用关联查询
      final Website website = websiteService.getByIdRel(id);
      // 附加状态说明
      website.setStatusName(WEBSITE_STATUS_NAME[website.getStatus()]);
      website.setStatusIcon(WEBSITE_STATUS_ICON[website.getStatus()]);
      website.setStatusUrl(WEBSITE_STATUS_URL[website.getStatus()]);
      website.setStatusBtnText(WEBSITE_STATUS_BTN_TEXT[website.getStatus()]);
      if (!website.getStatus().equals(2)) {
        website.setStatusText(WEBSITE_STATUS_TEXT[website.getStatus()]);
      }
      return success(website);
    }

    @PreAuthorize("hasAuthority('cms:website:save')")
    @ApiOperation("添加网站信息记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Website website) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          website.setUserId(loginUser.getUserId());
        }
        if (websiteService.save(website)) {
            // 绑定免费二级域名
            domainService.saveAsync(website);
            return success("添加成功");
        }
        return fail("添加失败");
    }


    @PreAuthorize("hasAuthority('cms:website:update')")
    @ApiOperation("修改网站信息记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Website website) {
        if (websiteService.updateById(website)) {
            // 绑定免费二级域名
            website.setTenantId(getLoginUser().getTenantId());
            domainService.saveAsync(website);
            return success("修改成功");
        }
        return fail("修改失败");
    }

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

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

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

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

  @ApiOperation("检查域名是否存在")
  @GetMapping("/existence")
  public ApiResult<?> existence(ExistenceParam<Website> param) {
    if (param.isExistence(websiteService, Website::getWebsiteCode)) {
      return success(param.getValue() + "已存在");
    }
    return fail(param.getValue() + "不存在");
  }

  @ApiOperation("网站基本信息")
  @GetMapping("/getSiteInfo")
  public ApiResult<Website> getSiteInfo(HttpServletRequest request) {
    String key = "SiteInfo:".concat(getTenantId().toString());
    final String siteInfo = redisUtil.get(key);
    String access_token = JwtUtil.getAccessToken(request);
    // 从缓存读取信息
    if(StrUtil.isNotBlank(siteInfo)){
      return success(JSONObject.parseObject(siteInfo,Website.class));
    }

    // 判断是否存在
    if (websiteService.count() == 0) {
      return fail("站点不存在",null);
    }

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

    // 站点配置参数
    HashMap<String, Object> config = new HashMap<>();
    final List<WebsiteField> fields = websiteFieldService.list();
    fields.forEach(d -> {
      config.put(d.getName(), d.getValue());
    });
    config.put("Domain", website.getDomain());
    config.put("SubDomain", website.getWebsiteCode().concat(".wsdns.cn"));
    website.setConfig(config);

    // 网站导航
    final NavigationParam navigationParam = new NavigationParam();
    navigationParam.setHide(0);
    navigationParam.setTop(0);
    navigationParam.setBottom(null);
    final List<Navigation> topNavs = navigationService.listRel(navigationParam);
    // 顶部菜单
    website.setTopNavs(CommonUtil.toTreeData(topNavs, 0, Navigation::getParentId, Navigation::getNavigationId, Navigation::setChildren));
    navigationParam.setTop(null);
    navigationParam.setBottom(0);
    final List<Navigation> bottomNavs = navigationService.listRel(navigationParam);
    // 底部菜单
    website.setBottomNavs(CommonUtil.toTreeData(bottomNavs, 0, Navigation::getParentId, Navigation::getNavigationId, Navigation::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);
    redisUtil.set(key,website,1L, TimeUnit.DAYS);

    return success(website);
  }

  private void createWebsite(String access_token) {
    final Integer tenantId = getTenantId();
    // 请求主服务器获取租户信息
    String result = HttpRequest.get("https://server.gxwebsoft.com/api/auth/tenant")
      .header("Authorization", access_token)
      .header("Tenantid", tenantId.toString())
      .timeout(20000)//超时，毫秒
      .execute().body();

    JSONObject jsonObject = JSONObject.parseObject(result);
    final String data = jsonObject.getString("data");
    final Company company = JSONObject.parseObject(data, Company.class);
    if(company == null){
      throw new BusinessException("站点不存在");
    }
    // 创建网站记录
    final Website website = new Website();
    website.setTenantId(company.getTenantId());
    website.setWebsiteName(company.getShortName());
    website.setWebsiteLogo(company.getCompanyLogo());
    website.setWebsiteIcon("/favicon.ico");
    website.setWebsiteType("企业官网");
    website.setDomain(company.getDomain());
    website.setExpirationTime(company.getExpirationTime());
    website.setIndustryParent(company.getIndustryParent());
    website.setIndustryChild(company.getIndustryChild());
    website.setCompanyId(company.getCompanyId());
    website.setAddress(company.getAddress());
    website.setComments(company.getComments());
    website.setKeywords(company.getCompanyName());
    website.setUserId(company.getUserId());
    websiteService.save(website);

    // 创建默认页面及导航
    final Navigation navigation = new Navigation();
    final Design design = new Design();
    // 1.首页
    design.setName("首页");
    design.setHome(1);
    design.setPath("/");
    design.setComponent("/pages/index");
    design.setSortNumber(0);
    designService.save(design);
    navigation.setTitle(design.getName());
    navigation.setPath(design.getPath());
    navigation.setComponent(design.getComponent());
    navigation.setHome(design.getHome());
    navigation.setPageId(design.getPageId());
    navigation.setSortNumber(0);
    navigation.setType(1);
    navigation.setPosition(1);
    navigationService.save(navigation);
//    // 2.关于我们
//    design.setName("关于我们");
//    design.setPath("/about");
//    design.setComponent("/about/index");
//    design.setSortNumber(1);
//    designService.save(design);
//    navigation.setTitle(design.getName());
//    navigation.setPath(design.getPath());
//    navigation.setComponent(design.getComponent());
//    navigation.setPageId(design.getPageId());
//    navigation.setSortNumber(1);
//    navigation.setType(1);
//    navigationService.save(navigation);
//    // 3.产品展示
//    final ArticleCategory articleCategory = new ArticleCategory();
//    articleCategory.setTitle("产品展示");
//    articleCategory.setPath("/product/" + articleCategory.getCategoryId());
//    articleCategory.setComponent("/article/photo");
//    articleCategory.setSortNumber(2);
//    articleCategoryService.save(articleCategory);
//    navigation.setTitle(articleCategory.getTitle());
//    navigation.setPath(articleCategory.getPath());
//    navigation.setComponent(articleCategory.getComponent());
//    navigation.setArticleCategoryId(articleCategory.getCategoryId());
//    navigation.setSortNumber(2);
//    navigation.setType(2);
//    navigationService.save(navigation);
//    // 4.新闻资讯
//    articleCategory.setTitle("新闻资讯");
//    articleCategoryService.save(articleCategory);
//    navigation.setTitle(articleCategory.getTitle());
//    navigation.setPath("/article/" + articleCategory.getCategoryId());
//    navigation.setComponent("/article/index");
//    navigation.setArticleCategoryId(articleCategory.getCategoryId());
//    navigation.setSortNumber(3);
//    navigation.setType(2);
//    navigation.setPosition(1);
//    navigationService.save(navigation);
//    // 5.表单页面
//    final Form form = new Form();
//    form.setName("业务咨询");
//    form.setLayout("[{\"id\":\"vhEB\",\"type\":\"text\",\"name\":\"姓名\",\"checked\":true},{\"id\":\"Hg7v\",\"type\":\"phone\",\"name\":\"手机号码\",\"checked\":true},{\"id\":\"byBy\",\"type\":\"textarea\",\"name\":\"需求描述\",\"checked\":false}]");
//    form.setComments("简单描述您的需求，我们会尽快联系您");
//    formService.save(form);
//    navigation.setTitle(form.getName());
//    navigation.setPath("/form/" + form.getFormId());
//    navigation.setComponent("/form/index");
//    navigation.setFormId(form.getFormId());
//    navigation.setSortNumber(4);
//    navigation.setType(4);
//    navigation.setPosition(1);
//    navigationService.save(navigation);
//    // 6.联系我们
//    design.setName("联系我们");
//    design.setPath("/contact");
//    design.setComponent("/about/index");
//    design.setSortNumber(5);
//    designService.save(design);
//    navigation.setTitle(design.getName());
//    navigation.setPath(design.getPath());
//    navigation.setComponent(design.getComponent());
//    navigation.setPageId(design.getPageId());
//    navigation.setSortNumber(5);
//    navigation.setType(1);
//    navigation.setPosition(1);
//    navigationService.save(navigation);
    // 添加字典
    final Dict dict = new Dict();
    dict.setDictName("路由方式");
    dict.setDictCode("navType");
    dict.setSortNumber(100);
    final boolean save = dictService.save(dict);
    final Integer dictId = dict.getDictId();
    final DictData dictData = new DictData();
    dictData.setDictDataName("uni.navigateTo");
    dictData.setDictDataCode("uni.navigateTo");
    dictData.setComments("保留当前页面，跳转到应用内的某个页面，使用uni.navigateBack可以返回到原页面");
    dictDataService.save(dictData);
    dictData.setDictDataName("uni.redirectTo");
    dictData.setDictDataCode("uni.redirectTo");
    dictData.setComments("关闭当前页面，跳转到应用内的某个页面");
    dictDataService.save(dictData);
    dictData.setDictDataName("uni.reLaunch");
    dictData.setDictDataCode("uni.reLaunch");
    dictData.setComments("关闭所有页面，打开到应用内的某个页面");
    dictDataService.save(dictData);
    dictData.setDictDataName("uni.switchTab");
    dictData.setDictDataCode("uni.switchTab");
    dictData.setComments("跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面");
    dictDataService.save(dictData);
    // 网站配置参数
    List<WebsiteField> fields = new ArrayList<>();
    WebsiteField field = new WebsiteField();
    field.setType(0);
    field.setName("siteLogo");
    field.setValue(company.getCompanyLogo());
    field.setComments("网站LOGO");
    websiteFieldService.save(field);
    field.setName("siteName");
    field.setValue(company.getShortName());
    field.setComments("网站名称");
    websiteFieldService.save(field);
    field.setName("icpNo");
    field.setValue("-");
    field.setComments("备案号");
    websiteFieldService.save(field);
    field.setName("qrcode");
    field.setValue("");
    field.setComments("公众号二维码");
    websiteFieldService.save(field);
    field.setName("bottomBg");
    field.setValue("https://oss.wsdns.cn/20240717/13165035c35e4f25a6c9fbd3636c6292.png");
    field.setComments("网站底部背景图");
    websiteFieldService.save(field);
    field.setName("address");
    field.setValue(company.getAddress());
    field.setComments("办公地址");
    websiteFieldService.save(field);
    field.setName("tel");
    field.setValue(company.getTel());
    field.setComments("公司电话");
    websiteFieldService.save(field);
    field.setName("domain");
    field.setValue(company.getDomain());
    field.setComments("网站域名");
    websiteFieldService.save(field);
  }

  @ApiOperation("获取服务器时间")
  @GetMapping("/getServerTime")
  public ApiResult<?> getServerTime(){
    // 服务器时间
    final ServerTimeVO vo = new ServerTimeVO();
    final int hour = DateUtil.hour(DateUtil.date(), true);
    final int minute = DateUtil.minute(DateUtil.date());
    vo.setDate(DateUtil.date());
    vo.setToday(DateUtil.today());
    vo.setHour(hour);
    vo.setMinute(minute);
    vo.setHourMinute(String.format("%02d", hour).concat(String.format("%02d", minute)));
    final int compare = Integer.compare(Integer.valueOf(vo.getHourMinute()), 900);
    vo.setIsAfter(compare);

    final User loginUser = getLoginUser();
    if (loginUser != null) {
      if (orderService.count(new LambdaQueryWrapper<Order>().eq(Order::getPayStatus,0)) > 0) {
        vo.setHasNoPayOrder(true);
      }
    }
    return success(vo);
  }

  @ApiOperation("获取未来一周的日期")
  @GetMapping("/getNext7day")
  public ApiResult<?> getNext7day(){
    List<Next7dayVO> dateList = new ArrayList<>();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd");
    for (int i = 0; i < 7; i++) {
      Date date = DateUtils.addDays(new Date(), +i);
      String formatDate = sdf.format(date);
      String dateTime = sdf2.format(date);
      final Next7dayVO vo = new Next7dayVO();
      vo.setDate(dateTime);
      vo.setDateTime(formatDate);
      final DateTime parse = DateUtil.parse(formatDate);
      int dayOfWeek = DateUtil.dayOfWeek(parse);
      vo.setWeek(dayOfWeek - 1);
      dateList.add(vo);
    }

    return success(dateList);
  }

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

}
