package cn.com.countrygarden.bi.main.service.test.impl;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.test.TestMapper;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.test.Test;
import cn.com.countrygarden.bi.main.util.roleUtils.AuthorityCheck;
import cn.com.countrygarden.bi.main.service.test.TestService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
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 tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URISyntaxException;
import java.util.List;


/**
 * package: cn.com.countrygarden.bi.main.service.impl describe: creat_user: lsl
 * creat_date: 2018/6/12 creat_time: 9:03
 **/
@Service
@Transactional
public class TestServiceImpl implements TestService {

	@Autowired
	private TestMapper testMapper;

	@Override
	@AuthorityCheck(authorityArray={"advise"})
	public Result queryPageList(Test test, int page, int size, String userCode) {
		Page<Test> objects = PageHelper.startPage(page, size);
		Condition condition = new Condition(Test.class);
		Example.Criteria criteria = condition.createCriteria();
		if (StringUtils.isNotBlank(test.getName())) {
			criteria.andLike("name", String.format("%%%s%%", test.getName()));
		}
		testMapper.selectByCondition(condition);
		PageData pageData = new PageData(objects);
		pageData.setData(objects.getResult());
		return Response.response(pageData);
	}

	@Override
	public Result queryById(Integer id) {
		return Response.response(testMapper.selectByPrimaryKey(id));
	}

	@Override
	public Result add(Test test, AccessToken accessToken) {
		testMapper.insert(test);
		return Response.response();
	}

	@Override
	public Result edit(Test test, AccessToken accessToken) {
		testMapper.updateByPrimaryKey(test);
		return Response.response();
	}

	@Override
	public Result del(Integer id) {
		testMapper.deleteByPrimaryKey(id);
		return Response.response();
	}

	@Override
	public Result conditionTest(Integer id) {

		Condition condition = null;
		Criteria create = null;
		condition = new Condition(Test.class);
		condition.excludeProperties("id");
		List<Test> list = testMapper.selectByCondition(condition);
		for (Test test : list) {
			System.out.println("==============查询除id外的所有字段======================" + test.getId());
		}
		condition = new Condition(Test.class);
		Criteria criteria = condition.createCriteria();
		// criteria.andEqualTo("id",15).andLike("name","%"+"我"+"%");等同下面的写法
		criteria.andEqualTo("id", 15).andLike("name", "%我%");
		List<Test> list2 = testMapper.selectByCondition(condition);
		for (Test test : list) {
			System.out
					.println("==============指定id+模糊查询======================" + test.getId() + "，名字：" + test.getName());
		}

		condition = new Condition(Test.class);
		condition.excludeProperties("name").orderBy("id").desc();
		list = testMapper.selectByCondition(condition);
		// 执行的sql: SELECT description , id , code FROM test order by id DESC
		for (Test test : list) {
			System.out.println("==============查询除name外的所有字段并且根据di倒序======================id:" + test.getId() + "，名字："
					+ test.getName());
		}
		condition = new Condition(Test.class);
		create = condition.createCriteria();
		condition.selectProperties("name").setDistinct(true);
		list = testMapper.selectByCondition(condition);
		// 执行的sql: SELECT distinct name FROM test
		for (Test test : list) {
			System.out.println("====================================id:" + test.getId() + "，名字：" + test.getName());
		}
		/**
		 * FOR
		 * UPDATE是一种行级锁，一旦用户对某个行施加了行级加锁，则该用户可以查询也可以更新被加锁的数据行，其它用户只能查询但不能更新被加锁的数据行．如果其它用户想更新该表中的数据行，则也必须对该表施加行级锁．即使多个用户对一个表均使用了共享更新，但也不允许两个事务同时对一个表进行更新，真正对表进行更新时，是以独占方式锁表，一直到提交或复原该事务为止。行锁永远是独占方式锁。
		 * 只有当出现如下之一的条件，便释放共享更新锁
		 */
		// condition = new Condition(Test.class);
		// condition.selectProperties("name").setForUpdate(true);
		// list = testMapper.selectByCondition(condition);
		// // 执行的sql: SELECT name FROM test FOR UPDATE
		// for (Test test : list) {
		// System.out.println("====================================id:" + test.getId() +
		// "，名字：" + test.getName());
		// }

		condition = new Condition(Test.class);
		create = condition.createCriteria();
		create.setAndOr("and");

		return null;
	}

	public Result TestFileUpload(MultipartFile attach, HttpServletRequest request)  {

		// 上传图片文件处理
		String idPicPath = null;
		String workPicPath = null;
		String errorInfo = null;
		boolean flag = true;
		String path="";
//		path=request.getSession().getServletContext().getRealPath("fileupload"+File.separator);
		try {
			path = this.getClass().getClassLoader().getResource("/").toURI().getPath()
					 + "/fileupload";
		} catch (URISyntaxException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		System.out.println("==============path======================" + path);
		if (!attach.isEmpty()) {
			String oldFileName = attach.getOriginalFilename();// 原文件名
			System.out.println("==============oldFileName 原文件名======================" + oldFileName);
			String prefix = FilenameUtils.getExtension(oldFileName);// 获得原文件名的后辍
			int filesize = 50000;
			if (attach.getSize() > filesize) {
				return Response.response("上传文件不得超过500kb");
			} else {
				String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + oldFileName;
				File targetFile = new File(path, fileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				// 保存
				try {
					attach.transferTo(targetFile);
				} catch (Exception e) {
					return Response.response("上传文件失败");

				}

				idPicPath = path + File.separator + fileName;
			}
		}
		return Response.response("上传文件成功");
	}
}
