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.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.ugp.api.Enum.NoticeStatusEnum;
import com.yeejoin.amos.boot.module.ugp.api.Enum.ProjectInitiationEnum;
import com.yeejoin.amos.boot.module.ugp.api.Enum.WhetherItPassEnum;
import com.yeejoin.amos.boot.module.ugp.api.constants.XJConstant;
import com.yeejoin.amos.boot.module.ugp.api.dto.InstallNoticeDto;
import com.yeejoin.amos.boot.module.ugp.api.dto.InstallNoticePageDto;
import com.yeejoin.amos.boot.module.ugp.api.dto.ProjectDto;
import com.yeejoin.amos.boot.module.ugp.api.entity.InstallNotice;
import com.yeejoin.amos.boot.module.ugp.api.entity.Project;
import com.yeejoin.amos.boot.module.ugp.biz.fegin.TzsServiceFeignClient;
import com.yeejoin.amos.boot.module.ugp.biz.service.impl.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 安装告知表
 *
 * @author system_generator
 * @date 2022-09-22
 */
@RestController
@Api(tags = "安装告知表Api")
@RequestMapping(value = "/install-notice")
public class InstallNoticeController extends BaseController {

	@Autowired
	InstallNoticeServiceImpl installNoticeServiceImpl;

	@Autowired
	ProjectInitiationServiceImpl projectInitiationServiceImpl;

	@Autowired
	ProjectServiceImpl projectServiceImpl;

	@Autowired
	OrgServiceImpl orgServiceImpl;

	@Autowired
	UnitLicenceServiceImpl unitLicenceService;

	@Resource
	private InstallNoticeServiceImpl iInstallNoticeService;

	@Resource
	private IPipeServiceImpl pipeService;

	@Resource
	private ProjectResourceServiceImpl projectResourceService;

	@Resource
	private MaterialServiceImpl materialService;

	@Resource
	private TzsServiceFeignClient tzsServiceFeignClient;


	/**
	 * 新增安装告知表
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增安装告知表", notes = "新增安装告知表")
	public ResponseModel<InstallNoticeDto> save(@RequestBody InstallNoticeDto model) {
		model = installNoticeServiceImpl.createWithModel(model);
		return ResponseHelper.buildResponse(model);
	}

	/**
	 * 根据sequenceNbr更新
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@PutMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新", notes = "根据sequenceNbr更新")
	public ResponseModel<InstallNoticeDto> updateBySequenceNbrInstallNotice(@RequestBody InstallNoticeDto model, @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
		return ResponseHelper.buildResponse(installNoticeServiceImpl.updateWithModel(model));
	}

	/**
	 * 根据sequenceNbr删除
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@DeleteMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除安装告知表", notes = "根据sequenceNbr删除安装告知表")
	public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
		return ResponseHelper.buildResponse(installNoticeServiceImpl.removeById(sequenceNbr));
	}

	/**
	 * 根据sequenceNbr查询
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个安装告知表", notes = "根据sequenceNbr查询单个安装告知表")
	public ResponseModel<InstallNoticeDto> selectOne(@PathVariable Long sequenceNbr) {
		return ResponseHelper.buildResponse(installNoticeServiceImpl.queryBySeq(sequenceNbr));
	}
	/**
	 * 列表分页查询
	 *
	 * @param current 当前页
	 * @param current 每页大小
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/page")
	@ApiOperation(httpMethod = "GET", value = "安装告知表分页查询", notes = "安装告知表分页查询")
	public ResponseModel<Page<InstallNoticeDto>> queryForPage(@RequestParam(value = "current") int current, @RequestParam
			(value = "size") int size) {
		Page<InstallNoticeDto> page = new Page<InstallNoticeDto>();
		page.setCurrent(current);
		page.setSize(size);
		return ResponseHelper.buildResponse(installNoticeServiceImpl.queryForInstallNoticePage(page));
	}

	/**
	 * 列表分页查询
	 *
	 * @param current 当前页
	 * @param current 每页大小
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/installNoticePage")
	@ApiOperation(httpMethod = "GET", value = "安装告知表分页查询", notes = "安装告知表分页查询")
	public ResponseModel<Page<InstallNoticePageDto>> queryForPage1(@RequestParam(value = "current") int current, @RequestParam
			(value = "size") int size,@RequestParam(required = false) String name,@RequestParam(required = false) String constructionUnit) {
		Page<InstallNoticePageDto> page = new Page<InstallNoticePageDto>();
		page.setCurrent(current);
		page.setSize(size);
		return ResponseHelper.buildResponse(installNoticeServiceImpl.installNoticePage(page,name,constructionUnit));
	}
	/**
	 * 列表全部数据查询
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "安装告知表列表全部数据查询", notes = "安装告知表列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<InstallNoticeDto>> selectForList() {
		return ResponseHelper.buildResponse(installNoticeServiceImpl.queryForInstallNoticeList());
	}

	/**
	 * 根据主键sequenceNbr查询安装告知申请详情
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping ("")
	@ApiOperation(httpMethod = "GET", value = "查询安装告知申请详情", notes = "查询安装告知申请详情")
	public ResponseModel<InstallNoticeDto> installNoticeinfoById(@RequestParam ("sequenceNbr") Long sequenceNbr){
		return ResponseHelper.buildResponse(installNoticeServiceImpl.selectOneById(sequenceNbr));
	}

	/**
	 * 提交申请
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@PutMapping(value = "/submit/{sequenceNbr}")
	@ApiOperation(httpMethod = "put", value = "根据sequenceNbr更新提交申请", notes = "根据sequenceNbr更新提交申请")
	public ResponseModel<InstallNoticeDto> InstallNoticeSubmit(@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
		final InstallNoticeDto model = installNoticeServiceImpl.selectOneById(sequenceNbr);
		Project project = projectServiceImpl.getById(model.getProjectId());
		if (model.getNoticeStatus().equals("已保存")){
			model.setNoticeStatus("已提交");
			installNoticeServiceImpl.updateWithModel(model);
			projectInitiationServiceImpl.execute(project.getInstanceId(),model,"1",null);
		}
		return ResponseHelper.buildResponse(model);
	}

	/**
	 * 新增安装告知申请,保存/提交
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@PostMapping (value = "/saveInstallNotice")
	@ApiOperation(httpMethod = "Post", value = "新增安装告知申请", notes = "新增安装告知申请")
	public ResponseModel<InstallNoticeDto> saveInstallNotice(@RequestBody JSONObject object,@RequestParam(required = false) String noticeStatus,@RequestParam(required = false)String installId) {
		return  ResponseHelper.buildResponse(installNoticeServiceImpl.saveInstallNotice(object, noticeStatus,installId));
	}

	/**
	 * 根据sequenceNbr查询安装告知信息及附件
	 *
	 * @param sequenceNbr  主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/message/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET",value = "根据sequenceNbr安装告知信息",  notes = "根据sequenceNbr安装告知信息")
	public ResponseModel<JSONObject> selectOneBySeq(@PathVariable Long sequenceNbr) {

		JSONObject jsonObject = installNoticeServiceImpl.selectOneBySeq(sequenceNbr);
		return ResponseHelper.buildResponse(jsonObject);
	}

	/**
	 * 根据sequenceNbr修改安装告知信息及附件
	 *
	 * @param sequenceNbr  主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@PutMapping(value = "/message/{sequenceNbr}")
	@ApiOperation(httpMethod = "put",value = "根据sequenceNbr安装告知信息",  notes = "根据sequenceNbr安装告知信息")
	public ResponseModel<InstallNoticeDto> updateOneBySeq(@PathVariable Long sequenceNbr,@RequestBody JSONObject object,@RequestParam(required = false) String noticeStatus) {

		final InstallNoticeDto installNoticeDto = installNoticeServiceImpl.selectOneById(sequenceNbr);

		if (installNoticeDto.getNoticeStatus().equals("已保存")){
			installNoticeDto.setNoticeStatus(noticeStatus);
		}
		installNoticeDto.setProjectId(object.getLong("projectId"));
		installNoticeDto.setLicenseNum(object.getString("licenseNum"));
		installNoticeDto.setLicenseCompany(object.getString("licenseCompany"));
		final JSONArray licenseAttch = object.getJSONArray("licenseAttch");
		final JSONArray contractAttch = object.getJSONArray("contractAttch");
		installNoticeDto.setInstallPri(object.getString("installPri"));
		installNoticeDto.setLicenseAttch(JSON.toJSONString(licenseAttch));
		installNoticeDto.setContractAttch(JSON.toJSONString(contractAttch));

		return ResponseHelper.buildResponse(installNoticeServiceImpl.updateWithModel(installNoticeDto));
	}


	/**
	 * 根据sequenceNbr删除安装告知表
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@DeleteMapping(value = "message/{sequenceNbr}")
	@ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除安装告知表", notes = "根据sequenceNbr删除安装告知表")
	public ResponseModel<Boolean> deleteBySeq(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
		final InstallNoticeDto installNoticeDto = installNoticeServiceImpl.selectOneById(sequenceNbr);
		final String noticeStatus = installNoticeDto.getNoticeStatus();
		if (!noticeStatus.equals("已接收")){
			return ResponseHelper.buildResponse(installNoticeServiceImpl.removeById(sequenceNbr));
		}
		return  ResponseHelper.buildResponse(false);

	}

	/**
	 * 查询当前登陆人所在单位下的可选告知申请的所有项目列表
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "查询当前登陆人所在单位下的所以项目列表", notes = "查询当前登陆人所在单位下的所以项目列表")
	@GetMapping(value = "/getProjects")
	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<Project>();
		if (!ValidationUtil.isEmpty(companyId)) {
		wrapper.eq(Project::getInstallationUnitId,companyId).eq(Project::getStatus,ProjectInitiationEnum.告知申请.getName());
		}
		return ResponseHelper.buildResponse(projectServiceImpl.list(wrapper));
	}

	/**
	 * 监察部门接受安装告知
	 * @param sequenceNbr
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/acceptNotification")
	@ApiOperation(httpMethod = "GET", value = "监察部门接受安装告知", notes = "监察部门接受安装告知")
	public ResponseModel<Boolean> acceptNotification(Long sequenceNbr){
		InstallNotice installNotice = installNoticeServiceImpl.getById(sequenceNbr);
		installNotice.setNoticeStatus(NoticeStatusEnum.已接收.getName());
		Project project = projectServiceImpl.getById(installNotice.getProjectId());
		JSONObject json = JSON.parseObject(JSON.toJSONString(installNotice));
		json.put(XJConstant.PROCESS_PROJECT_STATE,"告知待审核");
		projectInitiationServiceImpl.execute(project.getInstanceId(),json,NoticeStatusEnum.已接收.getStatusId(),null);
		return ResponseHelper.buildResponse(installNoticeServiceImpl.updateById(installNotice));
	}

	/**
	 * 监检部门审查(通过/退回)安装告知
	 * @param sequenceNbr
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/inspectNotification")
	@ApiOperation(httpMethod = "GET", value = "监检部门审查(通过/退回)安装告知", notes = "监检部门审查(通过/退回)安装告知")
	public ResponseModel<Boolean> inspectNotification(Long sequenceNbr,String option){
		InstallNotice installNotice = installNoticeServiceImpl.getById(sequenceNbr);
		installNotice.setApproved(true);
		installNotice.setNoticeStatus(NoticeStatusEnum.已通过.getName());
		if(NoticeStatusEnum.已退回.getStatusId().equals(option)){
			installNotice.setApproved(false);
			installNotice.setNoticeStatus(NoticeStatusEnum.已退回.getName());
		}
		Project project = projectServiceImpl.getById(installNotice.getProjectId());
		projectInitiationServiceImpl.execute(project.getInstanceId(),installNotice,option,null);
		return ResponseHelper.buildResponse(installNoticeServiceImpl.updateById(installNotice));
	}

	/**
	 * 新增告知时页面回显接口
	 * @param projectId
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/getInstallNoticeByProjectId")
	@ApiOperation(httpMethod = "GET", value = "新增告知时页面回显接口", notes = "新增告知时页面回显接口")
	public ResponseModel<JSONObject> getInstallNoticeByProjectId(Long projectId){
		if(ValidationUtil.isEmpty(projectId)){
			return null;
		}
		JSONObject jsonObject = new JSONObject();
		ProjectDto projectDto = projectServiceImpl.getDetail(projectId);
		Map map = new org.apache.commons.beanutils.BeanMap(projectDto);
		jsonObject.putAll(map);
		//项目指定的安装单位的许可信息
		Long companyId = projectDto.getInstallationUnitId();
		jsonObject = unitLicenceService.getLicenceByCompanyId(jsonObject,companyId);
		return ResponseHelper.buildResponse(jsonObject);
	}

	/**
	 * 新增/修改安装告知表信息
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@PostMapping(value = "/saveOrUpdate")
	@ApiOperation(value = "新增/修改安装告知表信息", notes = "新增/修改安装告知表信息")
	public ResponseModel<InstallNoticeDto> saveOrUpdate(@RequestBody JSONObject jsonObject) {
		InstallNoticeDto model = JSON.parseObject(JSON.toJSONString(jsonObject.get("noticeInfo")), InstallNoticeDto.class);
		Long projectId = Long.valueOf(String.valueOf(jsonObject.get("projectId")));
		Project project = projectServiceImpl.getById(projectId);
		model.setProjectId(projectId);
		model.setNoticeStatus(String.valueOf(jsonObject.get("noticeStatus")));
		LambdaQueryWrapper<InstallNotice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(InstallNotice::getProjectId, model.getProjectId());
		lambdaQueryWrapper.eq(InstallNotice::getIsDelete, Boolean.FALSE);
		InstallNotice one = iInstallNoticeService.getOne(lambdaQueryWrapper);
		if (ObjectUtils.isNotEmpty(one)) {
			model.setSequenceNbr(one.getSequenceNbr());
		}
		InstallNotice installNotice = new InstallNotice();
		BeanUtils.copyProperties(model, installNotice);
		installNotice.setNoticeDate(new Date());
		installNotice.setOrganizationCode(orgServiceImpl.getOrgUsr().getBizOrgCode());
		iInstallNoticeService.saveOrUpdate(installNotice);
		if (!WhetherItPassEnum.SAVE.getCode().equals(model.getNoticeStatus())) {
			projectInitiationServiceImpl.execute(project.getInstanceId(), model, model.getNoticeStatus(), null);
		}
		return ResponseHelper.buildResponse(model);
	}

	/**
	 * 告知页面回显内容
	 * @param projectId 由于跳转是已有功能，前端处理传参为行数据的 sequenceNbr字段 所以这里的接参的参数名改为 sequenceNbr
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/getInfoByProjectId")
	@ApiOperation(value = "告知页面回显内容", notes = "告知页面回显内容")
	public ResponseModel<JSONObject> getInfoByProjectId(@RequestParam("sequenceNbr") Long projectId) {
		if (ObjectUtils.isEmpty(projectId)) {
			return null;
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("noticeInfo",iInstallNoticeService.getInfoByProjectId(projectId));
		jsonObject.put("projectInfo",projectServiceImpl.selectById(projectId));
		return ResponseHelper.buildResponse(jsonObject);
	}
}
