package com.ekexiu.portal.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.jfw.apt.annotation.Autowrie;
import org.jfw.apt.annotation.DefaultValue;
import org.jfw.apt.annotation.Nullable;
import org.jfw.apt.web.annotation.Path;
import org.jfw.apt.web.annotation.operate.Delete;
import org.jfw.apt.web.annotation.operate.Get;
import org.jfw.apt.web.annotation.operate.Post;
import org.jfw.apt.web.annotation.operate.Put;
import org.jfw.apt.web.annotation.param.JdbcConn;
import org.jfw.apt.web.annotation.param.PathVar;
import org.jfw.apt.web.annotation.param.RequestBody;
import org.jfw.util.PageQueryResult;
import org.jfw.util.StringUtil;

import com.ekexiu.portal.dao.HonorDao;
import com.ekexiu.portal.dao.OrgDao;
import com.ekexiu.portal.dao.PaperDao;
import com.ekexiu.portal.dao.PartTimeJobDao;
import com.ekexiu.portal.dao.PatentDao;
import com.ekexiu.portal.dao.ProfessorDao;
import com.ekexiu.portal.dao.ProfessorEduBgDao;
import com.ekexiu.portal.dao.ProjectDao;
import com.ekexiu.portal.dao.ResearchAreaDao;
import com.ekexiu.portal.dao.ResearchAreaLogDao;
import com.ekexiu.portal.dao.ResourceDao;
import com.ekexiu.portal.po.Professor;
import com.ekexiu.portal.pojo.EditProfessor;
import com.ekexiu.portal.pojo.ProfessorInfo;
import com.ekexiu.portal.util.Calculate;

@Path("/professor")
public class ProfessorService {
	@Autowrie
	private Calculate calculate;
	@Autowrie
	private ResourceDao resourceDao;
	@Autowrie
	private ImageService imageService;
	@Autowrie
	private OrgService orgService;
	@Autowrie
	private PaperDao paperDao;
	@Autowrie
	private OrgDao orgDao;
	@Autowrie
	private ProfessorDao professorDao;
	@Autowrie
	private ResearchAreaLogDao researchAreaLogDao;
	@Autowrie
	private ResearchAreaDao researchAreaDao;
	@Autowrie
	private ProfessorEduBgDao professorEduBgDao;
	@Autowrie
	private PartTimeJobDao partTimeJobDao;
	@Autowrie
	private PatentDao patentDao;
	@Autowrie
	private HonorDao honorDao;
	@Autowrie
	private ProjectDao projectDao;

	
	public Calculate getCalculate() {
		return calculate;
	}

	public void setCalculate(Calculate calculate) {
		this.calculate = calculate;
	}

	public ResourceDao getResourceDao() {
		return resourceDao;
	}

	public void setResourceDao(ResourceDao resourceDao) {
		this.resourceDao = resourceDao;
	}

	public ImageService getImageService() {
		return imageService;
	}

	public void setImageService(ImageService imageService) {
		this.imageService = imageService;
	}

	public OrgService getOrgService() {
		return orgService;
	}

	public void setOrgService(OrgService orgService) {
		this.orgService = orgService;
	}

	public ProjectDao getProjectDao() {
		return projectDao;
	}

	public void setProjectDao(ProjectDao projectDao) {
		this.projectDao = projectDao;
	}

	public HonorDao getHonorDao() {
		return honorDao;
	}

	public void setHonorDao(HonorDao honorDao) {
		this.honorDao = honorDao;
	}

	public PatentDao getPatentDao() {
		return patentDao;
	}

	public void setPatentDao(PatentDao patentDao) {
		this.patentDao = patentDao;
	}

	public PartTimeJobDao getPartTimeJobDao() {
		return partTimeJobDao;
	}

	public void setPartTimeJobDao(PartTimeJobDao partTimeJobDao) {
		this.partTimeJobDao = partTimeJobDao;
	}

	public PaperDao getPaperDao() {
		return paperDao;
	}

	public void setPaperDao(PaperDao paperDao) {
		this.paperDao = paperDao;
	}

	public ProfessorEduBgDao getProfessorEduBgDao() {
		return professorEduBgDao;
	}

	public void setProfessorEduBgDao(ProfessorEduBgDao professorEduBgDao) {
		this.professorEduBgDao = professorEduBgDao;
	}

	public ResearchAreaLogDao getResearchAreaLogDao() {
		return researchAreaLogDao;
	}

	public void setResearchAreaLogDao(ResearchAreaLogDao researchAreaLogDao) {
		this.researchAreaLogDao = researchAreaLogDao;
	}

	public ResearchAreaDao getResearchAreaDao() {
		return researchAreaDao;
	}

	public void setResearchAreaDao(ResearchAreaDao researchAreaDao) {
		this.researchAreaDao = researchAreaDao;
	}

	public ProfessorDao getProfessorDao() {
		return professorDao;
	}

	public void setProfessorDao(ProfessorDao professorDao) {
		this.professorDao = professorDao;
	}

	public OrgDao getOrgDao() {
		return orgDao;
	}

	public void setOrgDao(OrgDao orgDao) {
		this.orgDao = orgDao;
	}


	

	@Post
	@Path
	public String insert(@JdbcConn(true) Connection con, Professor professor, @Nullable String orgName)
			throws SQLException, IOException {
		if(professor.getId() == null ) {
			professor.setId(StringUtil.buildUUID());
		}
		professor.setAuthentication(false);
		if (professor.getOrgId() == null) {
			if(null != this.orgDao.queryByName(con, orgName)){
				professor.setOrgId(this.orgDao.queryByName(con, orgName));
			} else {
				professor.setOrgId(this.orgService.createOrganization(con, orgName));
			}
		}
		this.professorDao.insert(con, professor);
		this.imageService.saveDefaultHeadImage(professor.getId());
		return professor.getId();
	}

	@Put
	@Path
	public void update(@JdbcConn(true) Connection con, @RequestBody EditProfessor professor) throws SQLException, IOException {
		if(professor.getOrgName()!=null)
			if(null != this.orgDao.queryByName(con, professor.getOrgName())){
				professor.setOrgId(this.orgDao.queryByName(con, professor.getOrgName()));
			} else {
				professor.setOrgId(this.orgService.createOrganization(con, professor.getOrgName()));
			}
		this.professorDao.update(con, professor);
	}
	
	@Get
	@Path("/baseInfo/{id}")
	public EditProfessor queryBaseInfo(@JdbcConn Connection con, @PathVar String id) throws SQLException {
		EditProfessor professor = this.professorDao.queryBaseInfo(con, id);
		if(null != professor){
			professor.setHasHeadImage(this.imageService.hasProfessorImage(id));
		}
		return professor;
	}
	
	@Get
	@Path("/editBaseInfo/{id}")
	public EditProfessor queryEditBaseInfo(@JdbcConn Connection con, @PathVar String id) throws SQLException {
		EditProfessor professor = this.professorDao.queryEditBaseInfo(con, id);
		if(null != professor){
			professor.setHasHeadImage(this.imageService.hasProfessorImage(id));
		}
		return professor;
	}
	
	@Get
	@Path("/{id}")
	public Professor query(@JdbcConn Connection con, @PathVar String id) throws SQLException {
		return this.professorDao.query(con, id);
	}
	@Get
	@Path("/qa")
	public List<Professor> queryAll(@JdbcConn Connection con) throws SQLException {
		return this.professorDao.query(con);
	}
	
	@Post
	@Path("/updateStarAvg")
	public boolean updateStarAvg(@JdbcConn(true) Connection con) throws SQLException {
		List<Professor> professors = this.professorDao.queryStar(con);
		BigDecimal bigStar = this.professorDao.queryBigStar(con);
		BigDecimal smallStar = this.professorDao.querySmallStar(con);
		BigDecimal bigConsult = this.professorDao.queryBigConsult(con);
		BigDecimal smallConsult = this.professorDao.querySmallConsult(con);
		for (Professor professor : professors) {
			BigDecimal star = professor.getStarLevel();
			BigDecimal consult = new BigDecimal(professor.getConsultCount());
			BigDecimal avgStar = this.calculate.calcAvgStar(bigStar, smallStar, bigConsult, smallConsult, star, consult);
			this.professorDao.updateStarAvg(con, professor.getId(), avgStar);
		}
		return true;
	}
	
	@Get
	@Path("/pqAPP")
	public PageQueryResult<EditProfessor> queryAPP(@JdbcConn Connection con, @Nullable String key,
			@Nullable String subject,@Nullable String industry,@Nullable String province,
			@Nullable String address, @Nullable Integer authentication, 
			@DefaultValue("10") int pageSize,@DefaultValue("1") int pageNo) throws SQLException{
		if(key!=null) {key="%"+key+"%";}
		if(subject!=null) {subject ="%"+subject+"%";}
		if(null!=industry) {industry="%"+industry+"%";}
		if(null!=province) {province="%"+province+"%";}
		if(null!=address) {address="%"+address+"%";}
		PageQueryResult<EditProfessor> queryResult = this.professorDao.queryAPP(con,key,subject,industry,province,address,authentication,pageSize,pageNo);
		List<EditProfessor> editProfessors = queryResult.getData();
		if(editProfessors != null) {
			for (EditProfessor editProfessor : editProfessors) {
				editProfessor.setHasHeadImage(this.imageService.hasProfessorImage(editProfessor.getId()));
				editProfessor.setResearchAreas(this.researchAreaDao.query(con, editProfessor.getId()));
				editProfessor.setResources(this.resourceDao.queryList(con, editProfessor.getId()));
			}
			queryResult.setData(editProfessors);
		}
		return queryResult;
	}
	
	@Post
	@Path("/starLevel")
	public void updateStarLevel(@JdbcConn(true) Connection con, String id, BigDecimal starLevel) throws SQLException{
		this.professorDao.updateStarLevel(con, id, starLevel);
	}
	
	@Post
	@Path("/subject")
	public void updateSubject(@JdbcConn(true) Connection con,String id, String subject) throws SQLException{
		this.professorDao.updateSubject(con, id, subject);
	}
	
	@Post
	@Path("/industry")
	public void updateIndustry(@JdbcConn(true) Connection con, String id, String industry) throws SQLException{
		this.professorDao.updateIndustry(con, id, industry);
	}
	@Post
	@Path("/address")
	public void updateAddress(@JdbcConn(true) Connection con, String id, String province, String address) throws SQLException{
		this.professorDao.updateProvince(con, id, province);
		this.professorDao.updateAddress(con, id, address);
	}
	@Post
	@Path("/descp")
	public void updateDescp(@JdbcConn(true) Connection con, String id, String descp) throws SQLException{
		this.professorDao.updateDescp(con, id, descp);
	}
	

	@Delete
	@Path("/{id}")
	public void delete(@JdbcConn(true) Connection con, @PathVar String id) throws SQLException {
		this.researchAreaLogDao.delete(con, id);
		this.researchAreaDao.delete(con, id);
		this.professorEduBgDao.delete(con, id);
		this.partTimeJobDao.delete(con, id);
		this.paperDao.delete(con, id);
		this.professorDao.delete(con, id);
		this.patentDao.delete(con, id);
		this.honorDao.delete(con, id);
		this.projectDao.delete(con, id);
	}
	
	@Get
	@Path("/pqBaseInfo")
	PageQueryResult<EditProfessor> queryEditBaseInfo(@JdbcConn(false) Connection con,@Nullable String key,
			@Nullable String subject,@Nullable String industry,@Nullable String address,@Nullable Integer authentication, 
			@DefaultValue("10") int pageSize,@DefaultValue("1") int pageNo)throws SQLException{
		if(key!=null) {key="%"+key+"%";}
		if(subject!=null) {subject ="%"+subject+"%";}
		if(null!=industry) {industry="%"+industry+"%";}
		if(null!=address) {address="%"+address+"%";}
		PageQueryResult<EditProfessor> queryResult = this.professorDao.queryEditBaseInfo(con, key, subject, industry, address, authentication, pageSize, pageNo);
		List<EditProfessor> editProfessors = queryResult.getData();
		if(editProfessors != null){
			for (EditProfessor editProfessor : editProfessors) {
				editProfessor.setHasHeadImage(this.imageService.hasProfessorImage(editProfessor.getId()));
				editProfessor.setResearchAreas(this.researchAreaDao.query(con, editProfessor.getId()));
			}
			queryResult.setData(editProfessors);
		}
		return queryResult;
	}
	
	@Get
	@Path("/pq")
	PageQueryResult<Professor> query(@JdbcConn(false) Connection con,@Nullable String key,
			@Nullable String subject,@Nullable String industry,@Nullable String address, 
			@DefaultValue("10") int pageSize,@DefaultValue("1") int pageNo)throws SQLException{
	//	System.out.println("key==["+(key==null?"":key)+"]");
	//	System.out.println("subject==["+(subject==null?"":subject)+"]");
	//	System.out.println("industry==["+(industry==null?"":industry)+"]");
		if(key!=null) key="%"+key+"%";
		if(subject!=null) subject ="%"+subject+"%";
		if(null!=industry) industry="%"+industry+"%";
		if(null!=address) address="%"+address+"%";
		return this.professorDao.query(con, key, subject, industry, address, pageSize, pageNo);
	}
	
	@Get
	@Path("/info/{id}")
	public ProfessorInfo qinfo(@JdbcConn(false) Connection con,@PathVar String id) throws SQLException{
		ProfessorInfo info = this.professorDao.queryInfo(con, id);
		if(info!=null){
			info.setOrgName(this.orgDao.query(con, info.getOrgId()).getName());
			info.setEdus(this.professorEduBgDao.query(con, id));
			info.setHonors(this.honorDao.query(con, id));
			info.setJobs(this.partTimeJobDao.query(con, id));
			info.setPapers(this.paperDao.query(con, id));
			info.setPatents(this.patentDao.query(con, id));
			info.setProjects(this.projectDao.query(con, id));
			info.setResearchAreaLogs(this.researchAreaLogDao.query(con, id));
			info.setResearchAreas(this.researchAreaDao.query(con, id));
		}
		return info;
		
	}
	
	public static void main(String[] args)throws Exception{
//		Connection con = DriverManager.getConnection("jdbc:postgresql://121.42.53.174:5432/ekexiu", "postgres",  "postgres");
//		try{
//		ProfessorService service = new ProfessorService();
//		ProfessorDao dao = new ProfessorDaoExtend();
//		service.setProfessorDao(dao);
//		PageQueryResult<Professor> result =service.query(con,"鏉?, "鏉愭枡", "閲戝睘", 10, 2);
//		System.out.println(result.getTotal());
//		for(Professor p:result.getData()){
//			System.out.println("======");
//			JsonService.toJson(p,System.out);
//		}
//		}finally{
//			con.close();
//		}
		System.out.println(URLEncoder.encode("输出中文", "UTF-8"));
	}
}
