/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workclientinfo.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.serialnum.service.SerialNumTplService;
import com.jeeplus.modules.sys.dao.AreaDao;
import com.jeeplus.modules.sys.entity.Area;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workclientinfo.dao.WorkClientBankDao;
import com.jeeplus.modules.workclientinfo.dao.WorkClientInfoDao;
import com.jeeplus.modules.workclientinfo.dao.WorkClientLinkmanDao;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workclientinfo.entity.WorkClientBank;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workclientinfo.entity.WorkClientLinkman;
import com.jeeplus.modules.workcontractinfo.dao.WorkContractInfoDao;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workreimbursement.utils.VarStr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 客户管理Service
 * @author 丁旭
 * @version 2017-03-20
 */
@Service
@Transactional(readOnly = true)
public class WorkClientInfoService extends CrudService<WorkClientInfoDao, WorkClientInfo> {

	@Autowired
	private WorkClientLinkmanDao workClientLinkmanDao;
	@Autowired
	private WorkClientBankDao workClientBankDao;
	@Autowired
	private WorkClientAttachmentDao workClientAttachmentDao;
    @Autowired
    private WorkContractInfoDao workContractInfoDao;
    @Autowired
    private WorkClientInfoDao workClientInfoDao;
    @Autowired
    private SerialNumTplService serialNumTplService;

    @Autowired
    private AreaDao areaDao;

    public WorkClientInfo get(String id) {
	    if(StringUtils.isBlank(id)){
	        return new WorkClientInfo();
        }
        WorkClientInfo workClientInfo = super.get(id);
		//获取一个客户所关联的联系人信息
//        if(StringUtils.isNotBlank(wld[0])){
//            WorkClientLinkman workClientLinkman = workClientLinkmanDao.get(wld[0]);
//            workClientInfo.setWorkClientLinkman(workClientLinkman);
//        }
        if(workClientInfo != null){
            workClientInfo.setWorkClientLinkmanList(workClientLinkmanDao.findList(new WorkClientLinkman(workClientInfo)));
            //获取一个客户关联的银行信息
            workClientInfo.setWorkClientBankList(workClientBankDao.findList(new WorkClientBank(workClientInfo)));
            //获取附件信息
            WorkClientAttachment workClientAttachment = new WorkClientAttachment();
            workClientAttachment.setAttachmentId(id);
            workClientAttachment.setAttachmentFlag(VarStr.attachmentFlag[0]);
            workClientInfo.setWorkAttachments(workClientAttachmentDao.findList(workClientAttachment));

            //多个联系人
            List<WorkClientLinkman> linkman = workClientLinkmanDao.findByClientId(workClientInfo.getId());
//        workClientInfo.setWorkClientLinkman(linkman);
            workClientInfo.setWorkClientLinkmanList(linkman);
            WorkClientAttachment attchment = new WorkClientAttachment();
            attchment.setAttachmentId(workClientInfo.getId());
            List<WorkClientAttachment> attachments = workClientAttachmentDao.findList(attchment);
            workClientInfo.setWorkAttachments(attachments);
        }
		return workClientInfo;
	}

    /**
     * 获取客户列表信息
     * @param workClientInfo
     * @return
     */
	public List<WorkClientInfo> findList(WorkClientInfo workClientInfo) {
        workClientInfo.setDelFlag("0");
		return super.findList(workClientInfo);
	}

    /**
     * 获取客户联系人列表信息
     * @return
     */
    public List<WorkClientLinkman> findByClientId(String clientId) {
        return workClientLinkmanDao.findByClientId(clientId);
    }


    public List<WorkClientLinkman> findLinkmanList(String projectId) {
        WorkClientLinkman linkman = new WorkClientLinkman();
        linkman.setProjectId(projectId);
        return workClientLinkmanDao.findListByProjectId(linkman);
    }

    /**
     * 获取联系人列表信息
     * @param workClientInfo
     * @return
     */
	public List<WorkClientLinkman> findLinkmanList(WorkClientInfo workClientInfo)  {
		return workClientLinkmanDao.findList(new WorkClientLinkman(workClientInfo));
	}
    /**
     * 获取联系人列表信息
     * @param workClientLinkman
     * @return
     */
	public List<WorkClientLinkman> findByClient(WorkClientLinkman workClientLinkman)  {
		return workClientLinkmanDao.findByClient(workClientLinkman);
	}
    /**
     * 获取合同信息
     */
    public List<WorkContractInfo> findCIF(WorkClientInfo workClientInfo)  {
        return workContractInfoDao.findList(new WorkContractInfo(workClientInfo));
    }
    /**
     * 获取银行开户信息
     * @param workClientInfo
     * @return
     */
    public List<WorkClientBank> findBankList(WorkClientInfo workClientInfo)  {
        return workClientBankDao.findListByClient(new WorkClientBank(workClientInfo));
    }

    /**
     * 获取附件列表信息
     * @param workClientInfo
     * @return
     */
    public List<WorkClientAttachment> findAttachmentList(WorkClientInfo workClientInfo)  {
        WorkClientAttachment workClientAttachment = new WorkClientAttachment();
        workClientAttachment.setAttachmentId(workClientInfo.getId());
        workClientAttachment.setAttachmentFlag(VarStr.attachmentFlag[0]);
        return workClientAttachmentDao.findList(workClientAttachment);
    }

    /**
     * 获取一个客户信息
     * @param page 分页对象
     * @param workClientInfo
     * @return
     */
    public Page<WorkClientInfo> findPage(Page<WorkClientInfo> page, WorkClientInfo workClientInfo) {
//        workClientInfo.setOfficeId(UserUtils.getSelectOffice().getId());
//        workClientInfo.getSqlMap().put("dsf", dataScopeFilter(workClientInfo.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_CLIENT_INFO.getValue()));
        long t1 = System.currentTimeMillis();
        int count = workClientInfoDao.queryCount(workClientInfo);
        page.setCount(count);
        long t2 = System.currentTimeMillis();
        logger.info("查询客户总数耗时：{}",t2-t1);
        page.setCountFlag(false);
        workClientInfo.setPage(page);
        List<WorkClientInfo> list = findList(workClientInfo);
        long t3 = System.currentTimeMillis();
        logger.info("查询客户列表耗时：{}",t3-t2);
        if(list!=null && list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                WorkClientInfo entity = list.get(i);
                List<WorkClientLinkman> linkmanList = findLinkmanList(entity);
                entity.setWorkClientLinkmanList(linkmanList);
                if(linkmanList!=null && linkmanList.size()>0){
                    StringBuilder builder = new StringBuilder();
                    for (int j = 0; j < linkmanList.size(); j++) {
                        builder.append(linkmanList.get(j).getName());
                        if(j<linkmanList.size()-1){
                            builder.append(",");
                        }
                    }
                    entity.setLinkManNames(builder.toString());
                }
                List<WorkClientBank> bankList = findBankList(entity);
                entity.setWorkClientBankList(bankList);
            }
        }
        long t4 = System.currentTimeMillis();
        logger.info("查询客户详情耗时：{}",t4-t3);
        logger.info("查询客户总耗时：{}",t4-t1);
        page.setList(list);
        return page;
    }

    /**
     * 获取客户关联的联系人信息
     * @param page
     * @param workClientInfo
     * @return
     */
	public Page<WorkClientLinkman> findLinkmanPage(Page<WorkClientLinkman> page, WorkClientInfo workClientInfo) {
		WorkClientLinkman linkman = new WorkClientLinkman(workClientInfo);
		linkman.setPage(page);
		page.setList(workClientLinkmanDao.findList(linkman));
		return page;
	}

    /**
     * 获取客户关联的银行信息
     * @param page
     * @param workClientInfo
     * @return
     */
	public Page<WorkClientBank> findBankPage(Page<WorkClientBank> page,WorkClientInfo workClientInfo){
	    WorkClientBank workClientBank = new WorkClientBank(workClientInfo);
	    workClientBank.setPage(page);
	    page.setList(workClientBankDao.findList(workClientBank));
	    return page;
    }

    /**
     * 获取附件列表信息
     * @param page
     * @param workClientInfo
     * @return
     */
    public Page<WorkClientAttachment> findAttachmentPage(Page<WorkClientAttachment> page,WorkClientInfo workClientInfo){
        String id = workClientInfo.getId();
        WorkClientAttachment workClientAttachment = new WorkClientAttachment();
        workClientAttachment.setAttachmentId(id);
        workClientAttachment.setPage(page);
        workClientAttachment.setAttachmentFlag(VarStr.attachmentFlag[0]);
        page.setList(workClientAttachmentDao.findList(workClientAttachment));
        return page;
    }

    /**
     * 保存或修改信息
     * @param workClientInfo
     */
	@Transactional(readOnly = false)
	public void save(WorkClientInfo workClientInfo) {
	    User user = UserUtils.getUser();
        long t1 = System.currentTimeMillis();
        Area area = workClientInfo.getArea();
        area = areaDao.get(area.getId());
        workClientInfo.setArea(area);
        workClientInfo.setNumber(serialNumTplService.genSerialNum(user.getCompany(),"50"));
		super.save(workClientInfo);
        long t2 = System.currentTimeMillis();
        logger.info("保存客户主表耗时：{}",t2-t1);
		//联系人信息
		for (WorkClientLinkman workClientLinkman : workClientInfo.getWorkClientLinkmanList()){
			if (workClientLinkman.getId() == null){
				continue;
			}
			if (WorkClientLinkman.DEL_FLAG_NORMAL.equals(workClientLinkman.getDelFlag())){
                workClientLinkman.setClientId(workClientInfo);
				if (StringUtils.isBlank(workClientLinkman.getId())){
					workClientLinkman.preInsert();
					workClientLinkmanDao.insert(workClientLinkman);
				}else{
					workClientLinkman.preUpdate();
					workClientLinkmanDao.update(workClientLinkman);
				}
			}else{
				workClientLinkmanDao.delete(workClientLinkman);
			}
		}
        long t3 = System.currentTimeMillis();
        logger.info("保存客户联系人耗时：{}",t3-t2);
		//开户信息
        for (WorkClientBank workClientBank : workClientInfo.getWorkClientBankList()){
            if (workClientBank.getId() == null){
                continue;
            }
            if (WorkClientBank.DEL_FLAG_NORMAL.equals(workClientBank.getDelFlag())){
                workClientBank.setClientId(workClientInfo);
                if (StringUtils.isBlank(workClientBank.getId())){
                    workClientBank.preInsert();
                    workClientBankDao.insert(workClientBank);
                }else{
                    workClientBank.preUpdate();
                    workClientBankDao.update(workClientBank);
                }
            }else{
                workClientBankDao.delete(workClientBank);
            }
        }
        long t4 = System.currentTimeMillis();
        logger.info("保存客户银行信息耗时：{}",t4-t3);
        //附件信息
        for (WorkClientAttachment workClientAttachment : workClientInfo.getWorkAttachments()){
            if (workClientAttachment.getId() == null){
                continue;
            }
            if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())){
                workClientAttachment.setAttachmentId(workClientInfo.getId());
                workClientAttachment.setAttachmentFlag("44");
                workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
                if (StringUtils.isBlank(workClientAttachment.getId()) || "null".equals(workClientAttachment.getId())){
                    workClientAttachment.preInsert();
                    workClientAttachmentDao.insert(workClientAttachment);
                }else{
                    workClientAttachment.preUpdate();
                    workClientAttachmentDao.update(workClientAttachment);
                }
            }else{
                workClientAttachmentDao.delete(workClientAttachment);
            }
        }
        logger.info("保存客户耗时：{}",System.currentTimeMillis()-t1);

	}

    /**
     * 该客户是否被引用
     */
    public boolean getUsedCount(WorkClientInfo workClientInfo){
        //WorkBidProject
        //WorkBidingProject
        //WorkEngineeringProject
        //WorkFullManage
        //work_contract_info
        //被引用过的客户信息不可以被删除，但可以修改。 没有被引用过的客户信息可以删除
        //投标、招标、工程咨询、全过程、合同
        String clientId = workClientInfo.getId();
        int count = 0;
        count += workClientInfoDao.getBeUsedCount1(clientId);
        if(count>0){
            return true;
        }
        count += workClientInfoDao.getBeUsedCount2(clientId);
        if(count>0){
            return true;
        }
        count += workClientInfoDao.getBeUsedCount3(clientId);
        if(count>0){
            return true;
        }
        count += workClientInfoDao.getBeUsedCount4(clientId);
        if(count>0){
            return true;
        }
        count += workClientInfoDao.getBeUsedCount5(clientId);
        if(count>0){
            return true;
        }
        return false;
    }


    /**
     * 删除客户的所有信息
     * @param workClientInfo
     */
	@Transactional(readOnly = false)
	public void delete(WorkClientInfo workClientInfo){
		super.delete(workClientInfo);   //删除客户信息
		workClientLinkmanDao.delete(new WorkClientLinkman(workClientInfo)); //删除联系人信息
		workClientBankDao.delete(new WorkClientBank(workClientInfo)); //删除银行信息
        WorkClientAttachment workClientAttachment = new WorkClientAttachment();
        workClientAttachment.setAttachmentId(workClientInfo.getId());
        workClientAttachment.setAttachmentFlag(VarStr.attachmentFlag[0]);
        workClientAttachmentDao.delete(workClientAttachment); //删除附件信息


	}


    /**
     * 上传多个文件
     * @param request
     * @param upload_files
     */
    public  List<WorkClientAttachment> uploadFile(HttpServletRequest request, MultipartFile[] upload_files, String ClientId,String attachmentFlag){
        String  uploadFolder = request.getSession().getServletContext().getRealPath("local_upload/notify/"+System.currentTimeMillis());
        new File(uploadFolder).mkdirs();
        InputStream inputStream = null;
        List<String> imgList = new ArrayList<>();
        List<WorkClientAttachment> workClientAttachments = new ArrayList<>();
        if(upload_files!=null && upload_files.length>0){
            for(int i=0;i<upload_files.length;i++){
                try {
                    if (upload_files[i] == null || upload_files[i].getSize() == 0)
                        continue;
                    String imageName = System.nanoTime() + upload_files[i].getOriginalFilename();
                    String imageNewName = uploadFolder + "/" + imageName;
                    imgList.add(imageNewName);
                    upload_files[i].transferTo(new File(imageNewName));
                    inputStream = new FileInputStream(new File(imageNewName));
                    OSSClientUtil ossUtil = new OSSClientUtil();
                    String suffix = imageNewName.substring(imageNewName.lastIndexOf("."));
                    String name = System.nanoTime() + suffix;
                    ossUtil.uploadFile2OSS(inputStream, Global.getNotifyData(), name);
                    WorkClientAttachment workClientAttachment = new WorkClientAttachment();
                    workClientAttachment.setId("");
                    workClientAttachment.setUrl(Global.getAliyunUrl() + "/" + Global.getNotifyData() + name);
                    workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
                    workClientAttachment.setAttachmentName(upload_files[i].getOriginalFilename());
                    workClientAttachment.setAttachmentId(ClientId);
                    workClientAttachment.setType(suffix);
                    workClientAttachments.add(workClientAttachment);
                    workClientAttachment.setAttachmentFlag(attachmentFlag);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    try {
                        if (inputStream != null)
                            inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return workClientAttachments;
    }

    /**
     * 上传单个文件
     * @param request
     * @param upload_files
     */
    public  WorkClientAttachment uploadFileSingle(HttpServletRequest request, CommonsMultipartFile upload_files, String ClientId, String attachmentFlag){
        String  uploadFolder = request.getSession().getServletContext().getRealPath("local_upload/notify/"+System.currentTimeMillis());
        InputStream inputStream = null;
        WorkClientAttachment workClientAttachment = new WorkClientAttachment();
        try {
            new File(uploadFolder).mkdirs();
            String imageName = System.nanoTime()+upload_files.getOriginalFilename();
            String imageNewName = uploadFolder+"/"+imageName;
            upload_files.transferTo(new File(imageNewName));
            inputStream = new FileInputStream(new File(imageNewName));
            OSSClientUtil ossUtil = new OSSClientUtil();
            String suffix = imageNewName.substring(imageNewName.lastIndexOf("."));
            String name = System.nanoTime() + suffix;
            ossUtil.uploadFile2OSS(inputStream, Global.getNotifyData(), name);
            workClientAttachment.setUrl(Global.getAliyunUrl()+"/"+Global.getNotifyData()+name);
            workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
            workClientAttachment.setAttachmentName(upload_files.getOriginalFilename()); //name
            workClientAttachment.setAttachmentId(ClientId);
            workClientAttachment.setType(suffix);
            workClientAttachment.setAttachmentFlag(attachmentFlag);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return workClientAttachment;
    }
    /**
     * 删除附件
     * @return
     */
    @Transactional(readOnly = false)
    public String deleteAttachment(WorkClientAttachment  workClientAttachment){
        int i = workClientAttachmentDao.deleteByLogic(workClientAttachment);
        String str = (i > 0)?"删除成功":"删除失败";
        return str;
    }

    /**
     * 保存或修改信息
     * @param workClientAttachment
     */
    @Transactional(readOnly = false)
    public String save(WorkClientAttachment workClientAttachment) {
        int update = 0;
        if(!workClientAttachment.getIsNewRecord()){
            workClientAttachment.preUpdate();
            update = workClientAttachmentDao.update(workClientAttachment);
        }else{
            workClientAttachment.preInsert();
            update = workClientAttachmentDao.insert(workClientAttachment);
        }
        String str = (update > 0)?"上传成功":"上传失败";
        return str;
    }

    /**
     *
     * @MethodName: deleteFile
     * @Description: 单文件删除
     * @param fileUrl 需要删除的文件url
     * @return boolean 是否删除成功
     */
    @Transactional(readOnly = false)
    public void deleteFile(String fileUrl,String attach){
        new OSSClientUtil().deleteSingleObject(fileUrl);
        workClientAttachmentDao.delete(workClientAttachmentDao.get(attach));
    }


    /**
     * 获取客户关联的联系人信息
     * @param page
     * @return
     */
    public Page<WorkClientLinkman> findLinkmanPage(Page<WorkClientLinkman> page, WorkClientLinkman linkman) {
        linkman.setPage(page);
        page.setList(workClientLinkmanDao.findList(linkman));
        return page;
    }

    /**
     * 保存或修改信息
     * @param workClientInfo
     */
    @Transactional(readOnly = false)
    public void saveImport(WorkClientInfo workClientInfo) {
        Area area = workClientInfo.getArea();
        area = areaDao.get(area.getId());
        workClientInfo.setArea(area);
        super.save(workClientInfo);
        //联系人信息
        for (WorkClientLinkman workClientLinkman : workClientInfo.getWorkClientLinkmanList()){
            workClientLinkman.preInsert();
            workClientLinkman.setClientId(workClientInfo);
            workClientLinkmanDao.insert(workClientLinkman);
        }
        //开户信息
        for (WorkClientBank workClientBank : workClientInfo.getWorkClientBankList()){
            workClientBank.preInsert();
            workClientBank.setClientId(workClientInfo);
            workClientBankDao.insert(workClientBank);
        }

    }

    public int countByUscCode(String uscCode) {
        return dao.countByUscCode(uscCode);
    }

    public Page<WorkClientBank> findBankInfoPage(Page<WorkClientBank> page, WorkClientBank workClientBank) {
        workClientBank.setPage(page);
        page.setOrderBy("b.update_date");
        page.setList(workClientBankDao.findList(workClientBank));
        return page;
    }

    public WorkClientLinkman queryLinkManByClientId(String clientId){
        return workClientLinkmanDao.queryLinkManByClientId(clientId);
    }

    /**
     * 无合同状态，获取公司所有的客户相关联的联系人信息
     * @param page
     * @return
     */
    public Page<WorkClientLinkman> queryLinkManPageByCompany(Page<WorkClientLinkman> page, WorkClientLinkman linkman){
        linkman.setPage(page);
        page.setList(workClientLinkmanDao.queryLinkManByCompany(linkman));
        return page;
    }



    public List<WorkClientInfo> findByName(WorkClientInfo workClientInfo){
        return workClientInfoDao.findByName(workClientInfo);
    }

}