package com.bcxin.ins.service.order.impl;

import com.bcxin.ins.dao.order.ComPoliciesAPIDao;
import com.bcxin.ins.service.order.ComPoliciesAPIService;
import com.bcxin.ins.entity.common.ComPolicies;
import com.bcxin.ins.util.DateUtil;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.ins.vo.DwzPage;
import com.bcxin.mybatisplus.plugins.Page;
import com.bcxin.mybatisplus.service.impl.ServiceImpl;
import com.bcxin.mybatisplus.toolkit.StringUtils;
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 java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;


@Service
@Transactional(readOnly = true)
public class ComPoliciesAPIServiceImpl extends ServiceImpl<ComPoliciesAPIDao, ComPolicies> implements ComPoliciesAPIService {


	@Autowired
	private ComPoliciesAPIDao dao;

	@Override
	public List<ComPolicies> findComPoliciesList(ComPolicies comPolicies, DwzPage page){
		Page<ComPolicies> pageHelper = new Page<ComPolicies>(page.getPageNum(), page.getNumPerPage());
		List<ComPolicies> list = dao.findComPoliciesList(pageHelper,comPolicies.getTitle());
		page.setTotalCount(new Long(pageHelper.getTotal()).intValue());
		return list;
	}

	@Override
	public boolean uploadFile(MultipartFile file, ComPolicies comPolicies, String basePath) {
		boolean flag = true;
		try {
			if(file == null || StringUtils.isEmpty(file.getOriginalFilename())) {
				return flag;
			}

			String originalName = file.getOriginalFilename();
			String fileType = originalName.split("\\.").length > 1 ? originalName.split("\\.")[1] : ConstProp.BLANK_CHAR;
			String parentPath = "/policy/policies/" + ConstProp.SLASH;
			File baseFile = new File(basePath + parentPath);
			if(!baseFile.exists()){
				baseFile.mkdirs();
			}

			String targetFilePath =  DateUtil.generatorRadomNumber() + ("".equals(fileType) ? ConstProp.BLANK_CHAR : (ConstProp.DOT + fileType));

			File targetFile = new File(baseFile, targetFilePath);
			file.transferTo(targetFile);

			comPolicies.setVisit_path(parentPath + targetFilePath);
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}

		return flag;
	}

	@Override
	public boolean deleteLogoFile(String path, ComPolicies comPolicies) {
		boolean flag = true;

		if (path != null) {
			File file = new File(path);
			try {
				Files.delete(file.toPath());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		comPolicies.setVisit_path(null);

		return flag;
	}

}
