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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.module.hygf.api.config.UserLimits;
import com.yeejoin.amos.boot.module.hygf.api.dto.BasicGridAcceptanceDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.BasicGridRecordDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.UserUnitInformationDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.AcceptanceCheckItem;
import com.yeejoin.amos.boot.module.hygf.api.entity.HygfOnGrid;
import com.yeejoin.amos.boot.module.hygf.api.entity.HygfRectificationOrder;
import com.yeejoin.amos.boot.module.hygf.api.mapper.BasicGridAcceptanceMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.HygfOnGridMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PersonnelBusinessMapper;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.BasicGridAcceptanceServiceImpl;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.WorkflowImpl;
import com.yeejoin.amos.component.robot.BadRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
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 java.util.*;

/**
 *
 *
 * @author system_generator
 * @date 2024-01-16
 */
@RestController
@Api(tags = "并网Api")
@RequestMapping(value = "/basic-grid-acceptance")
public class BasicGridAcceptanceController extends BaseController {

	@Autowired
	BasicGridAcceptanceServiceImpl basicGridAcceptanceServiceImpl;
	@Autowired
	BasicGridAcceptanceMapper basicGridAcceptanceMapper;
	@Autowired
	HygfOnGridMapper onGridMapper;
	@Autowired
	PersonnelBusinessMapper personnelBusinessMapper;
	@Autowired
	WorkflowImpl workflow;

	@Value("${admin.engineering.roleId}")
	Long engineeringId;
	@Value("${admin.area.roleId}")
	Long areaId;
	@Value("${admin.design.roleId}")
	Long designId;
	@Value("${admin.delerAdmin.roleId}")
	Long delerAdminId;

	/**
	 * 新增保存
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
	public ResponseModel save(@RequestBody HygfOnGrid dto) {

		return ResponseHelper.buildResponse(basicGridAcceptanceServiceImpl.saveEntity(dto));
	}

	/**
	 * 新增保存
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save/commit")
	@ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
	@Transactional
	public ResponseModel saveAndCommit(@RequestBody HygfOnGrid dto) {

		return ResponseHelper.buildResponse(
				basicGridAcceptanceServiceImpl.saveAndCommit(dto, getSelectedOrgInfo().getUserModel().getRealName()));
	}

	/**
	 * 根据sequenceNbr更新
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新", notes = "根据sequenceNbr更新")
	public ResponseModel updateBySequenceNbrBasicGridAcceptance(@RequestBody HygfOnGrid model,
			@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
		model.setSequenceNbr(sequenceNbr);
		return ResponseHelper.buildResponse(basicGridAcceptanceServiceImpl.modifyEntity(model));
	}

	/**
	 * 根据sequenceNbr删除
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@DeleteMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除", notes = "根据sequenceNbr删除")
	public ResponseModel<Boolean> deleteBySequenceNbr(@RequestParam("sequenceNbrs") Long[] sequenceNbrs) {
		return ResponseHelper.buildResponse(basicGridAcceptanceServiceImpl.deleteForBatch(sequenceNbrs));
	}

	/**
	 * 根据sequenceNbr查询
	 *
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个", notes = "根据sequenceNbr查询单个")
	public ResponseModel<BasicGridAcceptanceDto> selectOne(@PathVariable Long sequenceNbr) {
		return ResponseHelper.buildResponse(basicGridAcceptanceServiceImpl.queryBySeq(sequenceNbr));
	}

	/**
	 * 经销商端列表分页查询
	 *
	 * @param current 当前页
	 * @param current 每页大小
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/page")
	@ApiOperation(httpMethod = "GET", value = "分页查询", notes = "分页查询")
	@UserLimits
	public ResponseModel<Page<BasicGridRecordDto>> queryForPage(@RequestParam(value = "current") int current,
			@RequestParam(value = "size") int size,
			@RequestParam(required = false, value = "projectAddress") String projectAddress,
			@RequestParam(required = false, value = "powerStationCode") String powerStationCode,
			@RequestParam(required = false, value = "ownersName") String ownersName,
			@RequestParam(required = false, value = "gridStatus") String gridStatus,
			@RequestParam(required = false, value = "type") String type,
			@RequestParam(required = false, value = "gridConnectionTime") String gridConnectionTime,
			@RequestParam(required = false, value = "province") String province,
			@RequestParam(required = false, value = "developerName") String developerName,
			@RequestParam(required = false, value = "regionalCompaniesName") String regionalCompaniesName,
			@RequestParam(required = false, value = "startTime") String startTime,
			@RequestParam(required = false, value = "endTime") String endTime) throws Exception {
		// 当前登录人所属场站
//        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto( getUserInfo().getUserId());

		ReginParams reginParams = getSelectedOrgInfo();
		List<String> basicGridNodes = new ArrayList<>();
		List<Long> roleIds = new ArrayList<>();
		for (Long aLong : reginParams.getUserModel().getOrgRoleSeqs().keySet()) {
			List<Long> longs = reginParams.getUserModel().getOrgRoleSeqs().get(aLong);
			roleIds.addAll(longs);
			if (longs.contains(areaId)) {
				basicGridNodes.add("bw-area");
			}
			if (longs.contains(engineeringId)) {
				basicGridNodes.add("bw-engineering");
			}
			if (longs.contains(designId)) {
				basicGridNodes.add("bw-design");
			}
			if (longs.contains(delerAdminId)) {
				basicGridNodes.add("bw-design");
				basicGridNodes.add("bw-engineering");
				basicGridNodes.add("bw-area");
			}
		}
		Page<BasicGridRecordDto> page = basicGridAcceptanceServiceImpl.selectPage(null, null, current, size,
				projectAddress, powerStationCode, ownersName, gridStatus, gridConnectionTime, "", basicGridNodes, type,
				province, developerName, regionalCompaniesName, startTime, endTime);
		// 根据角色及当前节点判断是否有操作权限
		if (basicGridNodes != null) {
			for (BasicGridRecordDto e : page.getRecords()) {
				for (String g : basicGridNodes) {
					if (null != e.getBasicGridNode() && e.getBasicGridNode().contains(g) && (roleIds.contains(areaId)
							|| roleIds.contains(designId) || roleIds.contains(engineeringId))) {
						e.setIsAudit("0");
						break;
					} else {
						e.setIsAudit("1");
					}
				}
			}
		}
		return ResponseHelper.buildResponse(page);
	}

	/**
	 * 审核管理端列表分页查询
	 *
	 * @param current 当前页
	 * @param current 每页大小
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/check/page")
	@ApiOperation(httpMethod = "GET", value = "分页查询", notes = "分页查询")
	@UserLimits
	public ResponseModel<Page<BasicGridRecordDto>> queryForCheckPage(@RequestParam(value = "current") int current,
			@RequestParam(value = "size") int size,
			@RequestParam(required = false, value = "projectAddress") String projectAddress,
			@RequestParam(required = false, value = "powerStationCode") String powerStationCode,
			@RequestParam(required = false, value = "ownersName") String ownersName,
			@RequestParam(required = false, value = "gridStatus") String gridStatus,
			@RequestParam(required = false, value = "gridConnectionTime") String gridConnectionTime,
			@RequestParam(required = false, value = "province") String province) throws Exception {
		// 当前登录人所属场站

		Page<BasicGridRecordDto> page = basicGridAcceptanceServiceImpl.selectPage(null, null, current, size,
				projectAddress, powerStationCode, ownersName, gridStatus, gridConnectionTime, "check", null, null,province, null, null, null, null);
		return ResponseHelper.buildResponse(page);
	}

	/**
	 * 列表全部数据查询
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "列表全部数据查询", notes = "列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<BasicGridAcceptanceDto>> selectForList() {
		return ResponseHelper.buildResponse(Collections.emptyList());
	}

	// 并网审核

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/execute")
	@ApiOperation(httpMethod = "POST", value = "执行工作流", notes = "执行工作流")
	public ResponseModel execute(@RequestBody AcceptanceCheckItem dto) {
		basicGridAcceptanceServiceImpl.execute(dto, getUserId());
		return ResponseHelper.buildResponse(null);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "POST", value = "完工自审-经销商管理", notes = "完工自审经销商管理")
	@PostMapping(value = "/completeAdminAudit")
	@Transactional
	public ResponseModel completeAdminAudit(@RequestBody Map<String, String> kv) {
		basicGridAcceptanceServiceImpl.completeAdminAudit(kv);
		return ResponseHelper.buildResponse(null);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "POST", value = "完工自审管理审核", notes = "完工自审管理审核")
	@PostMapping(value = "/completeAudit")
	@Transactional
	public ResponseModel completeAudit(@RequestBody Map<String, String> kv) {
		return basicGridAcceptanceServiceImpl.completeAudit(kv);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "整改单下发", notes = "整改单下发")
	@PostMapping(value = "/addRectification")
	@Transactional
	public ResponseModel addRectification(@RequestBody HygfRectificationOrder hygfReplenishment) {

		return basicGridAcceptanceServiceImpl.addRectification(hygfReplenishment);

	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "POST", value = "整改单添加信息", notes = "整改单添加信息")
	@PostMapping(value = "/nextTaskExcute")
	@Transactional
	public ResponseModel nextTaskExcute(@RequestBody HygfRectificationOrder hygfReplenishment) {

		return basicGridAcceptanceServiceImpl.nextTaskExcute(hygfReplenishment);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "POST", value = "整改单审核", notes = "整改单审核")
	@PostMapping(value = "/nextTaskAduit")
	@Transactional
	public ResponseModel nextTaskAduit(@RequestBody HygfRectificationOrder hygfReplenishment) {

		return basicGridAcceptanceServiceImpl.nextTaskAduit(hygfReplenishment);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "PUT", value = "整改单作废", notes = "整改单作废")
	@PutMapping(value = "/rollback")
	@Transactional
	public ResponseModel rollback(@RequestParam(value = "sequenceNbr") Long sequenceNbr) {

		return basicGridAcceptanceServiceImpl.rollback(sequenceNbr);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/test1")
	@ApiOperation(httpMethod = "POST", value = "执行工作流", notes = "执行工作流")
	public ResponseModel test() {
		basicGridAcceptanceServiceImpl.testKAIQI();
		return ResponseHelper.buildResponse(null);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/test2")
	@ApiOperation(httpMethod = "POST", value = "执行工作流", notes = "执行工作流")
	public ResponseModel test(String approvalStatus, String comment) {
		basicGridAcceptanceServiceImpl.zhixing(approvalStatus, comment);
		return ResponseHelper.buildResponse(null);
	}

}
