package com.hwrj.cloud.admin;


import com.hwrj.cloud.admin.dao.PmsProductExcelDao;
import com.hwrj.cloud.admin.dto.param.PmsProductExcel;
import com.hwrj.cloud.admin.dto.param.PmsProductExcelParam;
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.PmsProductService;
import com.hwrj.cloud.admin.service.UmsCompanyService;
import com.hwrj.cloud.admin.service.UmsMemberOriginService;
import com.hwrj.cloud.admin.util.EasyExcelUtil;
import com.hwrj.cloud.admin.util.OrderNo;
import com.hwrj.cloud.admin.util.UploadFileUtil;
import com.hwrj.cloud.common.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.StringUtils;
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;

@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AdminApplication.class)
public class FirstUploadForestData {

    @Autowired
    private UploadFileUtil uploadFileUtil;

private int i = 1;

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


    @Test
    public void readFile(){
        i++;

        if (i>2){
            return;
        }
        String filepath = "D:\\developerUtil\\code\\hwrj\\forest\\到数据\\待上传\\文件上传";//D盘下的file文件夹的目录
        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){
            excelPut(path);
        }


    }

    /**
     * 上传公司的excel
     * @param forestPath
     */
    public void 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;
        }
        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());
            }
        }


    }

    @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);
            infoFile.setFileUrl(url+br+s);
            if (str.contains("公众号二维码")){
                infoFile.setFileType("qrl");
                uploadFileUtil.uploadLocalFile(path+"\\"+str,br+s);
            }else if (str.contains("logo")){
                infoFile.setFileType("logo");
                uploadFileUtil.uploadLocalFile(path+"\\"+str,br+s);

            }else if (str.contains("供应商资质")){
                infoFile.setFileType("cert");
                uploadFileUtil.uploadLocalFile(path+"\\"+str,br+s);


            }else if (str.contains("供应商图片")){
                infoFile.setFileType("company");
                uploadFileUtil.uploadLocalFile(path+"\\"+str,br+s);


            }else{
                i=1;
                System.err.println("没有对应的照片");
            }

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

    }


    @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;
        }
    }

    @Test
    public void getImg(){
        if (i>1){
            return;
        }
        i++;
        ForestPath fs = new ForestPath();
        fs.setCompanyName("威宁县乌蒙绿色产业有限责任公司");
        fs.setPath("D:\\developerUtil\\code\\hwrj\\forest\\到数据\\上传\\威宁县乌蒙绿色产业有限责任公司\\生产地");
        addOriginImg(fs,"威宁县乌蒙绿色产业有限责任公司",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 s = OrderNo.NextOrderNo();
            uploadFileUtil.uploadLocalFile(path+"\\"+file.get(i),br+s);
            if (i>0){
                bu.append(","+url+br+s);
            }else {
                bu.append(url+br+s);
            }
        }
        u.setImgUrl(bu.toString());
        umsMemberOriginMapper.updateByPrimaryKeySelective(u);
    }

    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;
    }

    @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 void addProductImg(ForestPath forestPath,String companyName,Long companyId){
        List<String> directory = getDirectory(forestPath.getPath());
        Long aLong = companyId(companyName);
        List<PmsProduct> products = selectProduct(companyName);
        if (products != null&&directory != null&& products.size()>0&&directory.size()>0&&products.size()==directory.size()){
            for (int i = 0;i<directory.size();i++){
                updateFile(forestPath.getPath(),products.get(i).getId(),directory.get(i));
            }
        }




    }

    @Test
    public void productImg(){
        List<String> directory = getDirectory("D:\\developerUtil\\code\\hwrj\\forest\\到数据\\上传\\石阡县猫寨农林专业合作社\\产品");
        Long aLong = 111l;
        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();
                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;

    @Autowired
    private PmsProductService pmsProductService;


    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();
                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 GlobalException(1,"上传文件错误");
            }
            if(list != null && list.size() > 0){
                for(Object obj : list){
                    UmsMemberOriginExcel excel = (UmsMemberOriginExcel) obj;
                    excel.setCreateId(1);
                    excel.setState(0);
                    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 {

//        PmsProductExcelListener basicExcelListener = new PmsProductExcelListener(productExcelDao,null);
//        ExcelReader excelReader = null;
//        try {
//            excelReader = EasyExcel.read(file.getInputStream()).build();
//            ReadSheet readSheet3 =
//                    EasyExcel.readSheet(2).head(PmsProductExcel.class).registerReadListener(basicExcelListener).headRowNumber(2).build();
//            // 这里注意 一定要把sheet1 sheet2 一起传进去，不然有个问题就是03版的excel 会读取多次，浪费性能
//            excelReader.read(readSheet3);
//        } finally {
//            if (excelReader != null) {
//                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
//                excelReader.finish();
//            }
//        }

        List<PmsProductExcelParam> 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 GlobalException(1,"上传文件错误");
            }
            if(list != null && list.size() > 0){
                for(Object obj : list){
                    PmsProductExcel excel = (PmsProductExcel) obj;
                    PmsProductExcelParam pmsProductExcelParam = addData(excel);
                    listAll.add(pmsProductExcelParam);
                }
            }
        }
        log.info("sssss");
        productExcelDao.saveData(listAll);

    }




    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;
    }




}
