package com.goafanti.common.controller;

import com.goafanti.admin.service.AdminService;
import com.goafanti.admin.service.AttachmentService;
import com.goafanti.common.bo.Error;
import com.goafanti.common.bo.OutUser;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.dao.TOrderMidMapper;
import com.goafanti.common.dao.TOrderNewMapper;
import com.goafanti.common.enums.UserType;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.TOrderNew;
import com.goafanti.common.model.User;
import com.goafanti.common.service.DistrictGlossoryService;
import com.goafanti.common.service.IndustryCategoryService;
import com.goafanti.common.utils.*;
import com.goafanti.common.utils.excel.FileUtils;
import com.goafanti.common.utils.excel.NewExcelUtil;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.core.websocket.SystemWebSocketHandler;
import com.goafanti.fragment.service.FragmentService;
import com.goafanti.order.service.OrderProjectService;
import com.goafanti.user.service.UserService;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.socket.TextMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@Controller
@RequestMapping("/open")
public class TestPublicController extends CertifyApiController {

    @Value(value = "${upload.path}")
    private String		uploadPath			= null;

    private String		targePath			="F:/data/public/upload/new_order_file/";

    @Autowired
    private TOrderNewMapper tOrderNewMapper;


    private static final Logger logger	= LoggerFactory.getLogger(TestPublicController.class);

    @RequestMapping("/pushOrderList")
    @Transactional
    public Result pushOrder() {
      Result res= new Result();
        List<TOrderNew> list = tOrderNewMapper.selectgetAll();
        for (TOrderNew t : list) {
            if (StringUtils.isNotBlank(t.getContractPictureUrl())||
                    StringUtils.isNotBlank(t.getAgreementUrl())||
                    StringUtils.isNotBlank(t.getServiceContent())){
                TOrderNew neworder=new TOrderNew();
                neworder.setOrderNo(t.getOrderNo());
                try {
                    if (StringUtils.isNotBlank(t.getContractPictureUrl())){
                        String str= null;
                        str = moveImg(t.getContractPictureUrl(),t.getOrderNo(),0,uploadPath);
                        neworder.setContractPictureUrl(str);
                    }
                    if (StringUtils.isNotBlank(t.getAgreementUrl())){
                        String str=moveImg(t.getAgreementUrl(),t.getOrderNo(),1,uploadPath);
                        neworder.setAgreementUrl(str);
                    }
                    if (StringUtils.isNotBlank(t.getServiceContent())){
                        String str=moveImg(t.getServiceContent(),t.getOrderNo(),2,uploadPath);
                        neworder.setServiceContent(str);
                    }
                } catch (Exception e) {
                    logger.debug("订单编号["+t.getOrderNo()+"]移动异常..."+e.getLocalizedMessage());
                    continue;
                }
                logger.debug("订单编号["+t.getOrderNo()+"]移动成功\n"+t.getContractPictureUrl()+"\n"+neworder.getContractPictureUrl());
                tOrderNewMapper.updateByPrimaryKeySelective(neworder);
            }
        }
        return res;
    }

    @RequestMapping(value = "/pushOrder" ,method = RequestMethod.GET)
    public Result pushOrder(String orderNo) {
        Result res= new Result();
        TOrderNew t = tOrderNewMapper.selectByPrimaryKey(orderNo);
        TOrderNew neworder=new TOrderNew();
        neworder.setOrderNo(t.getOrderNo());
        try {
            if (StringUtils.isNotBlank(t.getContractPictureUrl())){
                String str= null;
                    str = moveImg(t.getContractPictureUrl(),t.getOrderNo(),0,uploadPath);
                neworder.setContractPictureUrl(str);
            }
            if (StringUtils.isNotBlank(t.getAgreementUrl())){
                String str=moveImg(t.getAgreementUrl(),t.getOrderNo(),1,uploadPath);
                neworder.setAgreementUrl(str);
            }
            if (StringUtils.isNotBlank(t.getServiceContent())){
                String str=moveImg(t.getServiceContent(),t.getOrderNo(),2,uploadPath);
                neworder.setServiceContent(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        tOrderNewMapper.updateByPrimaryKeySelective(neworder);
        return res;
    }



    /**

     * @param i 0订单合同
     * @param uploadPath
     * @return
     */

    private static String moveImg(String attURL ,String orderNo,Integer i,String uploadPath) throws Exception {
        StringBuffer str =new StringBuffer();
        String[] split = attURL.split(",");
        for (String s : split) {
            String url="";
            if (s.contains("/")){
                url=s.substring(s.lastIndexOf("/"));
            }else {
                url=s.substring(s.lastIndexOf("\\"));
            }
            String newURL="";
            String frontName="/new_order_file/";
            String rearName="";
            if (i==0){
                rearName="/contract";
            }else if (i==1){
                rearName="/agreement";

            }else if (i==2){
                rearName="/content";
            }
            newURL=frontName+orderNo+rearName;
            moveFile(s, newURL,uploadPath,url);
            str.append(newURL+url).append(",");
        }
        return str.substring(0,str.length()-1);
    }



    /**
     *
     * @param useURL 旧地址
     * @param newURL 新地址
     */
    private static int moveFile(String useURL, String newURL,String uploadPath,String url) throws Exception {
        String targePath=uploadPath+newURL;
        useURL=uploadPath+useURL;
        String targeUrl=targePath+url;
        //目标文件夹路径（没有会自动创建）
        File targetFile = new File(targePath);
        File srcFile = new File(useURL);
        if (!srcFile.exists()){
            throw new BusinessException("文件不存在");
        }
        File destFile = new File(targeUrl);
        //创建文件件
        createFile(targetFile);
        //复制文件
        copyFile(srcFile,destFile);
        //新地址有则删除旧数据删除源文件
        if (destFile.exists()){
            srcFile.delete();
        }
        return 1;
    }

    private static void createFile(File file) {
        if (file.exists()) {
        } else {
            if (!file.exists()) {
                //创建上级目录
                file.mkdirs();
            }
        }
    }

    private static void copyFile(File srcFile,File destFile) throws IOException {
        //该方法为复制文件，srcFile是原文件所在地址，destFile是目标文件所在地址

        File[] fileArray1 = srcFile.listFiles();
        File[] fileArray2 = destFile.listFiles();

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = bis.read(bys)) != -1)
        {
            bos.write(bys, 0, len);
        }
        bos.close();
        bis.close();
    }
}
