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.AbstractCRUDCacheServiceImpl;
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.key.RedisKey;
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 org.springframework.util.ObjectUtils;

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

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


    @Override
    public void putCache(String key, DeviceModuleDistributeEntity data) {
        super.putCache(key, data);


        if (YesNoEnum.YES.getValue() == data.getSelected()) {
            updateYesSelectedPath(data, YesNoEnum.YES);
        } else {
            updateYesSelectedPath(data, YesNoEnum.NO);
        }
        //设置yes与no

    }

    @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
    protected void updateAfter(DeviceModuleDistributeEntity entity, Context context) throws AppException {
        super.updateAfter(entity, context);
        if (YesNoEnum.YES.getValue() == entity.getSelected()) {
            updateYesSelectedPath(entity, YesNoEnum.YES);
        } else {
            updateYesSelectedPath(entity, YesNoEnum.NO);
        }
    }

    @Override
    protected void saveAfter(DeviceModuleDistributeEntity entity, Context context) throws AppException {
        super.saveAfter(entity, context);
        if (YesNoEnum.YES.getValue() == entity.getSelected()) {
            updateYesSelectedPath(entity, YesNoEnum.YES);
        } else {
            updateYesSelectedPath(entity, YesNoEnum.NO);
        }
    }

    @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();
        Long siteId = distributeEntity.getSiteId();
        String code = distributeEntity.getProductCode();
        String imageRe = distributeEntity.getImageResolutionValue();

        String disPath = path + "/" + siteId + "/" + 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> selected(DeviceModuleDistributeEntity distributeEntity, Context context) {
        DeviceModuleDistributeEntity deviceModuleDistributeEntity = this.get(distributeEntity.getId(), context);

        //选择默认资源默认分辨率
        //如果选择的资源未部署，则提示先部署后才能选择
        if (!ObjectUtils.isEmpty(deviceModuleDistributeEntity) && deviceModuleDistributeEntity.getDistribute() == YesNoEnum.NO.getValue()) {
            throw new AppException("选择的默认资源需先部署后才能选择！");
        }

        //如果选择默认为为否，且选择后没有默认选择，则不让他选择
        if (YesNoEnum.NO.getValue() == distributeEntity.getSelected()) {
            DeviceModuleDistributeQuery query = new DeviceModuleDistributeQuery();
            query.setProductId(deviceModuleDistributeEntity.getProductId());
            query.setIdNotList(Arrays.asList(distributeEntity.getId()));
            List<DeviceModuleDistributeEntity> deviceModuleDistributeEntities = this.find(query, context);

            if (ObjectUtils.isEmpty(deviceModuleDistributeEntities))
                throw new AppException("当前产品默认选择取消后没有默认选择，不能切换！");

            DeviceModuleDistributeEntity moduleDistribute = deviceModuleDistributeEntities.stream().filter(f -> f.getSelected() == YesNoEnum.YES.getValue()).findFirst().orElseGet(() -> null);
            if (ObjectUtils.isEmpty(moduleDistribute))
                throw new AppException("当前产品默认选择取消后没有默认选择，不能切换！");

            distributeEntity.setId(deviceModuleDistributeEntity.getId());
            distributeEntity.setSelected(YesNoEnum.NO.getValue());
            distributeEntity.setUpdateTime(new Date());
            distributeEntity.setUpdateUserId(this.getContextUserId(context));

            this.getDao().update(distributeEntity);
            updateYesSelectedPath(deviceModuleDistributeEntity, YesNoEnum.NO);

        } else {
            distributeEntity.setId(deviceModuleDistributeEntity.getId());
            distributeEntity.setSelected(YesNoEnum.YES.getValue());
            distributeEntity.setUpdateTime(new Date());
            distributeEntity.setUpdateUserId(this.getContextUserId(context));

            this.getDao().update(distributeEntity);
            updateYesSelectedPath(deviceModuleDistributeEntity, YesNoEnum.YES);

            //更新缓存
        }

        //查询同类资源，变更为非默认值后 再更新


/*        DeviceModuleDistributeQuery query = new DeviceModuleDistributeQuery();
        query.setProductId(deviceModuleDistributeEntity.getProductId());
        query.setSiteId(deviceModuleDistributeEntity.getSiteId());
        List<Long> idList = this.find(query, context).stream().map(i -> i.getId()).collect(Collectors.toList());

        DeviceModuleDistributeQuery condition = new DeviceModuleDistributeQuery();
        condition.setIdList(idList);

        DeviceModuleDistributeEntity entity = new DeviceModuleDistributeEntity();
        entity.setSelected(YesNoEnum.NO.getValue());*/

        //this.updateBatch(entity, condition, context);


        return Rest.ok();
    }

    private void updateYesSelectedPath(DeviceModuleDistributeEntity deviceModuleDistributeEntity, YesNoEnum yes) {
        String keyYesPath = deviceModuleDistributeEntity.getSiteId() + "#" + deviceModuleDistributeEntity.getProductId() + "#" + yes.getValue();
        String homeUrl = String.format("/homeDeviceUrl/%s/%s/%s", deviceModuleDistributeEntity.getSiteId(), deviceModuleDistributeEntity.getProductCode(), deviceModuleDistributeEntity.getImageResolutionValue());
        cacheService.set(RedisKey.KEY_DEVICE_DISBUTE_PATH_CHCHE + keyYesPath, homeUrl);
    }

    @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());
                moduleDistributeEntity.setSelected(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");

    }
}