package com.mortals.xhx.module.device.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
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.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.common.code.ImageReEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.pdu.site.SitePdu;
import com.mortals.xhx.feign.site.ISiteFeign;
import com.mortals.xhx.module.device.dao.DeviceModuleDistributeDao;
import com.mortals.xhx.module.device.model.DeviceModuleDistributeEntity;
import com.mortals.xhx.module.device.model.DeviceModuleDistributeQuery;
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 com.mortals.xhx.utils.EncodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;

/**
 * DeviceModuleDistributeService
 * 设备前端模块部署 service实现
 *
 * @author zxfei
 * @date 2022-08-02
 */
@Service("deviceModuleDistributeService")
public class DeviceModuleDistributeServiceImpl extends AbstractCRUDServiceImpl<DeviceModuleDistributeDao, DeviceModuleDistributeEntity, Long> implements DeviceModuleDistributeService {
    @Autowired
    private ProductService productService;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private ISiteFeign siteFeign;

    @Override
    protected void saveBefore(DeviceModuleDistributeEntity entity, Context context) throws AppException {
        ProductEntity productEntity = productService.get(entity.getProductId(), context);
        entity.setProductCode(productEntity.getProductCode());
        entity.setProductName(productEntity.getProductName());
        entity.setImageResolutionValue(ImageReEnum.getByValue(Integer.parseInt(entity.getImageResolution())).getDesc());
        super.saveBefore(entity, context);
    }


    @Override
    protected void updateBefore(DeviceModuleDistributeEntity entity, Context context) throws AppException {
        ProductEntity productEntity = productService.get(entity.getProductId(), context);
        entity.setProductCode(productEntity.getProductCode());
        entity.setProductName(productEntity.getProductName());
        entity.setImageResolutionValue(ImageReEnum.getByValue(Integer.parseInt(entity.getImageResolution())).getDesc());

        super.updateBefore(entity, context);
    }

    @Override
    public void active(DeviceModuleDistributeEntity distributeEntity, Context context) {
        //判断文件是否存在
        String targetFilePath = uploadService.getFilePath(distributeEntity.getFilePath());
        if (FileUtil.isEmpty(new File(targetFilePath))) {
            throw new AppException("部署文件不存在！");
        }

        if (!FileUtil.getSuffix(distributeEntity.getFilePath()).equals("zip")) {
            throw new AppException("部署只支持zip文件！");
        }

        //RuntimeUtil
        //部署路径是否存在 如果不存在 创建目录，
        String path = GlobalSysInfo.getParamValue(Constant.DISTRIBUTE_PATH, "/home/publish/app/homeDeviceUrl");

        String siteCode = distributeEntity.getSiteCode();
        String code = distributeEntity.getProductCode();
        String imageRe = distributeEntity.getImageResolutionValue();
        String disPath = "/" + siteCode + "/" + path + "/" + code + "/" + imageRe;
        //判断目标目录是否存在 如果存在 这删除
        if (FileUtil.isDirectory(disPath)) {
            FileUtil.del(disPath);
        }

        String fileEncode = "UTF-8";
        try {
            fileEncode = EncodeUtil.getEncode(targetFilePath, true);
        } catch (Exception e) {
            log.error("异常", e);
        }
        ZipUtil.unzip(targetFilePath, disPath, Charset.forName(fileEncode));
        //更新
        distributeEntity.setDistributeFilePath(disPath);
        distributeEntity.setDistribute(YesNoEnum.YES.getValue());
        distributeEntity.setUpdateTime(new Date());

        this.update(distributeEntity, context);
    }

    @Override
    public Rest<String> cloneAppBySite(DeviceModuleDistributeEntity deviceModuleDistributeEntity, Context context) {

        //拷贝应用
        Long targetSiteId = deviceModuleDistributeEntity.getTargetSiteId();
        Long sourceSiteId = deviceModuleDistributeEntity.getSourceSiteId();

        Rest<SitePdu> sitePduRest = siteFeign.info(targetSiteId);

        if (YesNoEnum.NO.getValue() == sitePduRest.getCode()) {
            throw new AppException("未查询到当前站点！");
        }

        SitePdu sitePdu = sitePduRest.getData();

        DeviceModuleDistributeQuery distributeQuery = new DeviceModuleDistributeQuery();
        distributeQuery.setSiteId(sourceSiteId);
        List<DeviceModuleDistributeEntity> deviceModuleDistributeEntities = this.find(distributeQuery);

        //如果已存在 则不复制
        for (DeviceModuleDistributeEntity moduleDistributeEntity : deviceModuleDistributeEntities) {
            DeviceModuleDistributeQuery query = new DeviceModuleDistributeQuery();
            query.setSiteId(targetSiteId);
            query.setProductId(moduleDistributeEntity.getProductId());
            query.setVersion(moduleDistributeEntity.getVersion());
            int count = this.count(query, context);
            if (count == 0) {
                moduleDistributeEntity.setId(null);
                moduleDistributeEntity.setSiteId(sitePdu.getId());
                moduleDistributeEntity.setSiteName(sitePdu.getSiteName());
                moduleDistributeEntity.setSiteCode(sitePdu.getSiteCode());
                moduleDistributeEntity.setDistributeFilePath("");
                moduleDistributeEntity.setDistribute(YesNoEnum.NO.getValue());
                this.save(moduleDistributeEntity, context);
            }
        }
        return Rest.ok();
    }


    public static void main(String[] args) {

        File file = new File("F:\\交警窗口证件照.zip");
        String disPath = "F:\\pics\\";

        String fileEncode = "UTF-8";
        try {
            fileEncode = EncodeUtil.getEncode("F:\\1672973316144.zip", true);
        } catch (Exception e) {

        }

        ZipUtil.unzip("F:\\1672973316144.zip", disPath, Charset.forName(fileEncode));

/*        File[] files = FileUtil.ls(disPath);
        for (File file1 : files) {
            System.out.println(file1.getName());

        }*/

/*        System.out.println(file.getName());

        System.out.println(FileUtil.getPrefix(file));*/


        // ZipUtil.unzip("F:\\1664176173348.zip", "F:\\tmp");

    }
}