package com.zcloud.controller.onlinexxks;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.service.onlinexxks.TeacherCertificateService;
import com.zcloud.service.onlinexxks.TeacherService;
import com.zcloud.util.*;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * 说明：教师管理
 * 作者：luoxiaobao
 * 时间：2022-03-04
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController extends BaseController {

	@Autowired
	private TeacherService teacherService;

	@Autowired
	private TeacherCertificateService teachercertificateService;

	/**新增
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	@RequiresPermissions("teacher:add")
	@ResponseBody
	public Object add(@RequestParam(value="frontFile") MultipartFile frontFile,
					  @RequestParam(value="reverseFile") MultipartFile reverseFile,
					  @RequestParam(value="diplomaFile") MultipartFile diplomaFile,
					  @RequestParam(value="certificateFile") MultipartFile certificateFile) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("TEACHER_ID", this.get32UUID());	//主键
		pd.put("CREATOR", Jurisdiction.getUsername());	//添加人
		pd.put("CREATTIME", DateUtil.date2Str(new Date()));	//添加时间
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		pd.put("ISDELETE", "0");	//是否删除(0:有效 1：删除)
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		this.handleTeacherFile(pd, frontFile, reverseFile, diplomaFile, certificateFile);
		teacherService.save(pd);
		map.put("result", errInfo);
		return map;
	}

	/**删除
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	@RequiresPermissions("teacher:del")
	@ResponseBody
	public Object delete() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
//		PageData old = teacherService.findById(pd);
//		this.deleteServerFile(old);
		teachercertificateService.deleteByTeacher(pd);
		teacherService.delete(pd);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	@RequiresPermissions("teacher:edit")
	@ResponseBody
	public Object edit(@RequestParam(value="frontFile",required=false) MultipartFile frontFile,
					   @RequestParam(value="reverseFile",required=false) MultipartFile reverseFile,
					   @RequestParam(value="diplomaFile",required=false) MultipartFile diplomaFile,
					   @RequestParam(value="certificateFile",required=false) MultipartFile certificateFile) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		PageData old = teacherService.findById(pd);
		this.deleteServerFile(old, frontFile, reverseFile, diplomaFile, certificateFile);
		this.handleTeacherFile(pd, frontFile, reverseFile, diplomaFile, certificateFile);
		teacherService.edit(pd);
		map.put("result", errInfo);
		return map;
	}

	/**
	 *	新增修改时删除原有附件文件
	 * @param old	数据对象
	 * @param frontFile		身份证照片（正面）
	 * @param reverseFile		身份证照片（反面）
	 * @param diplomaFile		毕业证照片
	 * @param certificateFile		资格证照片
	 */
	private void deleteServerFile(PageData old, MultipartFile frontFile, MultipartFile reverseFile,
                                  MultipartFile diplomaFile, MultipartFile certificateFile) throws Exception {
		if (StringUtils.isNotBlank(old.getString("IDENTITY_FILEPATH_FRONT")) && null != frontFile && !frontFile.isEmpty()) {
			Smb.delete(old.getString("IDENTITY_FILEPATH_FRONT"));
		}
		if (StringUtils.isNotBlank(old.getString("IDENTITY_FILEPATH_REVERSE")) && null != reverseFile && !reverseFile.isEmpty()) {
			Smb.delete(old.getString("IDENTITY_FILEPATH_REVERSE"));
		}
		if (StringUtils.isNotBlank(old.getString("DIPLOMA_FILEPATH")) && null != diplomaFile && !diplomaFile.isEmpty()) {
			Smb.delete(old.getString("DIPLOMA_FILEPATH"));
		}
		if (StringUtils.isNotBlank(old.getString("CERTIFICATE_FILEPATH")) && null != certificateFile && !certificateFile.isEmpty()) {
			Smb.delete(old.getString("CERTIFICATE_FILEPATH"));
		}
	}

	/**
	 *
	 * @param pd	数据对象
	 * @param frontFile		身份证照片（正面）
	 * @param reverseFile		身份证照片（反面）
	 * @param diplomaFile		毕业证照片
	 * @param certificateFile		资格证照片
	 */
	private void handleTeacherFile(PageData pd, MultipartFile frontFile, MultipartFile reverseFile,
                                   MultipartFile diplomaFile, MultipartFile certificateFile) throws Exception {
		String  ffile = DateUtil.getDays();
		if (null != frontFile && !frontFile.isEmpty()) {		 // 身份证照片（正面）
			//本地
//			String filePath = PathUtil.getProjectpath() + Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile;	//文件上传路径
//			String fileName = FileUpload.fileUp(file, filePath, this.get32UUID());				//执行上传
			//服务器
			String fileName = this.get32UUID()+frontFile.getOriginalFilename().substring(frontFile.getOriginalFilename().lastIndexOf("."));
			Smb.sshSftp(frontFile, fileName, Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile);
			pd.put("IDENTITY_FILEPATH_FRONT", Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile + "/" + fileName);
		}
		if (null != reverseFile && !reverseFile.isEmpty()) {		 // 身份证照片（反面）
			//服务器
			String fileName = this.get32UUID()+reverseFile.getOriginalFilename().substring(reverseFile.getOriginalFilename().lastIndexOf("."));
			Smb.sshSftp(reverseFile, fileName, Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile);
			pd.put("IDENTITY_FILEPATH_REVERSE", Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile + "/" + fileName);
		}
		if (null != diplomaFile && !diplomaFile.isEmpty()) {		 // 毕业证照片
			//服务器
			String fileName = this.get32UUID()+diplomaFile.getOriginalFilename().substring(diplomaFile.getOriginalFilename().lastIndexOf("."));
			Smb.sshSftp(diplomaFile, fileName, Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile);
			pd.put("DIPLOMA_FILEPATH", Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile + "/" + fileName);
		}
		if (null != certificateFile && !certificateFile.isEmpty()) {	 // 资格证照片
			//服务器
			String fileName = this.get32UUID()+certificateFile.getOriginalFilename().substring(certificateFile.getOriginalFilename().lastIndexOf("."));
			Smb.sshSftp(certificateFile, fileName, Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile);
			pd.put("CERTIFICATE_FILEPATH", Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile + "/" + fileName);
		}
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	@RequiresPermissions("teacher:list")
	@ResponseBody
	public Object list(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String KEYWORDS = pd.getString("KEYWORDS");						//关键词检索条件
		if(Tools.notEmpty(KEYWORDS))pd.put("KEYWORDS", KEYWORDS.trim());
		page.setPd(pd);
		List<PageData>	varList = teacherService.list(page);	//列出Teacher列表
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	 /**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	@RequiresPermissions("teacher:edit")
	@ResponseBody
	public Object goEdit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = teacherService.findById(pd);	//根据ID读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/info")
	@RequiresPermissions("teacher:edit")
	@ResponseBody
	public Object info() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = teacherService.info(pd);	//根据ID读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	 /**批量删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteAll")
	@RequiresPermissions("teacher:del")
	@ResponseBody
	public Object deleteAll() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		String DATA_IDS = pd.getString("DATA_IDS");
		if(Tools.notEmpty(DATA_IDS)){
			String ArrayDATA_IDS[] = DATA_IDS.split(",");
			pd.put("ArrayDATA_IDS", ArrayDATA_IDS);	//待删除ids
//			List<PageData> pdList = teacherService.findByIds(pd);
//			for (PageData d : pdList) {
//				this.deleteServerFile(d);
//			}
			teachercertificateService.deleteByTeacherAll(pd);
			teacherService.deleteAll(pd);
			errInfo = "success";
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	 /**导出到excel
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/excel")
	@RequiresPermissions("toExcel")
	public ModelAndView exportExcel() throws Exception{
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		Map<String,Object> dataMap = new HashMap<String,Object>();
		List<String> titles = new ArrayList<String>();
		titles.add("教师姓名");	//1
		titles.add("手机号");	//2
		titles.add("身份证号");	//3
		titles.add("文化程度");	//4
		titles.add("专业");	//5
		titles.add("身份证照片（正面）");	//6
		titles.add("身份证照片（反面）");	//7
		titles.add("毕业证照片");	//8
		titles.add("资格证照片");	//9
		titles.add("是否删除（0.正常 1.删除）");	//10
		titles.add("修改人");	//11
		titles.add("修改时间");	//12
		titles.add("添加人");	//13
		titles.add("添加时间");	//14
		titles.add("企业ID");	//15
		dataMap.put("titles", titles);
		List<PageData> varOList = teacherService.listAll(pd);
		List<PageData> varList = new ArrayList<PageData>();
		for(int i=0;i<varOList.size();i++){
			PageData vpd = new PageData();
			vpd.put("var1", varOList.get(i).getString("NAME"));	    //1
			vpd.put("var2", varOList.get(i).getString("PHONE"));	    //2
			vpd.put("var3", varOList.get(i).getString("IDENTITY_NUMBER"));	    //3
			vpd.put("var4", varOList.get(i).getString("EDUCATION_LEVEL"));	    //4
			vpd.put("var5", varOList.get(i).getString("PROFESSION"));	    //5
			vpd.put("var6", varOList.get(i).getString("IDENTITY_FILEPATH_FRONT"));	    //6
			vpd.put("var7", varOList.get(i).getString("IDENTITY_FILEPATH_REVERSE"));	    //7
			vpd.put("var8", varOList.get(i).getString("DIPLOMA_FILEPATH"));	    //8
			vpd.put("var9", varOList.get(i).getString("CERTIFICATE_FILEPATH"));	    //9
			vpd.put("var10", varOList.get(i).getString("ISDELETE"));	    //10
			vpd.put("var11", varOList.get(i).getString("OPERATOR"));	    //11
			vpd.put("var12", varOList.get(i).getString("OPERATTIME"));	    //12
			vpd.put("var13", varOList.get(i).getString("CREATOR"));	    //13
			vpd.put("var14", varOList.get(i).getString("CREATTIME"));	    //14
			vpd.put("var15", varOList.get(i).getString("CORPINFO_ID"));	    //15
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv,dataMap);
		return mv;
	}
	/**列表教师列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/listAllSelect")
	@ResponseBody
	public Object listAllSelect() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		List<PageData>	varList = teacherService.listAllBySelect(pd);	// 获取所有的教师信息
		JSONArray arr = JSONArray.fromObject(varList);
		String json = arr.toString().replaceAll("","");
		json = json.replaceAll("TEACHER_ID", "id").replaceAll("NAME", "name");
		map.put("zTreeNodes", json);
		map.put("result", errInfo);
		return map;
	}
}
