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

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.yeejoin.amos.boot.module.jyjc.api.entity.JyjcOpeningApplication;
import com.yeejoin.amos.boot.module.jyjc.api.model.JyjcOpeningApplicationRequstDto;
import com.yeejoin.amos.boot.module.jyjc.biz.config.BaseException;
import com.yeejoin.amos.boot.module.ymt.api.entity.TzBaseEnterpriseInfo;
import com.yeejoin.amos.boot.module.ymt.api.enums.FlowStatusEnum;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
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 com.yeejoin.amos.boot.module.jyjc.biz.service.impl.JyjcOpeningApplicationServiceImpl;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
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.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.jyjc.api.model.JyjcOpeningApplicationModel;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.foundation.enumeration.UserType;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * @author system_generator
 * @date 2023-12-13
 */
@RestController
@Api(tags = "检验业务申请单api")
@RequestMapping(value = "/jyjc-opening-application")
@EnableScheduling
public class JyjcOpeningApplicationController extends BaseController {

    @Autowired
    JyjcOpeningApplicationServiceImpl jyjcOpeningApplicationServiceImpl;

    /**
     * 新增
     *
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
	public ResponseModel<JyjcOpeningApplicationModel> save(@RequestBody JSONObject model) {
		JyjcOpeningApplicationModel jyjcOpeningApplicationModel = new JyjcOpeningApplicationModel();
		// 兼容工作台暂存逻辑、编辑时报错逻辑
		if (model.containsKey("applyInfo")) { // 工作台暂存逻辑
			BeanUtil.copyProperties(model.get("applyInfo"), jyjcOpeningApplicationModel);
		} else {                             // 详情保存逻辑
			BeanUtil.copyProperties(model, jyjcOpeningApplicationModel);
		}
		return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.saveOrUpdateModel(jyjcOpeningApplicationModel, false));
	}
	/**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "更新", notes = "更新")
	public ResponseModel<JyjcOpeningApplicationModel> updateBySequenceNbrJyjcOpeningApplication(@RequestBody JyjcOpeningApplicationModel model,@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
	    model.setSequenceNbr(sequenceNbr);
	    return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.saveOrUpdateModel(model,false));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "/submit")
	@ApiOperation(httpMethod = "PUT", value = "保存并提交", notes = "保存并提交")
	public ResponseModel<List<JyjcOpeningApplicationModel>> updateBySequenceNbrAndStartFlow(@RequestBody JSONObject jsonObject, @RequestParam(value = "sequenceNbr", required = false) Long sequenceNbr) {
		JyjcOpeningApplicationModel model = new JyjcOpeningApplicationModel();
		if (jsonObject.containsKey("applyInfo")) {
			BeanUtil.copyProperties(jsonObject.get("applyInfo"), model);
		} else {
			BeanUtil.copyProperties(jsonObject, model);
		}
		model.setSequenceNbr(sequenceNbr);
		if (sequenceNbr != null) {
			JyjcOpeningApplicationModel jyjcOpeningApplicationModel = jyjcOpeningApplicationServiceImpl.queryDetail(sequenceNbr);
			if (jyjcOpeningApplicationModel == null || ValidationUtil.isEmpty(jyjcOpeningApplicationModel.getBaseUnitLicences()) || ValidationUtil.isEmpty(jyjcOpeningApplicationModel.getUserInfos())) {
				throw new BadRequest("企业资质信息和检验人员信息为空，无法提交！");
			}
		}
		JyjcOpeningApplicationModel data = jyjcOpeningApplicationServiceImpl.saveOrUpdateModel(model, true);
		return ResponseHelper.buildResponse(Collections.singletonList(data));
	}

	@Deprecated
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/startFlow/{sequenceNbr}")
	@ApiOperation(httpMethod = "POST", value = "重新提交开通申请", notes = "重新提交开通申请")
	public ResponseModel<JyjcOpeningApplicationModel> resubmitJyjcOpeningApplication(@RequestBody JyjcOpeningApplicationModel model, @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
		model.setSequenceNbr(sequenceNbr);
		return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.resubmit(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){
//		JyjcOpeningApplication jyjcOpeningApplication = jyjcOpeningApplicationServiceImpl.getById(sequenceNbr);
//		List<String> status = Arrays.asList(String.valueOf(FlowStatusEnum.TO_BE_PROCESSED.getCode()), String.valueOf(FlowStatusEnum.TO_BE_FINISHED.getCode()));
//		if(status.contains(jyjcOpeningApplication.getStatus())) {
//			throw new BadRequest("除撤回跟驳回的流程之外其余流程不可删除！");
//		}
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.removeById(sequenceNbr));
    }

	/**
	 * 根据sequenceNbr删除
	 *
	 * @param sequenceNbrList 主键列表
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@DeleteMapping(value = "batchDelete")
	@ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除", notes = "根据sequenceNbr删除")
	public ResponseModel<Boolean> deleteBySequenceNbr(@RequestParam(value = "sequenceNbrList") List<Long> sequenceNbrList){
		return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.deleteBatchByIds(sequenceNbrList));
	}

    /**
     * 根据sequenceNbr查询
     *
	 * @param sequenceNbr  主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/detail")
	@ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个",  notes = "根据sequenceNbr查询单个")
	public ResponseModel<JyjcOpeningApplicationModel> selectOne(@RequestParam(value = "sequenceNbr", required = false) Long sequenceNbr) {
	    return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.queryDetail(sequenceNbr));
	}

	/**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/page")
	@ApiOperation(httpMethod = "POST",value = "分页查询",  notes = "分页查询")
	public ResponseModel<Page<JyjcOpeningApplicationModel>> queryForPage(@RequestParam(value = "current") int current,@RequestParam
                    (value = "size") int size,@RequestBody JyjcOpeningApplicationRequstDto jyjcOpeningApplicationRequstDto) {
	    Page<JyjcOpeningApplication> page = new Page<JyjcOpeningApplication>();
	    page.setCurrent(current);
	    page.setSize(size);
	    return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.queryForJyjcOpeningApplicationPage(page,jyjcOpeningApplicationRequstDto));
	}


//	/**
//	 * 列表分页查询
//	 *
//	 * @param current 当前页
//	 * @param current 每页大小
//	 * @return
//	 */
//	@TycloudOperation(ApiLevel = UserType.AGENCY)
//	@GetMapping(value = "/pageForCompany")
//	@ApiOperation(httpMethod = "GET",value = "分页查询-公司",  notes = "分页查询-公司")
//	public ResponseModel<Page<JyjcOpeningApplicationModel>> querypageForCompany(@RequestParam(value = "current") int current, @RequestParam
//			(value = "size") int size, JyjcOpeningApplicationRequstDto jyjcOpeningApplicationRequstDto) {
//		Page<JyjcOpeningApplication> page = new Page<JyjcOpeningApplication>();
//		page.setCurrent(current);
//		page.setSize(size);
//		return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.querypageForCompany(page,jyjcOpeningApplicationRequstDto));
//	}

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



	/**
	 * 列表全部数据查询
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "POST",value = "接收或者驳回业务开通申请",   notes = "接收或者驳回业务开通申请")
	@PostMapping(value = "/execueFlow")
	public ResponseModel<HashMap<String,String>> execueFlow(@RequestBody Map<String,Object> params) {

		jyjcOpeningApplicationServiceImpl.execueFlow(params);
		HashMap<String,String> result =new HashMap<>();
		result.put("result","success");
		return ResponseHelper.buildResponse(result);
	}

	/**
	 * 列表全部数据查询
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "撤回业务开通申请",   notes = "撤回业务开通申请")
	@GetMapping(value = "/rollBackFlow")
	public ResponseModel<Object> overflow(@RequestParam("sequenceNbr") String sequenceNbr) {
		return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.stopFlow(sequenceNbr));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getUserRole")
	@ApiOperation(httpMethod = "GET", value = "获取用户所属组", notes = "获取用户所属组")
	public ResponseModel<List<Long>> getUserRole() {
		AgencyUserModel userModel = Privilege.agencyUserClient.queryByUserId(RequestContext.getExeUserId()).getResult();
		if (userModel == null) {
			throw new BaseException("请先登陆！");
		}
		List<RoleModel> roleModels = userModel.getOrgRoles()
											  .values().stream().flatMap(Collection::stream).collect(Collectors.toList());
		List<Long> roleIds = roleModels.stream().map(RoleModel::getSequenceNbr).distinct().collect(Collectors.toList());
		return ResponseHelper.buildResponse(roleIds);
	}

	/**
	 * 废弃接口, 已替换成公共接口
	 *
	 *
	 * @param
	 * @return {@link  ResponseModel< List< Map< String  Object>>>}
	 * @author yangyang
	 * @throws
	 */
	@Deprecated
	@TycloudOperation (ApiLevel = UserType.AGENCY)
	@ApiOperation (httpMethod = "GET", value = "办理状态枚举列表", notes = "办理状态枚举列表")
	@GetMapping (value = "/flow-status/list")
	public ResponseModel<List<Map<String, Object>>> selectForFlowStatusList() {
		return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.selectForFlowStatusList());
	}

	/**
	 * 查询检验检测机构列表（基本信息及联系人）by 开通机构过滤
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getInspectionUnitList")
	@ApiOperation(httpMethod = "GET", value = "查询检验检测机构列表（基本信息及联系人）", notes = "查询检验检测机构列表（基本信息及联系人）by 开通机构过滤")
	public ResponseModel<List<TzBaseEnterpriseInfo>> getInspectionUnitList() {
		return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.getInspectionUnitList());
	}

	/**
	 * 作废
	 *
	 *
	 * @param
	 * @return {@link  ResponseModel< List< TzBaseEnterpriseInfo>>}
	 * @author yangyang
	 * @throws
	 * @date 2023/12/22 16:13
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "/discard")
	@ApiOperation(httpMethod = "PUT", value = "作废", notes = "作废")
	public ResponseModel<Boolean> doDiscard(@RequestBody Map<String,Object> params) {
		String sequenceNbr = (String) params.get("sequenceNbr");
		String remark = (String) params.get("remark");
		return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.doDiscard(Long.parseLong(sequenceNbr), remark));
	}


	/**
	 * 自动作废
	 *
	 *
	 * @param
	 * @return {@link  ResponseModel< List< TzBaseEnterpriseInfo>>}
	 * @author yangyang
	 * @throws
	 * @date 2023/12/22 16:13
	 */
	@Scheduled(cron = "0 0 0 * * ?")
	public void timingDiscard() {

		List<Long> longs = jyjcOpeningApplicationServiceImpl.selectOverdueData();

		if (CollectionUtils.isNotEmpty(longs)){
			for (Long aLong : longs) {
				String remark = "到期作废";
				jyjcOpeningApplicationServiceImpl.doDiscard(aLong, remark);

			}
		}
	}
}
