/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yifu4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.yifu.cloud.plus.v1.yifu.archives.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TDepartSettlementInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TSettleDomain;
import com.yifu.cloud.plus.v1.yifu.archives.service.TDepartSettlementInfoService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TSettleDomainService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ClientNameConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.MenuUtil;
import com.yifu.cloud.plus.v1.yifu.common.log.annotation.SysLog;
import com.yifu.cloud.plus.v1.yifu.common.security.annotation.Inner;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 项目表
 *
 * @author hgw
 * @date 2022-06-20 10:02:28
 */
@RestController
@RequiredArgsConstructor
@Log4j2
@RequestMapping("/tsettledomain")
@Tag(name = "项目表管理")
public class TSettleDomainController {

	private final TSettleDomainService tSettleDomainService;
	private final TDepartSettlementInfoService tDepartSettlementInfoService;
	private final MenuUtil menuUtil;
	/**
	 * 分页查询
	 *
	 * @param page          分页对象
	 * @param tSettleDomain 项目表
	 * @return
	 */
	// 	2022-9-27 16:36:56hgw备注：前端用这个接口模糊搜索项目信息：/yifu-archives/method/tempchangeinfo/getAllDeptPage
	@Operation(summary = "分页查询", description = "分页查询")
	@GetMapping("/page")
	public R<IPage<TSettleDomain>> getTSettleDomainPage(Page<TSettleDomain> page, TSettleDomain tSettleDomain) {
		YifuUser user = SecurityUtils.getUser();
		long roleId = 1839501715787390978L;
		boolean isSsc =	false;
		List<Long> roleList = user.getClientRoleMap().get(ClientNameConstants.CLIENT_MVP);
		for (Long role : roleList) {
			if (role == roleId) {
				isSsc =  true;
				break;
			}
		}
		if (!isSsc) {
			menuUtil.setAuthSql(user, tSettleDomain);
			if (Common.isNotNull(tSettleDomain.getAuthSql()) && tSettleDomain.getAuthSql().contains("or a.dept_id")) {
				tSettleDomain.setAuthSql(tSettleDomain.getAuthSql().replace("or a.dept_id", "or a.id "));
			}
		}
		return R.ok(tSettleDomainService.getPage(page, tSettleDomain));
	}

	/**
	 * 二级指标归属分页查询
	 *
	 * @param page          分页对象
	 * @param tSettleDomain 项目表
	 * @return
	 */
	@Operation(summary = "分页查询", description = "分页查询")
	@GetMapping("/twoBlongPage")
	public R<IPage<SecondBelongVo>> getTwoBlongPage(Page<TSettleDomain> page, TSettleDomain tSettleDomain) {
		return R.ok(tSettleDomainService.getTwoBlongPage(page, tSettleDomain));
	}

	/**
	 * 不分页查询
	 *
	 * @param tSettleDomain 项目表
	 * @return
	 */
	@Operation(summary = "不分页查询", description = "不分页查询")
	@GetMapping("/noPage")
	public R<List<TSettleDomain>> getTSettleDomainNoPage(TSettleDomain tSettleDomain) {
		return R.ok(tSettleDomainService.getList(tSettleDomain));
	}


	/**
	 * 通过id查询项目表
	 *
	 * @param id id
	 * @return R
	 */
	@Operation(summary = "通过id查询", description = "通过id查询")
	@GetMapping("/{id}")
	public R<TSettleDomain> getById(@PathVariable("id") String id) {
		return tSettleDomainService.getByIdAsso(id);
	}

	/**
	 * 新增项目表
	 *
	 * @param tSettleDomain 项目表
	 * @return R
	 */
	@Operation(summary = "新增项目表", description = "新增项目表")
	@SysLog("新增项目表")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('tsettledomain_add')")
	public R<Boolean> save(@RequestBody TSettleDomain tSettleDomain) {
		return R.ok(tSettleDomainService.save(tSettleDomain));
	}

	/**
	 * 修改项目表
	 *
	 * @param tSettleDomain 项目表
	 * @return R
	 */
	@Operation(summary = "修改项目表", description = "修改项目表")
	@SysLog("修改项目表")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('tsettledomain_edit')")
	public R<Boolean> updateById(@RequestBody TSettleDomain tSettleDomain) {
		return R.ok(tSettleDomainService.updateById(tSettleDomain));
	}

	/**
	 * 通过id删除项目表
	 *
	 * @param id id
	 * @return R
	 */
	@Operation(summary = "通过id删除项目表", description = "通过id删除项目表")
	@SysLog("通过id删除项目表")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('tsettledomain_del')")
	public R<Boolean> removeById(@PathVariable String id) {
		return R.ok(tSettleDomainService.removeById(id));
	}

	/**
	 * 获取登录用户拥有的项目信息及单位部分信息
	 *
	 * @param
	 * @return
	 * @Author fxj
	 * @Date 2019-08-28
	 **/
	@Operation(description = "获取登录用户拥有的项目数据）")
	@Inner
	@PostMapping("/getSettleDomainIdsByUserId")
	public TSettleDomainListVo getSettleDomainIdsByUserId(@RequestBody String userId) {
		TSettleDomainListVo vo = new TSettleDomainListVo();
		vo.setDeptIds(tSettleDomainService.getSettleDomainIdsByUserId(userId));
		vo.setDeptNos(tSettleDomainService.getSettleDomainNosByUserId(userId));
		return vo;
	}

	/**
	 * 获取登录用户拥有的项目信息及单位部分信息
	 *
	 * @param
	 * @return
	 * @Author fxj
	 * @Date 2019-08-28
	 **/
	@Operation(description = "获取登录用户拥有的项目数据）")
	@Inner
	@PostMapping("/getPermissionByUserId")
	public TSettleDomainListVo getPermissionByUserId(@RequestBody String userId) {
		TSettleDomainListVo vo = new TSettleDomainListVo();
		vo.setDeptIds(tSettleDomainService.getSettleDomainIdsByUserId(userId));
		return vo;
	}

	/**
	 * @param
	 * @Author: wangan
	 * @Date: 2019/10/18
	 * @Description:通过id获取项目及单位部分信息
	 **/
	@Inner
	@PostMapping("/getSettleDomainSelectVoById")
	public TSettleDomainSelectVo getInnerSettleDomainSelectVoByUserId(@RequestBody TSettleDomainSelectVo settleDomainSelectVo) {
		return tSettleDomainService.selectSettleDomainSelectVosById(settleDomainSelectVo);
	}

	/**
	 * @param
	 * @Author: wangan
	 * @Date: 2019/10/18
	 * @Description:获取所有客户单位的项目信息
	 **/
	@Inner
	@PostMapping("/selectAllSettleDomainSelectVos")
	public TSettleDomainListVo selectAllSettleDomainSelectVos() {
		List<TSettleDomainSelectVo> list = tSettleDomainService.selectAllSettleDomainSelectVos();
		TSettleDomainListVo listVo = new TSettleDomainListVo();
		listVo.setListSelectVO(list);
		if (Common.isNotNull(list)){
			listVo.setMapSelectVo(list.stream().collect(Collectors.toMap(TSettleDomain::getDepartNo, k->k, (existing, replacement) -> existing)));
		}
		return listVo;
	}

	/**
	 * @param
	 * @Author: wangan
	 * @Date: 2019/10/18
	 * @Description:获取所有客户单位的项目信息
	 **/
	@Inner
	@PostMapping("/selectAllSettleDomainSelectVo")
	public TSettleDomainListVo selectAllSettleDomainSelectVo() {
		List<TSettleDomainSelectVo> list = tSettleDomainService.selectAllSettleDomainSelectVos();
		TSettleDomainListVo listVo = new TSettleDomainListVo();
		listVo.setListSelectVO(list);
		if (Common.isNotNull(list)){
			listVo.setMapSelectVo(list.stream().collect(Collectors.toMap(TSettleDomain::getId, k->k, (existing, replacement) -> existing)));
		}
		return listVo;
	}

	/**
	 * @param
	 * @Author: wangan
	 * @Date: 2019/10/18
	 * @Description:获取所有客户单位的项目信息
	 **/
	@Inner
	@PostMapping("/selectSettleDomainSelectVoById")
	public TSettleDomainListVo selectSettleDomainSelectVoById(@RequestBody TSettleDomainSelectVo tSettleDomainSelectVo) {
		List<TSettleDomainSelectVo> list = new ArrayList<>();
		TSettleDomain tSettleDomain = tSettleDomainService.getById(tSettleDomainSelectVo.getId());
		BeanUtils.copyProperties(tSettleDomain,tSettleDomainSelectVo);
		tSettleDomainSelectVo.setCustomerCode(tSettleDomain.getCustomerNo());
		list.add(tSettleDomainSelectVo);
		TSettleDomainListVo listVo = new TSettleDomainListVo();
		listVo.setListSelectVO(list);
		return listVo;
	}

	/**
	 * @param
	 * @Author: wangan
	 * @Date: 2019/10/18
	 * @Description:获取所有客户单位的项目信息
	 **/
	@Inner
	@PostMapping("/selectSettleDomainSelectVoByNo")
	public TSettleDomainListVo selectSettleDomainSelectVoByNo(@RequestBody TSettleDomainSelectVo tSettleDomainSelectVo) {
		List<TSettleDomainSelectVo> list = new ArrayList<>();
		TSettleDomain tSettleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
				.eq(TSettleDomain::getDepartNo, tSettleDomainSelectVo.getDepartNo())
				.eq(TSettleDomain::getDeleteFlag, CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (tSettleDomain != null) {
			BeanUtils.copyProperties(tSettleDomain, tSettleDomainSelectVo);
			tSettleDomainSelectVo.setCustomerCode(tSettleDomain.getCustomerNo());
		}
		list.add(tSettleDomainSelectVo);
		TSettleDomainListVo listVo = new TSettleDomainListVo();
		listVo.setListSelectVO(list);
		return listVo;
	}

	/**
	 * @Author fxj
	 * @Description  通过项目编码获取项目及客户信息
	 * @Date 10:49 2022/7/20
	 * @Param
	 * @return
	**/
	@Operation(description = "通过项目编码获取项目及客户信息")
	@SysLog("通过项目编码获取项目及客户信息")
	@Inner
	@PostMapping("/getSetInfoByCodes")
	public SetInfoVo getSetInfoByCodes(@RequestBody(required = true) List<String> codes) {
		return  tSettleDomainService.getSetInfoByCodes(codes);
	}

	/**
	 * @Author fxj
	 * @Description  通过项目编码获取项目及客户信息
	 * @Date 10:49 2022/7/20
	 * @Param
	 * @return
	 **/
	@Operation(description = "通过项目编码获取项目及客户信息")
	@SysLog("通过项目编码获取项目及客户信息")
	@Inner
	@PostMapping("/getSettleInfoByCodes")
	public TSettleDomainListVo getSettleInfoByCodes(@RequestBody List<String> codes) {
		return tSettleDomainService.getSettleInfoByCodes(codes);
	}

	/**
	 * @Author huych
	 * @Description  通过项目编码获取项目信息
	 * @Date 11:37 2025/3/3
	 * @Param
	 * @return
	 **/
	@Operation(description = "通过项目编码获取项目信息")
	@SysLog("通过项目编码获取项目信息")
	@PostMapping("/getSettleDomainByNo")
	public R getSettleDomainByNo(@RequestParam String deptNo) {
		TSettleDomain tSettleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
				.eq(TSettleDomain::getDepartNo, deptNo)
				.eq(TSettleDomain::getDeleteFlag,CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		return R.ok(tSettleDomain);
	}

	/**
	 * @param id 项目主键
	 * @Description: 通过id获取结算主体及单位部分信息
	 * @Author: hgw
	 * @Date: 2022/8/10 17:01
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainSelectVo>
	 **/
	@Inner
	@PostMapping("/inner/getSettleDomainVoById")
	public TSettleDomainSelectVo getSettleDomainVoById(@RequestBody String id) {
		return tSettleDomainService.getSettleDomainVoById(id);
	}
	/**
	 * @param deptNo 项目主键
	 * @Description: 通过id获取结算主体及单位部分信息
	 * @Author: hgw
	 * @Date: 2022/8/10 17:01
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainSelectVo>
	 **/
	@Inner
	@PostMapping("/inner/getSettleDomainVoByNo")
	public TSettleDomainSelectVo getSettleDomainVoByNo(@RequestBody String deptNo) {
		return tSettleDomainService.getSettleDomainVoByNo(deptNo);
	}

	/**
	 * @param deptId 结算主体id
	 * @Description: 根据结算主体查询结算配置
	 * @Author: hgw
	 * @Date: 2022-8-10 18:14:31
	 * @return: com.yifu.cloud.v1.common.core.util.R<com.yifu.cloud.v1.hrms.api.entity.TDepartSettlementInfo>
	 **/
	@Inner
	@PostMapping("/inner/getInnerBySettlementId")
	public TDepartSettlementInfo getInnerBySettlementId(@RequestBody String deptId) {
		TDepartSettlementInfo departSettlementInfo = new TDepartSettlementInfo();
		departSettlementInfo.setSettleId(deptId);
		QueryWrapper<TDepartSettlementInfo> queryWrapperDs = new QueryWrapper<>();
		queryWrapperDs.setEntity(departSettlementInfo);
		List<TDepartSettlementInfo> dsList = tDepartSettlementInfoService.list(queryWrapperDs);
		TDepartSettlementInfo ds = null;
		if (dsList != null && !dsList.isEmpty()) {
			ds = dsList.get(CommonConstants.ZERO_INT);
		}
		return ds;
	}

	/**
	 * 修改项目表--EKP调用接口
	 * @author  hyc
	 * @param jsonStr 项目表
	 * @return R
	 */
	@Operation(summary = "修改项目表--EKP调用接口", description = "修改项目表--EKP调用接口")
	@SysLog("修改项目表--EKP调用接口")
	@PostMapping("/updateProjectInfo")
	public R updateProjectInfo(@RequestBody String  jsonStr) {
		try {
			String json = jsonStr.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
			jsonStr = URLDecoder.decode(json, CommonConstants.UTF8).replace("=", "");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		List<TSettleDomainEkpVo> list= JSONObject.parseArray(jsonStr, TSettleDomainEkpVo.class);
		return tSettleDomainService.updateProjectInfo(list);
	}


	/**
	 * 分页查询 客户信息
	 * @return
	 */
	@Operation(summary = "分页查询客户信息", description = "分页查询客户信息")
	@GetMapping("/getUnitPage")
	public R<IPage<IdNameNoVo>> getUnitPage(Page<IdNameNoVo> page, IdNameNoVo idNameNo) {
		return R.ok(tSettleDomainService.getUnitPage(page, idNameNo));
	}

	/**
	 * 修改项目表--EKP调用接口
	 * @author  hyc
	 * @param jsonStr
	 * @return R
	 */
	@Operation(summary = "更新项目服务状态--EKP调用接口", description = "更新项目服务状态--EKP调用接口")
	@SysLog("更新项目服务状态--EKP调用接口")
	@PostMapping("/updateProjectStopStatus")
	public R updateProjectStopStatus(@RequestBody String jsonStr) {
		try {
			String json = jsonStr.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
			jsonStr = URLDecoder.decode(json, CommonConstants.UTF8).replace("=", "");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		List<TSettleDomainUpdVo> list= JSONObject.parseArray(jsonStr, TSettleDomainUpdVo.class);
		return tSettleDomainService.updateProjectStopStatus(list);
	}

	/**
	 * 修改项目表--EKP调用接口
	 * @author  fxj
	 * @param jsonStr
	 * @return R
	 */
	@Operation(summary = "更新项目服务团队--EKP调用接口", description = "更新项目服务团队--EKP调用接口")
	@SysLog("更新项目服务团队--EKP调用接口")
	@PostMapping("/updateProjectServerTeam")
	public R<Boolean> updateProjectServerTeam(@RequestBody String jsonStr) {
		try {
			String json = jsonStr.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
			jsonStr = URLDecoder.decode(json, CommonConstants.UTF8).replace("=", "");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		List<TSettleDomainUpServerTeamVo> list= JSONObject.parseArray(jsonStr, TSettleDomainUpServerTeamVo.class);
		return tSettleDomainService.updateProjectServerTeam(list);
	}

	/**
	 * 分页查询 客户信息
	 * @return
	 */
	@Operation(summary = "代发户切换按钮", description = "代发户切换按钮")
	@PostMapping("/changeIssueStatus")
	public R<Boolean> changeIssueStatus(@RequestBody ChangeIssueStatusVo changeIssueStatusVo) {
		return tSettleDomainService.changeIssueStatus(changeIssueStatusVo);
	}

	/**
	 * @Author fxj
	 * @Description 更新项目前端客服及手机号码--EKP调用接口
	 * @Date 11:46 2025/2/28
	**/
	@Operation(summary = "更新项目前端客服及手机号码--EKP调用接口", description = "更新项目前端客服及手机号码--EKP调用接口")
	@SysLog("更新项目前端客服及手机号码--EKP调用接口")
	@PostMapping("/updateProjectCsInfo")
	public R<Boolean> updateProjectCsInfo(@RequestBody String jsonStr) {
		try {
			String json = jsonStr.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
			jsonStr = URLDecoder.decode(json, CommonConstants.UTF8).replace("=", "");

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		List<TDomainUpCsVo> list= JSONObject.parseArray(jsonStr, TDomainUpCsVo.class);
		return tSettleDomainService.updateProjectCsInfo(list);
	}

	/**
	 * 获取登录用户拥有的项目前端客服数据
	 *
	 * @param
	 * @return
	 * @Author huych
	 * @Date 2025-03-13
	 **/
	@Operation(description = "获取登录用户拥有的项目前端客服数据）")
	@Inner
	@PostMapping("/getAllDeptByCustomerLoginName")
	public TSettleDomainRegistListVo getAllDeptByCustomerLoginName(@RequestBody String userLoginName) {
		TSettleDomainRegistListVo vo = new TSettleDomainRegistListVo();
		vo.setDeptNos(tSettleDomainService.getAllDeptByCustomerLoginName(userLoginName));
		return vo;
	}
}
