package com.zcloud.controller.relatedparty;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.relatedparty.UnitsService;
import com.zcloud.service.system.DictionariesService;
import com.zcloud.util.*;
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-06-07
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/units")
public class UnitsController extends BaseController {

	@Autowired
	private UnitsService unitsService;
	@Autowired
	private DictionariesService dictionariesService;
	@Autowired
	private Smb smb;
	/**新增
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	// @RequiresPermissions("units:add")
	@ResponseBody
	@LogAnno(menuType= "综合管理",menuServer= "相关方管理",instructionsOperate = "相关方单位管理",instructionsType = "新增")
	public Object add(@RequestParam(value="file",required=false) MultipartFile file) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("UNITS_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");	//是否删除
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		if (null != file && !file.isEmpty()) {
			String  ffile = DateUtil.getDays();
//			String filePath = PathUtil.getProjectpath() + Const.FILEPATHFILE + ffile;	//文件上传路径
//			String fileName = FileUpload.fileUp(file, filePath, this.get32UUID());				//执行上传
			String fileName = this.get32UUID()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			smb.sshSftp(file, fileName, Const.FILEPATHFXGFGL + Jurisdiction.getCORPINFO_ID() + "/" + ffile);
			pd.put("FILEPATH", Const.FILEPATHFXGFGL + Jurisdiction.getCORPINFO_ID() + "/" + ffile + "/" + fileName);
		}
		pd.put("UNITS_ID", pd.getString("UNITS_ID"));
		List<PageData> list = unitsService.listAll(pd);
		for (PageData pageData : list) {
			if (pageData.get("CODE").equals(pd.get("CODE"))){
				errInfo = "fail";
				map.put("result", errInfo);
				map.put("msg", "统一社会信用代码重复");
				return map;
			}
			if (pageData.get("UNITS_NAME").equals(pd.get("UNITS_NAME"))){
				errInfo = "fail";
				map.put("result", errInfo);
				map.put("msg", "相关方单位名称重复");
				return map;
			}
		}
		unitsService.save(pd);
		map.put("result", errInfo);
		return map;
	}

	/**删除
	 * @param out
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	// @RequiresPermissions("units:del")
	@ResponseBody
	@LogAnno(menuType= "综合管理",menuServer= "相关方管理",instructionsOperate = "相关方单位管理",instructionsType = "删除")
	public Object delete() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		unitsService.delete(pd);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	// @RequiresPermissions("units:edit")
	@ResponseBody
	@LogAnno(menuType= "综合管理",menuServer= "相关方管理",instructionsOperate = "相关方单位管理",instructionsType = "修改")
	public Object edit(@RequestParam(value="file",required=false) MultipartFile file) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();

		if (null != file && !file.isEmpty()) {
			String  ffile = DateUtil.getDays();
////			String filePath = PathUtil.getProjectpath() + Const.FILEPATHFILE + ffile;	//文件上传路径
////			String fileName = FileUpload.fileUp(file, filePath, this.get32UUID());				//执行上传
			String fileName = this.get32UUID()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			smb.sshSftp(file, fileName, Const.FILEPATHFXGFGL + Jurisdiction.getCORPINFO_ID() + "/" + ffile );
			pd.put("FILEPATH", Const.FILEPATHFXGFGL + Jurisdiction.getCORPINFO_ID() + "/" + ffile + "/" + fileName);
		}

		unitsService.edit(pd);

		map.put("result", errInfo);
		return map;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	// @RequiresPermissions("units:list")
	@ResponseBody
	@LogAnno(menuType= "综合管理",menuServer= "相关方管理",instructionsOperate = "相关方单位管理",instructionsType = "列表")
	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());
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		page.setPd(pd);
		List<PageData>	varList = unitsService.list(page);	//列出Units列表
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	@RequestMapping(value = "/listAll")
//	@RequiresPermissions("units:list")
	@ResponseBody
	public Object listAll() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = this.getPageData();
		pd.put("CORPINFO_ID",Jurisdiction.getCORPINFO_ID());
		List<PageData> varList = unitsService.listAll(pd);    //列出Units列表
		map.put("varList", varList);
		map.put("result", errInfo);
		return map;
	}

	/**判断相关方单位名是否存在
	 * @return
	 */
	@RequestMapping(value="/hasName")
	@ResponseBody
	@LogAnno(menuType= "综合管理",menuServer= "相关方管理",instructionsOperate = "相关方单位管理",instructionsType = "判断相关方单位名称是否存在")
	public Object hasName() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = unitsService.findByName(pd);
		if(pd != null){
			errInfo = "fail";
			map.put("msg", "相关方单位名称重复");
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}
	/**判断社会信用代码是否存在
	 * @return
	 */
	@RequestMapping(value="/hasCode")
	@ResponseBody
	@LogAnno(menuType= "综合管理",menuServer= "相关方管理",instructionsOperate = "相关方单位管理",instructionsType = "判断社会信用代码是否存在")
	public Object hasCode() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		if(unitsService.findByCode(pd) != null){
			errInfo = "fail";
			map.put("msg", "统一社会信用代码重复");
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}
	 /**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	// @RequiresPermissions("units:edit")
	@ResponseBody
	@LogAnno(menuType= "综合管理",menuServer= "相关方管理",instructionsOperate = "相关方单位管理",instructionsType = "去修改页面获取数据")
	public Object goEdit(@RequestParam(value="file",required=false) MultipartFile file) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = unitsService.findById(pd);	//根据ID读取

		List<String> POSSESSIONALL = new ArrayList<String>();
		if(pd.get("PROVINCE") != null && Tools.notEmpty(pd.get("PROVINCE").toString())) {
			POSSESSIONALL.add(pd.get("PROVINCE").toString());
		}
		if(pd.get("CITY") != null && Tools.notEmpty(pd.get("CITY").toString())) {
			POSSESSIONALL.add(pd.get("CITY").toString());
		}
		if(pd.get("COUNTY") != null && Tools.notEmpty(pd.get("COUNTY").toString())) {
			POSSESSIONALL.add(pd.get("COUNTY").toString());
		}
		if(pd.get("VILLAGE") != null && Tools.notEmpty(pd.get("VILLAGE").toString())) {
			POSSESSIONALL.add(pd.get("VILLAGE").toString());
		}
		if(pd.get("STREET") != null && Tools.notEmpty(pd.get("STREET").toString())) {
			POSSESSIONALL.add(pd.get("STREET").toString());
		}
		if(POSSESSIONALL != null && POSSESSIONALL.size() > 0) {
			pd.put("posOption", initDicTreeByNum(POSSESSIONALL.get(POSSESSIONALL.size()-1)));
		}

		pd.put("POSSESSION", POSSESSIONALL);
		map.put("pd", pd);

		map.put("result", errInfo);
		return map;
	}

	/**批量删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteAll")
	// @RequiresPermissions("units:del")
	@ResponseBody
	@LogAnno(menuType= "综合管理",menuServer= "相关方管理",instructionsOperate = "相关方单位管理",instructionsType = "批量删除")
	public Object deleteAll() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String DATA_IDS = pd.getString("DATA_IDS");
		if(Tools.notEmpty(DATA_IDS)){
			String ArrayDATA_IDS[] = DATA_IDS.split(",");
			unitsService.deleteAll(ArrayDATA_IDS);
			errInfo = "success";
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	 /**导出到excel
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/excel")
	// @RequiresPermissions("toExcel")
	@LogAnno(menuType= "综合管理",menuServer= "相关方管理",instructionsOperate = "相关方单位管理",instructionsType = "导出到excel")
	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("注册资金(万元)");	//10
		titles.add("资产总额(万元)");	//11
		titles.add("类型");	//12
		titles.add("添加人");	//13
		titles.add("添加时间");	//14
		titles.add("修改人");	//15
		titles.add("修改时间");	//16
		titles.add("是否删除");	//17
		titles.add("企业ID");	//18
		dataMap.put("titles", titles);
		List<PageData> varOList = unitsService.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("UNITS_NAME"));	    //1
			vpd.put("var2", varOList.get(i).getString("CODE"));	    //2
			vpd.put("var3", varOList.get(i).getString("COMPANY_AREA"));	    //3
			vpd.put("var4", varOList.get(i).getString("ADDRESS"));	    //4
			vpd.put("var5", varOList.get(i).getString("CONTACTS"));	    //5
			vpd.put("var6", varOList.get(i).get("CONTACTS_PHONE").toString());	//6
			vpd.put("var7", varOList.get(i).get("LR_MOBILE").toString());	//7
			vpd.put("var8", varOList.get(i).get("EMPLOYEES").toString());	//8
			vpd.put("var9", varOList.get(i).getString("CREATE_DATE"));	    //9
			vpd.put("var10", varOList.get(i).get("REGCAPITAL").toString());	//10
			vpd.put("var11", varOList.get(i).get("TOTALASSETS").toString());	//11
			vpd.put("var12", varOList.get(i).getString("UNITS_TYPE"));	    //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("OPERATOR"));	    //15
			vpd.put("var16", varOList.get(i).getString("OPERATTIME"));	    //16
			vpd.put("var17", varOList.get(i).getString("ISDELETE"));	    //17
			vpd.put("var18", varOList.get(i).getString("CORPINFO_ID"));	    //18
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv,dataMap);
		return mv;
	}
	/**
	 * 初始化数据字典懒加载下拉树（根据编码）
	 * @param dictionaries_id
	 * @return
	 * @throws Exception
	 */
	public List<PageData> initDicTreeByNum(String dictionaries_bianma) throws Exception{
		PageData dic = new PageData();
		dic.put("BIANMA", dictionaries_bianma);
		dic = dictionariesService.findByBianma(dic);
		dic.put("value", dic.get("DICTIONARIES_ID"));
		dic.put("numValue", dic.get("BIANMA"));
		dic.put("id", dic.get("DICTIONARIES_ID"));
		dic.put("label", dic.get("NAME"));
		List<PageData> industryOption = dictionariesService.getTreeFromBelow(new ArrayList<PageData>(),dic);
		return industryOption;
	}
	/**
	 * 初始化数据字典懒加载下拉树（根据id）
	 * @param dictionaries_id
	 * @return
	 * @throws Exception
	 */
//	public List<PageData> initDicTree(String dictionaries_id) throws Exception{
//		PageData dic = new PageData();
//		dic.put("DICTIONARIES_ID", dictionaries_id);
//		dic = dictionariesService.findById(dic);
//		dic.put("value", dic.get("DICTIONARIES_ID"));
//		dic.put("id", dic.get("DICTIONARIES_ID"));
//		dic.put("label", dic.get("NAME"));
//		List<PageData> industryOption = dictionariesService.getTreeFromBelow(new ArrayList<PageData>(),dic);
//		return industryOption;
//	}
}
