package com.jeeplus.test.wdt.merchantCompany.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.sys.constant.CacheNames;
import com.jeeplus.sys.domain.DictValue;
import com.jeeplus.sys.service.DictTypeService;
import com.jeeplus.sys.service.dto.DictValueDTO;
import com.jeeplus.sys.service.mapstruct.DictValueWrapper;
import com.jeeplus.sys.utils.DictUtils;
import com.jeeplus.test.utils.MoneyUtil;
import com.jeeplus.test.wdt.merchantCompany.domain.MerchantDetails;
import com.jeeplus.test.wdt.merchantCompany.mapper.MerchantDetailsMapper;
import com.jeeplus.test.wdt.merchantCompany.service.dto.MerchantDetailsDTO;
import com.jeeplus.test.wdt.merchantCompany.service.mapstuct.MerchantDetailsWrapper;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 入驻详情service
 * @author: 徐滕
 * @version: 2024-01-04 10:56
 */
@Service
@Transactional
public class MerchantDetailsService extends ServiceImpl<MerchantDetailsMapper, MerchantDetails> {

    @Autowired
    private MerchantDetailsWrapper merchantDetailsWrapper;

    @Autowired
    private DictValueWrapper dictValueWrapper;

    @Autowired
    private DictTypeService dictTypeService;

    @Value("${merchantFilePath}")
    private String merchantFilePath;


    /**
     * 查询详情
     * @return
     */
    public MerchantDetailsDTO getLimit1() {
        MerchantDetailsDTO limit1 = baseMapper.getLimit1();
        //查询字典中数据获取方式并修改
        List<DictValueDTO> merchantDataSourcesList = DictUtils.getDictDTOList("merchant_data_sources");
        if(merchantDataSourcesList.size()>0){
            for (DictValueDTO dictValueDTO : merchantDataSourcesList) {
                if("result".equals(dictValueDTO.getLabel())){
                    if(null != limit1){
                        limit1.setDataSourcesType(dictValueDTO.getValue());
                    }
                }
            }
        }
        //查询字典中 大屏名称信息
        List<DictValueDTO> screenNameList = DictUtils.getDictDTOList("merchant_screen_name");
        if(screenNameList.size()>0){
            for (DictValueDTO dictValueDTO : screenNameList) {
                if("name".equals(dictValueDTO.getLabel())){
                    if(null != limit1){
                        limit1.setScreenName(dictValueDTO.getValue());
                    }
                }
            }
        }

        //查询字典中 大屏视频路径
        List<DictValueDTO> merchantFilePathList = DictUtils.getDictDTOList("merchant_file_path");
        if(merchantFilePathList.size()>0){
            for (DictValueDTO dictValueDTO : merchantFilePathList) {
                if("name".equals(dictValueDTO.getLabel())){
                    if(null != limit1){
                        limit1.setPath(dictValueDTO.getValue());
                    }
                }
            }
        }
        return limit1;
    }


    /**
     * 保存或者更新详情信息
     *
     * @param merchantDetailsDTO
     */
    public void saveOrUpdate(MerchantDetailsDTO merchantDetailsDTO) {
        MerchantDetails merchantDetails = merchantDetailsWrapper.toEntity ( merchantDetailsDTO );
        super.saveOrUpdate ( merchantDetails );
    }

    /**
     * 保存或者更新详情信息
     *
     * @param dataSources
     */
    public void saveDataSources(String dataSources) {

        Integer redisLoginNumber = (Integer) RedisUtils.getInstance ().get ( CacheNames.MERCHANTDETAILS );

        //查询字典中数据获取方式并修改
        List<DictValueDTO> merchantDataSourcesList = DictUtils.getDictDTOList("merchant_data_sources");
        if(merchantDataSourcesList.size()>0){
            for (DictValueDTO dictValueDTO : merchantDataSourcesList) {
                if("result".equals(dictValueDTO.getLabel())){
                    dictValueDTO.setValue(dataSources);
                    DictValue dictValue = dictValueWrapper.toEntity ( dictValueDTO );
                    dictTypeService.saveDictValue(dictValue);
                }
            }
        }
    }

    /**
     * 保存或者更新详情信息
     *
     * @param screenName
     */
    public void screenSave(String screenName, String filePath) {


        //查询字典中数据获取方式并修改
        List<DictValueDTO> merchantDataSourcesList = DictUtils.getDictDTOList("merchant_screen_name");
        if(merchantDataSourcesList.size()>0){
            for (DictValueDTO dictValueDTO : merchantDataSourcesList) {
                if("name".equals(dictValueDTO.getLabel())){
                    dictValueDTO.setValue(screenName);
                    DictValue dictValue = dictValueWrapper.toEntity ( dictValueDTO );
                    dictTypeService.saveDictValue(dictValue);
                }
            }
        }

        //查询字典中数据获取方式并修改
        List<DictValueDTO> merchantFilePathList = DictUtils.getDictDTOList("merchant_file_path");
        if(merchantFilePathList.size()>0){
            String newFilePath = filePath;
            filePath = filePath.replace("/file/download?path=","");
            filePath = filePath.replace("&name=","");
            //对视频路径进行解析

            String fileName = "";
            String fileAbsolutePath = "";
            int lastIndex = filePath.lastIndexOf('/');
            if (lastIndex != -1) {
                fileName = filePath.substring(lastIndex + 1);
                fileAbsolutePath = filePath.substring(0,lastIndex);
            } else {
            }
            for (DictValueDTO dictValueDTO : merchantFilePathList) {
                if("name".equals(dictValueDTO.getLabel())){
                    dictValueDTO.setValue(newFilePath);
                    DictValue dictValue = dictValueWrapper.toEntity ( dictValueDTO );
                    dictTypeService.saveDictValue(dictValue);
                    //数据处理完成后将原有的视频文件也进行删除

                    File folder = new File(fileAbsolutePath); // 替换为你的文件夹路径
                    deleteFiles(folder,fileName);
                }
            }
        }
    }

    public static void deleteFiles(File folder,String newFileName) {
        File[] files = folder.listFiles();
        if (files != null) { // 确保文件数组不为空
            for (File file : files) {
                if (file.isFile()) {
                    String fileName = file.getName();
                    if (!fileName.equals(newFileName)) {
                        boolean deleted = file.delete();
                        if (deleted) {
                            System.out.println("File deleted: " + file.getAbsolutePath());
                        } else {
                            System.out.println("Failed to delete file: " + file.getAbsolutePath());
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取大屏数据并返回
     * @param type 获取数据类型
     * @param settledEnterpriseType 入驻类型
     * @return
     */
    public Map<String,String> getScreenDetail(String type,String settledEnterpriseType){
        Map<String,String> map = new HashMap<>();
        //查询字典中大屏数据获取节点信息
        String dictType = "0";
        List<DictValueDTO> merchantDataSourcesList = DictUtils.getDictDTOList("merchant_data_sources");
        if(merchantDataSourcesList.size()>0){
            for (DictValueDTO dictValueDTO : merchantDataSourcesList) {
                if("result".equals(dictValueDTO.getLabel())){
                    dictType = dictValueDTO.getValue();
                }
            }
        }
        switch (dictType){
            case "0":   //查询填写值
                //获取数据信息
                MerchantDetailsDTO info = this.getLimit1();
                if ("settledEnterpriseNumber".equals(type)) {   //入驻企业数(产品加工企业)
                    map.put("value",info.getSettledEnterpriseNumber().toString());
                }else if ("cooperativeEnterpriseNumber".equals(type)) {   //入驻企业数(合作企业)
                    map.put("value",info.getCooperativeEnterpriseNumber().toString());
                }else if ("practitionerCount".equals(type)){    //电商从业人数
                    map.put("value",info.getPractitionerCount().toString());
                }else if ("commerceShopCount".equals(type)){    //电商小铺
                    map.put("value",info.getCommerceShopCount().toString());
                }else if ("annualSales".equals(type)){          //年交易额
                    map.put("value",info.getAnnualSales());
                }else if ("onlineRetailSales".equals(type)){    //网络零售额
                    map.put("value",info.getOnlineRetailSales());
                }else if ("merchantProductCount".equals(type)){    //入驻产品种类
                    map.put("value",info.getMerchantProductCount());
                }else if ("enterNumber".equals(type)){          //入驻平台
                    map.put("value",info.getEnterNumber());
                }
                break;

            case "1":   //计算汇总值

                if ("settledEnterpriseNumber".equals(type)) {   //入驻企业数(产品加工企业)
                    String settledEnterpriseNumber = baseMapper.getSettledEnterpriseNumber("1");
                    map.put("value",settledEnterpriseNumber);
                }else if ("cooperativeEnterpriseNumber".equals(type)) {   //入驻企业数(合作企业)
                    String settledEnterpriseNumber = baseMapper.getSettledEnterpriseNumber("2");
                    map.put("value",settledEnterpriseNumber);
                }else if ("practitionerCount".equals(type)){    //电商从业人数
                    String practitionerCount = baseMapper.getPractitionerCount();
                    map.put("value",practitionerCount);
                }else if ("commerceShopCount".equals(type)){    //电商小铺
                    String commerceShopCount = baseMapper.getCommerceShopCountCount();
                    map.put("value",commerceShopCount);
                }else if ("annualSales".equals(type)){          //年交易额
                    String annualSales = baseMapper.getAnnualSales();
                    BigDecimal bigDecimal = MoneyUtil.toTenThousand(annualSales);
                    map.put("value",bigDecimal.toString());

                }else if ("onlineRetailSales".equals(type)){    //网络零售额
                    String onlineRetailSales = baseMapper.getOnlineRetailSales();
                    BigDecimal bigDecimal = MoneyUtil.toTenThousand(onlineRetailSales);
                    map.put("value",bigDecimal.toString());

                }else if ("merchantProductCount".equals(type)){    //入驻产品种类
                    String merchantProductCount = baseMapper.getMerchantProductCount();
                    map.put("value",merchantProductCount);
                }else if ("enterNumber".equals(type)){          //抖音入驻
                    String enterNumber = baseMapper.getEnterNumber(settledEnterpriseType);
                    map.put("value",enterNumber);
                }
                break;
            default:
                map.put("value","0");
                break;
        }
        return map;
    }


    /**
     * 获取大屏名称
     * @return
     */
    public Map<String,String> getScreenName(){
        Map<String,String> map = new HashMap<>();
        map.put("value","");
        //查询字典中 大屏名称信息
        List<DictValueDTO> screenNameList = DictUtils.getDictDTOList("merchant_screen_name");
        if(screenNameList.size()>0){
            for (DictValueDTO dictValueDTO : screenNameList) {
                if("name".equals(dictValueDTO.getLabel())){
                    map.put("value",dictValueDTO.getValue());
                }
            }
        }
        return map;
    }


    /**
     * 获取大屏视频url
     * @return
     */
    public Map<String,String> getFilePathUrl(){
        Map<String,String> map = new HashMap<>();
        map.put("value","");
        //查询字典中 大屏名称信息
        List<DictValueDTO> screenNameList = DictUtils.getDictDTOList("merchant_file_path");
        if(screenNameList.size()>0){
            for (DictValueDTO dictValueDTO : screenNameList) {
                if("name".equals(dictValueDTO.getLabel())){

                    //视频文件地址
                    String filePath = dictValueDTO.getValue();
                    filePath = filePath.replace("/file/download?path=","");
                    filePath = filePath.replace("&name=","");
                    //对视频路径进行解析

                    String fileName = "";
                    int lastIndex = filePath.lastIndexOf('/');
                    if (lastIndex != -1) {
                        fileName = filePath.substring(lastIndex + 1);
                    }
                    String url = merchantFilePath + "/img/video/" + fileName;
                    map.put("value",url);
                }
            }
        }
        return map;
    }

}
