package com.yeejoin.amos.boot.module.ugp.biz.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.biz.utils.CommonResponseUtil;
import com.yeejoin.amos.boot.module.ugp.api.Enum.OrgEnum;
import com.yeejoin.amos.boot.module.ugp.api.constants.XJConstant;
import com.yeejoin.amos.boot.module.ugp.api.dto.EquipmentDto;
import com.yeejoin.amos.boot.module.ugp.api.dto.MaterialDto;
import com.yeejoin.amos.boot.module.ugp.api.dto.WelderEquipmentDto;
import com.yeejoin.amos.boot.module.ugp.api.entity.Attachment;
import com.yeejoin.amos.boot.module.ugp.api.entity.Company;
import com.yeejoin.amos.boot.module.ugp.api.entity.Equipment;
import com.yeejoin.amos.boot.module.ugp.api.entity.Project;
import com.yeejoin.amos.boot.module.ugp.api.mapper.CompanyMapper;
import com.yeejoin.amos.boot.module.ugp.biz.framework.BusinessIdentify;
import com.yeejoin.amos.boot.module.ugp.biz.service.impl.*;
import io.swagger.annotations.ApiModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import io.swagger.models.Model;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.web.servlet.support.RequestDataValueProcessor;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import org.springframework.beans.factory.annotation.Autowired;

import javax.crypto.spec.RC2ParameterSpec;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.ugp.api.dto.ProjectDto;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.foundation.enumeration.UserType;

/**
 * 项目信息表
 *
 * @author system_generator
 * @date 2022-09-22
 */
@RestController
@Api(tags = "项目信息表Api")
@RequestMapping(value = "/project")
public class ProjectController extends BaseController {

	@Autowired
	ProjectServiceImpl projectServiceImpl;
	@Autowired
	ProjectInitiationServiceImpl projectInitiationService;
	@Autowired
	CompanyMapper companyMapper;
	@Autowired
	OrgServiceImpl orgServiceImpl;
	@Autowired
	EquipmentServiceImpl equipmentService;
	@Autowired
	AttachmentServiceImpl attachmentServiceImpl;
	@Autowired
	ProjectResourceServiceImpl projectResourceServiceImpl;


	/**
	 * 新增项目信息表
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增项目信息表", notes = "新增项目信息表")
	@BusinessIdentify
	public ResponseModel<ProjectDto> save(@RequestBody ProjectDto model) {
		System.out.println("项目立项开始："+ DateUtils.date2LongStr(new Date()));
		String regionName = "",regionCode = "";
		Map<String,String> map = getInfo(regionName,regionCode,Long.valueOf(model.getInstallRegionCode()));
		model.setSubmitDate(new Date());
		model.setInstallationUnit(orgServiceImpl.getOrgUsrById(String.valueOf(model.getInstallationUnitId())).getBizOrgName());
		model.setDesignUnit(orgServiceImpl.getOrgUsrById(String.valueOf(model.getDesignUnitId())).getBizOrgName());
		model.setConstructionUnitId(orgServiceImpl.getReginParams().getBusinessInfo().getCompanySequenceNbr());
		model.setChargePerson(orgServiceImpl.getOrgUsrById(String.valueOf(model.getChargePersonId())).getBizOrgName());
		model.setInstallRegion(map.get("regionName"));
		model.setInstallRegionCode(map.get("regionCode"));
		model.setCode(getCode());
		model = projectServiceImpl.createWithModel(model);
		Project project = new Project();
		BeanUtils.copyProperties(model, project);
		System.out.println("项目立项保存信息结束："+DateUtils.date2LongStr(new Date()));
		String token = RequestContext.getToken();
		String appKey = RequestContext.getAppKey();
		String product = RequestContext.getProduct();
		//分支线程执行流程
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				RequestContext.setToken(token);
				RequestContext.setAppKey(appKey);
				RequestContext.setProduct(product);
				projectInitiationService.start(project);
			}
		});
		t1.start();
		return ResponseHelper.buildResponse(model);
	}
	// 静态变量存储最大值
	private static final AtomicInteger atomicNum = new AtomicInteger();
	private static final Integer INIT_CODE_NUM = 0;
	public String getCode(){
		String date = new SimpleDateFormat("yyyy").format(new Date());
		String code = "XM"+date+"-";
		String format="";
		String projectCode = "";
		LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
		wrapper.orderByDesc(Project::getCode);
		List<Project> list = projectServiceImpl.list(wrapper);
		if(!ValidationUtil.isEmpty(list)){
			projectCode =list.iterator().next().getCode();




		if(!ValidationUtil.isEmpty(projectCode)){
			String proDate = projectCode.substring(projectCode.indexOf("M")+1,projectCode.length() - 5);
			if (proDate.equals(date)){
				String substring = projectCode.substring(projectCode.length() - 4);
				atomicNum.set(Integer.parseInt(substring));
			}else {
				atomicNum.set(INIT_CODE_NUM);
			}
			format = String.format("%04d", atomicNum.incrementAndGet());
		}
		}else {
			format = String.format("%04d", atomicNum.incrementAndGet());
		}
		return code+format;
	}

	public Map<String,String> getInfo(String regionName,String regionCode,Long sequenceNbr){
		RegionModel region = Systemctl.regionClient.getRegion(sequenceNbr).getResult();
		regionName = region.getRegionName() + regionName;
		if(ValidationUtil.isEmpty(regionCode)){
			regionCode = String.valueOf(region.getRegionCode());
		} else {
			regionCode = region.getRegionCode() +"#" +regionCode;
		}
		Map<String,String> map = new HashMap();
		if(region.getParentId() != 0L){
			map = getInfo(regionName,regionCode,region.getParentId());
		} else {
			map.put("regionName",regionName);
		}
		map.put("regionCode",regionCode);
		return map;
	}

	/**
	 * 根据sequenceNbr更新
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新项目信息表", notes = "根据sequenceNbr更新项目信息表")
	public ResponseModel<ProjectDto> updateBySequenceNbrProject(@RequestBody ProjectDto model, @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
		model.setRecDate(new Date());
		model.setSequenceNbr(sequenceNbr);
		return ResponseHelper.buildResponse(projectServiceImpl.updateWithModel(model));
	}

	/**
	 * 根据sequenceNbr删除
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@DeleteMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除项目信息表", notes = "根据sequenceNbr删除项目信息表")
	public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
		return ResponseHelper.buildResponse(projectServiceImpl.removeById(sequenceNbr));
	}

	/**
	 * 根据sequenceNbr查询
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个项目信息表", notes = "根据sequenceNbr查询单个项目信息表")
	public ResponseModel<ProjectDto> selectOne(@PathVariable Long sequenceNbr) {
		ProjectDto projectDto = projectServiceImpl.queryBySeq(sequenceNbr);
		projectDto.setStartDateString(new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(projectDto.getStartDate()));
		return ResponseHelper.buildResponse(projectServiceImpl.queryBySeq(sequenceNbr));
	}

	/**
	 * 列表分页查询
	 *
	 * @param current 当前页
	 * @param current 每页大小
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/page")
	@ApiOperation(httpMethod = "GET",value = "项目信息表分页查询",  notes = "项目信息表分页查询")
	public ResponseModel<IPage<ProjectDto>> queryForPage(String current,String size, Project project) {
		return ResponseHelper.buildResponse(projectServiceImpl.queryProjectPage(current,size,project));
	}



	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "项目信息表列表全部数据查询",   notes = "项目信息表列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<ProjectDto>> selectForList() {
	    return ResponseHelper.buildResponse(projectServiceImpl.queryForProjectList());
	}
	/**
	 * 查询项目名称
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "查询项目名称", notes = "查询项目名称")
	@GetMapping(value = "/selectName")
	public ResponseModel<List<JSONObject>> selectName() {
		return ResponseHelper.buildResponse(projectServiceImpl.selectName());
	}

	/**
	 * 获取下拉选择值
	 * @param type INSTALL("安装单位")、DESIGN("设计单位")、SUPERVISION（”监察单位“）、MONITORING（”监检机构“）
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "查询下拉选择框的值", notes = "查询下拉选择框的值")
	@GetMapping(value = "/getSelectInfo")
	public ResponseModel<List<OrgUsr>> getSelectInfo(String type){
		return ResponseHelper.buildResponse(orgServiceImpl.getSelectInfo(type));
	}

	/**
	 * 查询监检机构下的人员列表
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "查询下拉选择框的值", notes = "查询下拉选择框的值")
	@GetMapping(value = "/getDepPerson")
	public ResponseModel<List<OrgUsr>> getDepPerson(String insDepId){
		return ResponseHelper.buildResponse(orgServiceImpl.getVerInfo(insDepId));
	}

	/**
	 * 查询当前登录单位下的人员列表
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "查询下拉选择框的值", notes = "查询下拉选择框的值")
	@GetMapping(value = "/getCharge")
	public ResponseModel<List<OrgUsr>> getCharge(@RequestParam(required = false) Long sequenceNbr){
		return ResponseHelper.buildResponse(orgServiceImpl.getCharge(sequenceNbr));
	}

	/**
	 * 查询当前登陆人所在单位下的所以项目列表
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "查询当前登陆人所在单位下的所以项目列表", notes = "查询当前登陆人所在单位下的所以项目列表")
	@GetMapping(value = "/getCompanyProjects")
	public ResponseModel<List<Project>> getCompanyProjects(){
		Long companyId = null;
		//获取当前登陆人所在单位id
//		companyId = orgServiceImpl.getCompanyId();
//		if(ValidationUtil.isEmpty(companyId)){
//			return ResponseHelper.buildResponse(new ArrayList<>());
//		}
		LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
		if (!ValidationUtil.isEmpty(companyId)) {
			wrapper.eq(Project::getConstructionUnitId,companyId);
		}

		return ResponseHelper.buildResponse(projectServiceImpl.list(wrapper));
	}

	/**
	 * 项目审核
	 * @param sequenceNbr
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "Post", value = "项目审核", notes = "项目审核")
	@PostMapping(value = "/processProject")
	public ResponseModel<String> processProject(@RequestParam("sequenceNbr") String sequenceNbr,String option,@RequestBody JSONObject json){
		Project project = projectServiceImpl.getById(sequenceNbr);
		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(project));
		jsonObject.put(XJConstant.PROCESS_PROJECT_STATE,"审核通过");
		String insDepId = json.getString(XJConstant.INS_DEPID);
		String insPerson = json.getString(XJConstant.INS_PRESON);
		if(!ValidationUtil.isEmpty(insPerson)){
			Map map = orgServiceImpl.getdetialInfo(insDepId);
			jsonObject.put(XJConstant.INS_PRESON,insPerson);
			//添加监检科室的回显
			jsonObject.put(XJConstant.INS_DEP,map.get("name"));
			jsonObject.put(XJConstant.PROCESS_PROJECT_STATE,"监检员待审核");
		} else if (!ValidationUtil.isEmpty(insDepId)) {

			Map map = orgServiceImpl.getdetialInfo(insDepId);
			jsonObject.put(XJConstant.INS_DEPID,map.get("sequenceNbr"));
			jsonObject.put(XJConstant.INS_DEP,map.get("name"));
			jsonObject.put(XJConstant.PROCESS_PROJECT_STATE,"监检员待分配");
		}
		if("0".equals(option)){
			jsonObject.put(XJConstant.PROCESS_PROJECT_STATE,"审核不通过");
		}
		if(ValidationUtil.isEmpty(option)){
			option = json.getString(XJConstant.PROCESS_PROJECT_STATE);
			if("1".equals(option)){
				jsonObject.put(XJConstant.PROCESS_PROJECT_STATE,"资料审批通过");
			} else if ("0".equals(option)){
				jsonObject.put(XJConstant.PROCESS_PROJECT_STATE,"资料审批不通过");
			} else if ("3".equals(option)){
				jsonObject.put(XJConstant.PROCESS_PROJECT_STATE,"监检科室待分配");
				option = "1";
			} else if ("4".equals(option)){
				jsonObject.put(XJConstant.PROCESS_PROJECT_STATE,"资料审核不通过");
				option = "0";
			}
		}
		if(ValidationUtil.isEmpty(option)){
			option = "1";
		}
		projectInitiationService.execute(project.getInstanceId(),jsonObject,option);
		return ResponseHelper.buildResponse("ok");
	}


	/**
	 * 审核员项目审核
	 * @param sequenceNbr
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "审核员项目审核", notes = "审核员项目审核")
	@PostMapping(value = "/insProcess")
	public ResponseModel<String> insProcess(String sequenceNbr,@RequestBody JSONObject json){
		String option = json.getString(XJConstant.PROCESS_PROJECT_STATE);
		Project project = projectServiceImpl.getById(sequenceNbr);
		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(project));
		jsonObject.put(XJConstant.PROCESS_PROJECT_STATE,"立项成功");
		if("0".equals(option)){
			jsonObject.put(XJConstant.PROCESS_PROJECT_STATE,"项目退回");
			projectInitiationService.execute(project.getInstanceId(),jsonObject,option);
			projectInitiationService.execute(project.getInstanceId(),jsonObject,option);
		}else if("2".equals(option)){
			jsonObject.put(XJConstant.PROCESS_PROJECT_STATE,"项目需重新提交资料");
		}
		projectInitiationService.execute(project.getInstanceId(),jsonObject,option);
		return ResponseHelper.buildResponse("ok");
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "POST", value = "添加附件", notes = "添加附件")
	@PostMapping(value = "/saveOrUpdateFile")
	public ResponseModel<String> saveOrUpdateFile(@RequestBody JSONObject jsonObject){
		String type = projectServiceImpl.saveOrUpdateFile(jsonObject);
		if ("over".equals(type)) {
			CommonResponseUtil.success(type,"提交成功！");
		} else if ("fail".equals(type)) {
			CommonResponseUtil.failure("资料尚未添加完成，不能提交！");
		} else {
			return CommonResponseUtil.success(type,"保存成功！");
		}
		return ResponseHelper.buildResponse(type);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "通过sequenceNbr查询项目详情", notes = "通过sequenceNbr查询项目详情")
	@GetMapping(value = "/getDetail")
	public ResponseModel<ProjectDto> getDetail(Long sequenceNbr){
		return ResponseHelper.buildResponse(projectServiceImpl.getDetail(sequenceNbr));
	}


	/**
	 * 查询当前登陆的建设单位和组织机构代码
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "查询当前登陆的建设单位和组织机构代码", notes = "查询当前登陆的建设单位和组织机构代码")
	@GetMapping(value = "/getConstructionInfo")
	public ResponseModel <Map> getConstructionInfo(){
		return ResponseHelper.buildResponse(orgServiceImpl.getConstructionInfo());
	}



	/**
	 * 项目进度
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "项目进度", notes = "项目进度")
	@GetMapping(value = "/projectSchedule")
	public ResponseModel <List<Map<String,String>>> projectSchedule(){
		return ResponseHelper.buildResponse(projectServiceImpl.projectSchedule());
	}

	/**
	 * 项目进度
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "项目进度", notes = "项目进度")
	@GetMapping(value = "/getProjectNumber")
	public ResponseModel<Map> getProjectNumber(){
		Map<String, Integer> map = new HashMap<>();
		map.put("num",0);
		List<Project> projects = projectResourceServiceImpl.getProjectList();
		if(!ValidationUtil.isEmpty(projects)){
			map.put("num",projects.size());
		}
		return ResponseHelper.buildResponse(map);
	}


	/**
	 * 项目概况
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "项目概况", notes = "项目概况")
	@GetMapping(value = "/projectOverview")
	public ResponseModel<List<Map<String,String>>> projectOverview(){
		return ResponseHelper.buildResponse(projectServiceImpl.projectOverview());
	}

	/**
	 * 当前辖区的在建项目
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "当前辖区的在建项目", notes = "当前辖区的在建项目")
	@GetMapping(value = "/projectInProgress")
	public ResponseModel<JSONObject> projectInProgress(){
		return ResponseHelper.buildResponse(projectServiceImpl.projectInProgress());
	}

	/**
	 * 获取当前登陆人所在单位下的项目的项目信息（包含经纬度信息）
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "获取当前登陆人所在单位下的项目的项目信息（包含经纬度信息）", notes = "获取当前登陆人所在单位下的项目的项目信息（包含经纬度信息）")
	@GetMapping(value = "/getProjectLocation")
	public ResponseModel<List<ProjectDto>> getProjectLocation(){
		return ResponseHelper.buildResponse(projectServiceImpl.getProjectLocation());
	}

}

