package com.zbkj.service.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.zbkj.common.constants.SysConfigConstants;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.page.PageDiy;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.page.PageDiyEditNameRequest;
import com.zbkj.common.response.page.PageDiyResponse;
import com.zbkj.service.dao.page.PageDiyDao;
import com.zbkj.service.service.PageDiyService;
import com.zbkj.service.service.SystemAttachmentService;
import com.zbkj.service.service.SystemConfigService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author dazongzi
* @description PageDiyServiceImpl 接口实现
* @date 2023-05-16
*/
@Service
public class PageDiyServiceImpl extends ServiceImpl<PageDiyDao, PageDiy> implements PageDiyService {

    @Resource
    private PageDiyDao dao;

    @Autowired
    private SystemConfigService systemConfigService;


    /**
    * 列表
    * @author dazongzi
    * @since 2023-05-16
    * @return List<PageDiy>
    */
    @Override
    public List<PageDiy> getList(String name, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<PageDiy> lambdaQueryWrapper = Wrappers.lambdaQuery();
        // 列表查询时忽略掉value字段，以免影响查询速度
        lambdaQueryWrapper.select(PageDiy.class, i -> !i.getColumn().equals("value"));
        lambdaQueryWrapper.eq(PageDiy::getIsDefault, 0);
        if(ObjectUtil.isNotEmpty(name)){
            lambdaQueryWrapper.like(PageDiy::getName, URLUtil.decode(name));
        }
        lambdaQueryWrapper.orderByDesc(PageDiy::getAddTime);
        List<PageDiy> pageDiys = dao.selectList(lambdaQueryWrapper);
        if(pageParamRequest.getPage() == 1){
            pageDiys.add(0, getDiyPageHome());
        }
        return pageDiys;
    }

    /**
     * 保存diy
     *
     * @param pageDiy diy数据
     */
    @Override
    public PageDiy savePageDiy(PageDiy pageDiy) {
        String adminApiPath = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_KEY_API_URL);
        if (StrUtil.isBlank(adminApiPath)) {
            throw new CrmebException("应用设置中 微信小程序数据配置 或者 支付回调地址以及网站地址 配置不全");
        }
        DocumentContext jsonContext = JsonPath.parse(pageDiy.getValue());
        // 通配符去掉关键子 再存储
        jsonContext.delete("$..*[?(@ == '"+ adminApiPath +"')]");
        pageDiy.setValue(jsonContext.jsonString());
        save(pageDiy);
        return pageDiy;
    }

    /**
     * 编辑diy名称
     *@param pageDiyEditNameRequest 待编辑名称对象
     */
    @Override
    public Boolean editPageDiyName(PageDiyEditNameRequest pageDiyEditNameRequest) {
        PageDiy pageDiyForUpdate = new PageDiy();
        pageDiyForUpdate.setId(pageDiyEditNameRequest.getId());
        pageDiyForUpdate.setName(pageDiyEditNameRequest.getName());
        return dao.updateById(pageDiyForUpdate) > 0;
    }

    /**
     * 设置DIY首页模版
     * isDefault =1 是平台首页 2=商户 diy后期商户再处理
     *
     * @param diyId 被设置为首页的diy模版id
     * @return 设置结果
     */
    @Override
    public Boolean setDiyPageHome(Integer diyId) {
        PageDiy pageDiy = dao.selectById(diyId);
        if(ObjectUtil.isNull(pageDiy)) throw new CrmebException("当前DIY模版不存在");

        // 取消现有的首页设置，如果存在的话
        LambdaQueryWrapper<PageDiy> queryWaiteResetDefaultTemp = Wrappers.lambdaQuery();
        queryWaiteResetDefaultTemp.eq(PageDiy::getIsDefault, 1);
        List<PageDiy> currentWaitResetPageHome = dao.selectList(queryWaiteResetDefaultTemp);
        List<PageDiy> currentTempByReset = currentWaitResetPageHome.stream().map(homeTemp -> homeTemp.setIsDefault(0)).collect(Collectors.toList());
        saveOrUpdateBatch(currentTempByReset);

        // 设置当前diy数据为商城首页
        pageDiy.setIsDefault(1);
        return dao.updateById(pageDiy) > 0;
    }

    /**
     * 获取DIY首页模版Id
     *
     * @return 首页模版ID
     */
    @Override
    public PageDiy getDiyPageHome() {
        LambdaQueryWrapper<PageDiy> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PageDiy::getIsDefault, 1);
        queryWrapper.select(PageDiy.class, i -> !i.getColumn().equals("value"));
        List<PageDiy> currentWaitResetPageHome = dao.selectList(queryWrapper);
        if(ObjectUtil.isNull(currentWaitResetPageHome) || currentWaitResetPageHome.size() != 1){
            throw new CrmebException("首页模版设置不正确！");
        }
        return currentWaitResetPageHome.get(0);
    }

    /**
     * 根据id加载diy模版配置
     *
     * @param id 对应的模版id
     *           描述：
     *           id=0加载商城首页的，也就是setDiyPageHome后的数据，平台端会默认设置已经有首页的数据，也会预制
     *           id>1时加载对应的模版即可
     */
    @Override
    public PageDiyResponse getDiyPageByPageId(Integer id) {
        PageDiy pageDiy;
        if(0 == id){
            LambdaQueryWrapper<PageDiy> getHomeDefault = Wrappers.lambdaQuery();
            getHomeDefault.eq(PageDiy::getIsDefault, 1);
            pageDiy = getOne(getHomeDefault);
        }else{
            pageDiy = getById(id);
        }

        if(ObjectUtil.isNull(pageDiy)) throw new CrmebException("未找到对应模版信息");


        // 优化front比必要的字段 提高diy组件渲染效率
        DocumentContext jsonContext = JsonPath.parse(pageDiy.getValue());
        jsonContext.delete("$..*[?(@.name == 'goodList')].itemStyle.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].tabConfig.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].typeConfig.list");
//        jsonContext.delete("$..*[?(@.name == 'goodList')].selectConfig");
        jsonContext.delete("$..*[?(@.name == 'goodList')].goodsSort.list");
        jsonContext.delete("$..*[?(@.name == 'goodList')].goodsList.list[*].attrValue");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].activeValueBrand");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].goodsList");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].selectConfig");
        jsonContext.delete("$..*[?(@.name == 'homeTab')].productList..*.goods[*].attrValue");

        PageDiyResponse response = new PageDiyResponse();
        BeanUtils.copyProperties(pageDiy, response);
        response.setValue(JSON.parseObject(jsonContext.jsonString()));
//           response.setValue(JSON.parseObject(pageDiy.getValue()));
        return response;
    }

}

