package com.hwrj.cloud.admin.controller;


import com.alibaba.fastjson.JSONObject;
import com.hwrj.cloud.admin.dao.PmsProductExcelDao;
import com.hwrj.cloud.admin.dto.param.ForestPath;
import com.hwrj.cloud.admin.dto.param.PmsProductExcel;
import com.hwrj.cloud.admin.dto.param.PmsProductExcelParam;
import com.hwrj.cloud.admin.dto.utilEntity.LagLatEntity;
import com.hwrj.cloud.admin.excelEntity.UmsCompanyInfoExcel;
import com.hwrj.cloud.admin.excelEntity.UmsMemberOriginExcel;
import com.hwrj.cloud.admin.listener.ImportExcelEventListener;
import com.hwrj.cloud.admin.mapper.PmsProductMapper;
import com.hwrj.cloud.admin.mapper.UmsCompanyFileMapper;
import com.hwrj.cloud.admin.mapper.UmsCompanyInfoMapper;
import com.hwrj.cloud.admin.mapper.UmsMemberOriginMapper;
import com.hwrj.cloud.admin.model.*;
import com.hwrj.cloud.admin.service.UmsCompanyService;
import com.hwrj.cloud.admin.service.UmsMemberOriginService;
import com.hwrj.cloud.admin.util.*;
import com.hwrj.cloud.common.api.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/first")
@Api(tags = "第一次上传用")
@Slf4j
public class UploadCompanyInfoAndProductController {

    @Autowired
    private UploadFileUtil uploadFileUtil;


    @Value("${qiniu.path}")
    private String url;
    @Autowired
    private CompanyLatLagGet companyLatLagGet;

    List<PmsProductExcelParam> listAll = new ArrayList<>();


    @ApiOperation("上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paths", value = "文件路径", required = true),
            @ApiImplicitParam(name = "type", value = "上传类型", required = true, allowableValues = "1,2,3"),
            @ApiImplicitParam(name = "compName", value = "公司名称", required = false)
    })
    @PostMapping("/upload")
    @Transactional
    public CommonResult readFile(@RequestParam(value = "paths") String paths, @RequestParam(value = "type") String type, @RequestParam(value = "compName", required = false) String compName) {

        if ("1".equals(type)) {
            String filepath = paths;
            List<String> file = getDirectory(filepath);
            List<ForestPath> list = new ArrayList<>();
            file.stream().forEach(item -> {
                ForestPath forestPath = new ForestPath();
                forestPath.setCompanyName(item);
                forestPath.setPath(filepath + "\\" + item);
                forestPath.setType("1");
                System.out.println(item);
                list.add(forestPath);
            });
            for (ForestPath path : list) {
                return excelPut(path);
            }
        } else if ("2".equals(type)) {
            ForestPath fs = new ForestPath();
            fs.setCompanyName(compName);
            fs.setPath(paths);
            return excelPut(fs);
        } else if ("3".equals(type)) {
            ForestPath fs = new ForestPath();
            fs.setPath(paths + "\\" + compName);
            fs.setCompanyName(compName);
            return excelPut(fs);
        }

        return CommonResult.success();

    }

    /**
     * 上传公司的excel
     *
     * @param forestPath
     */
    public CommonResult excelPut(ForestPath forestPath) {
        String company = forestPath.getCompanyName();


        List<String> strings = getDirectory(forestPath.getPath());
        List<String> excel = getFile(forestPath.getPath());
        for (String path : excel) {
            if (path.endsWith(".xlsx")) {
                company = addCompanyInfo(new File(forestPath.getPath() + "\\" + path), company);
                System.out.println("供应商导入表格--" + path);
            }
        }
        if (StringUtils.isEmpty(company)) {
            return CommonResult.failed("导表失败");
        }
        Long companyId = companyId(company);
        List<ForestPath> list = new ArrayList<>();
        for (String str : strings) {
            ForestPath forestPath1 = new ForestPath();
            forestPath1.setType("2");
            forestPath1.setPath(forestPath.getPath() + "\\" + str);
            forestPath1.setCompanyName(str);
            list.add(forestPath1);

        }
        for (ForestPath p : list) {
            if ("产品".equals(p.getCompanyName())) {
                addProductImg(p, company, companyId);
            } else if ("供应商".equals(p.getCompanyName())) {
                addCompanyImg(p, company, companyId);
            } else if ("生产地".equals(p.getCompanyName())) {
                addOriginImg(p, company, companyId);
            } else {
                System.out.println("没有对应文件夹的处理方式---" + p.getCompanyName());
            }
        }
        return CommonResult.success();


    }

    @Autowired
    private UmsCompanyFileMapper umsCompanyFileMapper;

    public void addCompanyImg(ForestPath forestPath, String companyName, Long companyId) {
        String path = forestPath.getPath();
        List<String> file = getFile(path);
        String br = "0/3/" + companyId + "/";
        int i = 0;
        List<UmsCompanyFile> files = new ArrayList<>();
        for (String str : file) {
            String s = OrderNo.NextOrderNo();
            UmsCompanyFile infoFile = new UmsCompanyFile();
            infoFile.setUpdateTime(new Date());
            infoFile.setCompId(companyId(companyName));
            infoFile.setFileStatus(0);
            String imgName = br + s;
            str = str.toLowerCase();
            String[] split = null;
            try {
                split = str.split("\\.");
            } catch (Exception e) {
                throw new RuntimeException("获取文件后缀出错!=======>" + split);
            }
            imgName = imgName + "." + split[1];
            String filePath = path + "\\" + str;
            infoFile.setFileUrl(url + imgName);
            if (str.contains("公众号二维码")) {
                infoFile.setFileType("qrl");
                uploadFileUtil.uploadLocalFile(filePath, imgName);
            } else if (str.contains("logo")) {
                infoFile.setFileType("logo");
                uploadFileUtil.uploadLocalFile(filePath, imgName);

            } else if (str.contains("供应商资质")) {
                infoFile.setFileType("cert");
                uploadFileUtil.uploadLocalFile(filePath, imgName);


            } else if (str.contains("供应商图片")) {
                infoFile.setFileType("company");
                uploadFileUtil.uploadLocalFile(filePath, imgName);
            } else {
                i = 1;
                System.err.println("没有对应的照片");
            }

            if (i == 0) {
                infoFile.setCreateTime(new Date());
                umsCompanyFileMapper.insertSelective(infoFile);
            }
            i = 0;
        }

    }


    @Autowired
    private UmsCompanyInfoMapper umsCompanyInfoMapper;

    public Long companyId(String compName) {
        if (StringUtils.isEmpty(compName)) {
            return null;
        }
        UmsCompanyInfoExample example = new UmsCompanyInfoExample();
        UmsCompanyInfoExample.Criteria criteria = example.createCriteria();
        criteria.andCompNameEqualTo(compName);
        example.setOrderByClause("create_time desc");
        List<UmsCompanyInfo> umsCompanyInfos = umsCompanyInfoMapper.selectByExample(example);
        if (umsCompanyInfos != null && umsCompanyInfos.size() > 0) {
            return umsCompanyInfos.get(0).getId();
        } else {
            return null;
        }
    }

    public void addOriginImg(ForestPath forestPath, String companyName, Long companyId) {

        List<String> file = getFile(forestPath.getPath());

        if (file != null && file.size() > 0) {

            Long aLong = originId(companyName, null);
            if (aLong == null) {
                System.err.println("添加图片失败--" + forestPath.getPath());
                return;
            } else {
                addImg(file, forestPath.getPath(), aLong);

            }
            return;
        }
        List<String> list = getDirectory(forestPath.getPath());
        List<UmsMemberOrigin> origin = origin(companyName);
        if (list == null || origin == null || origin.size() < list.size()) {
            return;
        }
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Long aLong = origin.get(i).getId();
                String str = list.get(i);
                if (aLong != null) {
                    List<String> file1 = getFile(forestPath.getPath() + "\\" + str);
                    if (file1 != null && file1.size() > 0) {
                        addImg(file1, forestPath.getPath() + "\\" + str, aLong);
                    }
                } else {
                    System.err.println("找不到对应的文件--" + str);

                }
            }
        }


    }

    //生产地图片
    public void addImg(List<String> file, String path, Long aLong) {
        String br = "0/1/" + aLong + "/";
        UmsMemberOrigin u = new UmsMemberOrigin();
        u.setId(aLong);
        StringBuffer bu = new StringBuffer();
        for (int i = 0; i < file.size(); i++) {
            String oldFileName = file.get(i);
            String s = OrderNo.NextOrderNo();
            String[] split = null;
            try {
                split = oldFileName.split("\\.");
            } catch (Exception e) {
                throw new RuntimeException("获取文件后缀出错!=======>" + split);
            }
            String fileName = br + s + "." + split[1];
            uploadFileUtil.uploadLocalFile(path + "\\" + oldFileName, fileName);
            if (i > 0) {
                bu.append("," + url + fileName);
            } else {
                bu.append(url + fileName);
            }
        }
        u.setImgUrl(bu.toString());
        umsMemberOriginMapper.updateByPrimaryKeySelective(u);
    }

    @Autowired
    private UmsMemberOriginMapper umsMemberOriginMapper;

    public Long originId(String compName, String originName) {
        if (StringUtils.isEmpty(compName)) {
            return null;
        }
        UmsMemberOriginExample example = new UmsMemberOriginExample();
        UmsMemberOriginExample.Criteria criteria = example.createCriteria();
        criteria.andCompNameEqualTo(compName);
        if (!StringUtils.isEmpty(originName)) {
            criteria.andOriginNameEqualTo(originName);
        }

        example.setOrderByClause("id desc");
        List<UmsMemberOrigin> umsMemberOrigins = umsMemberOriginMapper.selectByExample(example);
        if (umsMemberOrigins != null && umsMemberOrigins.size() > 0) {
            return umsMemberOrigins.get(0).getId();
        }
        return null;
    }

    public List<UmsMemberOrigin> origin(String compName) {
        if (StringUtils.isEmpty(compName)) {
            return null;
        }
        UmsMemberOriginExample example = new UmsMemberOriginExample();
        UmsMemberOriginExample.Criteria criteria = example.createCriteria();
        criteria.andCompNameEqualTo(compName);


        example.setOrderByClause("id asc");
        List<UmsMemberOrigin> umsMemberOrigins = umsMemberOriginMapper.selectByExample(example);
        return umsMemberOrigins;
    }


    public void addProductImg(ForestPath forestPath, String companyName, Long companyId) {
        List<String> directory = getDirectory(forestPath.getPath());
        if (listAll != null || listAll.size() < 1) {
            log.info("好像没有数据哦");
        }
        for (PmsProductExcelParam pms : listAll) {
            if (directory.contains(pms.getProductNo())) {
                updateFile(forestPath.getPath(), pms.getId(), pms.getProductNo());
            }
        }


    }

    @Test
    public void productImg() {
        List<String> directory = getDirectory("D:\\developerUtil\\code\\hwrj\\forest\\到数据\\上传\\石阡县猫寨农林专业合作社\\产品");
        List<PmsProduct> products = selectProduct("石阡县猫寨农林专业合作");
        if (products != null && directory != null && products.size() > 0 && directory.size() > 0 && products.size() == directory.size()) {
            for (int i = 0; i < directory.size(); i++) {
                updateFile("D:\\developerUtil\\code\\hwrj\\forest\\到数据\\上传\\石阡县猫寨农林专业合作社\\产品", products.get(i).getId(), directory.get(i));
            }
        }


    }


    public void updateFile(String path, Long along, String str) {
        String upPath = path + "\\" + str;
        String br = "0/2/" + along + "/";
        List<String> file = getFile(upPath);
        if (file != null && file.size() > 0) {
            PmsProduct p = new PmsProduct();
            p.setId(along);
            StringBuilder builder = new StringBuilder();
            for (String s : file) {
                String fs = br + OrderNo.NextOrderNo();
                String[] split = null;
                try {
                    split = s.split("\\.");
                } catch (Exception e) {
                    throw new RuntimeException("获取文件后缀出错!=======>" + split);
                }
                fs = fs + "." + split[1];
                uploadFileUtil.uploadLocalFile(upPath + "\\" + s, fs);
                if (s.contains("首图")) {
                    p.setPic(url + fs);
                } else {
                    builder.append(url + fs + ",");
                }
            }
            String st = null;
            if (!StringUtils.isEmpty(builder.toString())) {
                String s = builder.toString();
                st = s.substring(0, s.lastIndexOf(","));
            }
            p.setAlbumPics(st);
            pmsProductMapper.updateByPrimaryKeySelective(p);
        }

    }


    @Autowired
    private PmsProductMapper pmsProductMapper;

    public List<PmsProduct> selectProduct(String companyName) {
        PmsProductExample pms = new PmsProductExample();
        PmsProductExample.Criteria criteria = pms.createCriteria();

        criteria.andCompNameEqualTo(companyName);

//        criteria.andUmsCompanyInfoIdEqualTo(companyId);
        pms.setOrderByClause("id asc");
        List<PmsProduct> pmsProducts = pmsProductMapper.selectByExample(pms);
        return pmsProducts;
    }

    public List<String> getDirectory(String path) {
        List<String> paths = new ArrayList<>();
        File file = new File(path);//File类型可以是文件也可以是文件夹
        File[] fileList = file.listFiles();//将该目录下的所有文件放置在一个File类型的数组中
        for (int j = 0; j < fileList.length; j++) {
            File f = fileList[j];
            if (f.isDirectory()) {
                paths.add(f.getName());
            }
        }
        return paths;

    }

    public List<String> getFile(String path) {
        List<String> paths = new ArrayList<>();
        File file = new File(path);//File类型可以是文件也可以是文件夹
        File[] fileList = file.listFiles();//将该目录下的所有文件放置在一个File类型的数组中
        for (int j = 0; j < fileList.length; j++) {
            File f = fileList[j];
            if (f.isFile()) {
                paths.add(f.getName());
            }
        }
        return paths;
    }

    public String addCompanyInfo(File pdf, String companyName) {
        try {
//                    File pdf = fileList[i];
            System.out.println(pdf.getPath());
            FileInputStream fileInputStream = null;
            fileInputStream = new FileInputStream(pdf);
            MultipartFile multipartFile = new MockMultipartFile(pdf.getName(), pdf.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
//                        String url = ossFileUtils.upload(multipartFile.getOriginalFilename(), multipartFile);
            String name = importExcel(multipartFile, companyName);
            return name;
        } catch (Exception e) {
            System.out.println(e.getMessage());

        }
        return null;

    }

    @Autowired
    private UmsCompanyService umsCompanyService;

    @Autowired
    private UmsMemberOriginService umsMemberOriginService;


    @Transactional(rollbackFor = Exception.class)
    public String importExcel(MultipartFile file, String companyName) throws Exception {

        //导入公司
        String companyId = null;
        List<UmsCompanyInfoExcel> listAll = new ArrayList<>();
        List<Object> list = EasyExcelUtil.readExcel(file, new UmsCompanyInfoExcel(), 1, 2);
        if (list != null && list.size() > 0) {
            for (Object o : list) {
                UmsCompanyInfoExcel umsCompanyInfoExcel = (UmsCompanyInfoExcel) o;
                umsCompanyInfoExcel.setCreateId(0l);
                companyId = umsCompanyInfoExcel.getCompName();
                LagLatEntity lagLat = companyLatLagGet.getLagLat(umsCompanyInfoExcel.getCityId(), umsCompanyInfoExcel.getCountyId(), umsCompanyInfoExcel.getDetailAddress());
                if (lagLat != null) {
                    umsCompanyInfoExcel.setLatitude(new BigDecimal(lagLat.getLat()));
                    umsCompanyInfoExcel.setLongitude(new BigDecimal(lagLat.getLag()));
                }
                listAll.add(umsCompanyInfoExcel);
            }
        }
        umsCompanyService.importExcel(listAll);

        if (StringUtils.isEmpty(companyId)) {
            return null;
        }
        //导入生产地
        importOriginExcel(file, companyId);

        //导入商品
        importBasic(file);

        return companyId;
    }


    @Autowired
    private ImportExcelEventListener importExcelEventListener;

    public void importOriginExcel(MultipartFile file, String companyName) {
        List<UmsMemberOriginExcel> listAll = new ArrayList<>();
        if (file != null) {
            List<Object> list = null;
            try {
                list = EasyExcelUtil.readExcel(file, new UmsMemberOriginExcel(), 2, 2);
            } catch (IOException e) {
                //e.printStackTrace();
                throw new RuntimeException("上传文件错误!");
            }
            if (list != null && list.size() > 0) {
                for (Object obj : list) {
                    UmsMemberOriginExcel excel = (UmsMemberOriginExcel) obj;
                    excel.setCreateId(1);
                    excel.setState(0);
                    LagLatEntity lagLat = companyLatLagGet.getLagLat(excel.getCityName(), excel.getCountyName(), excel.getDetailAddress());
                    if (lagLat != null) {
                        excel.setLatitude(lagLat.getLat());
                        excel.setLongitude(lagLat.getLag());
                    }
                    excel.setCompName(companyName);
                    listAll.add(excel);
                }
            }
        }
        int saveNum = 0;
        if (listAll != null && listAll.size() > 0) {
            int batchNum = 500;
            if (listAll.size() > batchNum) {
                List<UmsMemberOriginExcel> list = listAll.subList(0, batchNum);
                saveNum = umsMemberOriginService.batchSave(list);
                //if (saveNum > 0){ //存在前面数据已存在情况
                //异步导入
                importExcelEventListener.batchSaveOriginExcel(listAll.subList(batchNum, listAll.size()));
                log.info("正在导入数据，请稍后刷新!");
                //}
            }
            saveNum = umsMemberOriginService.batchSave(listAll);
            if (saveNum < 1) {
                log.info("导入数据已存在，请勿重复导入");
            }
        }

    }

    @Autowired
    private PmsProductExcelDao productExcelDao;

    public void importBasic(MultipartFile file) throws IOException {


        listAll = new ArrayList<>();
        if (file != null) {
            List<Object> list = null;
            try {
                list = EasyExcelUtil.readExcel(file, new PmsProductExcel(), 3, 2);
            } catch (IOException e) {
                //e.printStackTrace();
                throw new RuntimeException("上传文件错误!");
            }
            if (list != null && list.size() > 0) {
                for (Object obj : list) {
                    PmsProductExcel excel = (PmsProductExcel) obj;
                    PmsProductExcelParam pmsProductExcelParam = addData(excel);
                    listAll.add(pmsProductExcelParam);
                }
            }
        }
        List<PmsBrand> bandlist = new ArrayList<>();
        //去除品牌里面的空格以及空字符
        for (PmsProductExcelParam pmsProductExcelParam : listAll) {
            String brandName = pmsProductExcelParam.getBrandName();
            pmsProductExcelParam.setBrandName(MyStringUtils.replaceBlank(brandName));
        }
        log.info("开始插入品牌数据");
        List<String> BandNames = listAll.stream().map(PmsProductExcelParam::getBrandName).distinct().collect(Collectors.toList());
        for (String bandName : BandNames) {
            PmsBrand pmsBrand = new PmsBrand();
            pmsBrand.setName(bandName);
            pmsBrand.setFirstLetter(ChineseCharToEn.getAllFirstLetter(bandName));
            pmsBrand.setShowStatus(1);
            pmsBrand.setSort(1);
            pmsBrand.setFactoryStatus(1);
            pmsBrand.setProductCount(listAll.size());
            pmsBrand.setCreateId((long) 1);
            pmsBrand.setCreateTime(new Date());
            bandlist.add(pmsBrand);
        }
        if (BandNames.size() > 0) {
            productExcelDao.saveBrandData(bandlist);
        }
        log.info("开始插入商品数据");
        if (listAll.size() > 0) {
            log.info(JSONObject.toJSONString(listAll));
            productExcelDao.saveData(listAll);
        }
        List<String> compNames = listAll.stream().map(PmsProductExcelParam::getUmsCompanyInfo).distinct().collect(Collectors.toList());
        if (compNames.size() > 0) {
            //更新大小类以及品牌生产地
            updateProductType(compNames);
        }

    }

    //更新大小类
    public void updateProductType(List<String> compName) {
        List<Long> ids = listAll.stream().map(PmsProductExcelParam::getId).distinct().collect(Collectors.toList());
        productExcelDao.updateBrand(compName, ids);
        productExcelDao.updateBigType(compName, ids);
        productExcelDao.updateSimType(compName, ids);
        productExcelDao.updateMemberOrigin(compName, ids);
        productExcelDao.updateBrandComp(compName, ids);
    }


    private PmsProductExcelParam addData(PmsProductExcel pmsProductExcel) {

        PmsProductExcelParam pmsProductExcelParam = new PmsProductExcelParam();
        BeanUtils.copyProperties(pmsProductExcel, pmsProductExcelParam);
        //名称
        String name = pmsProductExcel.getName();
        //价格
        BigDecimal price = pmsProductExcel.getPrice();
        //标题
        pmsProductExcelParam.setDetailTitle(name);
        //笔记
        pmsProductExcelParam.setNote(name);
        //关键字
        pmsProductExcelParam.setKeywords(name);

        String description = replaceBlank(pmsProductExcel.getDescription());

        pmsProductExcelParam.setUmsCompanyInfoId(companyId(pmsProductExcel.getUmsCompanyInfo()));

        //商品描述
        pmsProductExcelParam.setDescription(description);
        //简述
        pmsProductExcelParam.setSubTitle(description);
        //使用说明
        String instructions = replaceBlank(pmsProductExcel.getInstructions());
        //默认文本
        pmsProductExcelParam.setDetailDesc(instructions);
        //web网页显示
        pmsProductExcelParam.setDetailHtml(instructions);
        //手机网页显示
        pmsProductExcelParam.setDetailMobileHtml(instructions);
        //市场价
        pmsProductExcelParam.setOriginalPrice(price);
        //创建人 admin 1
        pmsProductExcelParam.setCreateUser((long) 1);
        //创建时间
        pmsProductExcelParam.setCreateTime(new Date());
        return pmsProductExcelParam;
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }


}
