package com.mortals.xhx.module.device.web;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.net.url.UrlBuilder;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.util.DataUtil;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.code.ImageReEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.module.device.model.DeviceModuleDistributeEntity;
import com.mortals.xhx.module.device.service.DeviceModuleDistributeService;
import com.mortals.xhx.module.product.model.ProductEntity;
import com.mortals.xhx.module.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.Charset;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mortals.xhx.common.key.Constant.PARAM_SERVER_HTTP_URL;

/**
 *
 * 设备前端模块部署
 *
 * @author zxfei
 * @date 2022-08-02
 */
@RestController
@RequestMapping("device/module/distribute")
public class DeviceModuleDistributeController extends BaseCRUDJsonBodyMappingController<DeviceModuleDistributeService,DeviceModuleDistributeEntity,Long> {

    @Autowired
    private ParamService paramService;
    @Autowired
    private ProductService productService;

    public DeviceModuleDistributeController(){
        super.setModuleDesc( "设备前端模块部署");
    }

    @Override
    protected void init(Map<String, Object> model, Context context) {
        this.addDict(model, "distribute", YesNoEnum.getEnumMap());
        this.addDict(model, "productId", productService.find(new ProductEntity()).stream().collect(Collectors.toMap(x -> x.getId().toString(), y -> y.getProductName())));

/*        Rest<RespData<List<SkinBasePdu>>> resp = skinBaseFeign.list(new SkinBasePdu());
        if (resp.getCode() == YesNoEnum.YES.getValue()) {
            Map<String, Map<String, String>> skinProductCodeMap = resp.getData().getData().stream().collect(Collectors.groupingBy(x -> x.getProductCode(), Collectors.toMap(a -> a.getImageResolution() == null ? "" : a.getImageResolution()+"", b -> b.getImageResolutionValue() == null ? "" : b.getImageResolutionValue(), (o, n) -> n)));
            this.addDict(model, "imageResolution", skinProductCodeMap);
        }*/

        this.addDict(model, "imageResolution", ImageReEnum.getEnumMap());
        super.init(model, context);
    }


    /**
     * 部署
     */
    @PostMapping(value = "active")
    public Rest<Void> deviceActive(@RequestBody DeviceModuleDistributeEntity moduleDistributeEntity) {
        String busiDesc = this.getModuleDesc() + "设备模块部署";
        Rest<Void> rest = Rest.ok(busiDesc + " 【成功】");
        try {
            this.service.active(moduleDistributeEntity, getContext());
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error("设备模块部署", e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }


    @Override
    protected int viewAfter(Long id, Map<String, Object> model, DeviceModuleDistributeEntity entity, Context context) throws AppException {

        String serverName = request.getHeader("server-name");
        Integer serverPort = DataUtil.converStr2Int(request.getHeader("server-port"),0);

        String homeUrl="";
        ProductEntity productEntity = productService.get(entity.getProductId(), context);
        if(!ObjectUtils.isEmpty(productEntity.getHomeUrl())){
            homeUrl= productEntity.getHomeUrl();
        }
        String domain = GlobalSysInfo.getParamValue(PARAM_SERVER_HTTP_URL, "http://192.168.0.98:11078");
        if(!ObjectUtils.isEmpty(serverName)&& Validator.isIpv4(serverName)){
            String str = UrlBuilder.ofHttp(serverName).setPort(serverPort>0?serverPort:11078).addPath(homeUrl).build();
            String decodeStr = URLDecoder.decode(str, Charset.defaultCharset());
            entity.setFilePath(decodeStr);
        }else{
            String str = UrlBuilder.of(domain.trim()).addPath(homeUrl).build();
            String decodeStr = URLDecoder.decode(str, Charset.defaultCharset());
            entity.setFilePath(decodeStr);
        }
        //String temp=domain+"/"+homeUrl;
        //entity.setFilePath(UrlBuilder.of(domain).addPath(homeUrl).build());
       // entity.setFilePath(temp);
        return super.viewAfter(id, model, entity, context);
    }
}