package com.mortals.xhx.module.product.service.impl;
import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.net.url.UrlPath;
import cn.hutool.core.util.URLUtil;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.module.product.model.ProductQuery;
import com.sun.jndi.toolkit.url.UrlUtil;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.module.product.dao.ProductDao;
import com.mortals.xhx.module.product.model.ProductEntity;
import com.mortals.xhx.module.product.service.ProductService;
import org.springframework.util.ObjectUtils;

import java.nio.charset.Charset;

/**
* ProductService
* 产品 service实现
*
* @author zxfei
* @date 2022-06-27
*/
@Service("productService")
public class ProductServiceImpl extends AbstractCRUDServiceImpl<ProductDao, ProductEntity, Long> implements ProductService {


    @Override
    protected void saveBefore(ProductEntity entity, Context context) throws AppException {
        //新增产品编码不能重复
        ProductEntity productEntity = this.selectOne(new ProductQuery().productCode(entity.getProductCode()));
        if(!ObjectUtils.isEmpty(productEntity))throw new AppException("当前产品编码已存在！");
        //默认时，需拼接homeUrl
        updateDeviceHomeUrl(entity);
        super.saveBefore(entity, context);
    }



    @Override
    protected void updateBefore(ProductEntity entity, Context context) throws AppException {
        ProductEntity productEntity = this.get(entity.getId());
        if(!productEntity.getProductCode().equals(entity.getProductCode())){
            ProductEntity productEntity1 = this.selectOne(new ProductQuery().productCode(entity.getProductCode()));
            if(!ObjectUtils.isEmpty(productEntity1))throw new AppException("当前产品编码已存在！");
        }
        updateDeviceHomeUrl(entity);
        super.updateBefore(entity, context);
    }

    private void updateDeviceHomeUrl(ProductEntity entity) {
        if (!ObjectUtils.isEmpty(entity.getSkinName())) {
            String path = UrlPath.of(Constant.DEVICE_BASEHOME_PATH,Charset.defaultCharset())
                    .add(entity.getProductCode())
                    .add(entity.getSkinName())
                    .toString();
            entity.setHomeUrl(path);
        }
    }


    public static void main(String[] args) {

        //String path = URLUtil.completeUrl("http://192.168.0.98:11091/homeDeviceUrl", "pdj");

        //System.out.println("path:"+path);


        String path =UrlBuilder.create().setHost("http").setHost("192.168.0.98").setPort(11091).addPath("pdj").build();


        path = UrlPath.of("homeDeviceUrl", Charset.defaultCharset()).add("pdj").toString();

        System.out.println("path:"+path);

    }
}