package com.loan.system.controller.wechat;

import cn.hutool.core.bean.BeanUtil;
import com.loan.system.context.BaseContext;
import com.loan.system.domain.dto.CollateralPlanApprovalDTO;
import com.loan.system.domain.dto.CollateralPlanDTO;
import com.loan.system.domain.entity.ApprovalRecord;
import com.loan.system.domain.entity.Collateral;
import com.loan.system.domain.entity.CollateralPlan;
import com.loan.system.domain.entity.User;
import com.loan.system.domain.enums.ExceptionEnum;
import com.loan.system.domain.enums.RoleEnum;
import com.loan.system.domain.pojo.Result;
import com.loan.system.domain.vo.CollateralPlanVO;
import com.loan.system.domain.vo.CollateralVO;
import com.loan.system.service.ApprovalService;
import com.loan.system.service.CollateralPlanService;
import com.loan.system.service.CollateralService;
import com.loan.system.service.Impl.UserServiceImpl;
import com.loan.system.service.UserService;
import com.loan.system.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import static com.loan.system.domain.enums.DecisionEnum.*;
import static com.loan.system.domain.enums.ExceptionEnum.*;

@RestController
@RequestMapping("/wechat/collateral")
@Api(tags = "抵押物接口")
public class CollateralController {

    @Autowired
    private CollateralService collateralService;
    @Autowired
    private CollateralPlanService collateralPlanService;
    @Autowired
    private ApprovalService approvalService;
    @Autowired
    private UserService userService;
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    //显示业务相关抵押物状态
    @GetMapping("/{id}")
    @ApiOperation("查看业务相关抵押物状态")
    public Result findCollateral(@PathVariable("id") Long id){
        List<CollateralVO> collaterals = collateralService.findByCaseId(id);
        return ResultUtil.success("success",collaterals);
    }
    /**
     * 查看项目抵押物计划
     * @param id
     * @return 响应
    */
    @GetMapping("/plan/{id}")
    @ApiOperation("查看项目抵押物计划")
    public Result findCollateralPlan(@PathVariable("id") Long id){
        List<CollateralPlan> collateralPlans = collateralPlanService.findByCaseIdAndIsDelete(id,false);
        if(collateralPlans == null || collateralPlans.isEmpty()){
            return ResultUtil.error(COLLATERAL_PLAN_NOT_EXIST.getCode(),"计划不存在");
        }

        List<String> Roles=new ArrayList<>();
        Roles.add(RoleEnum.LEAD_SALES.getMsg());
        Roles.add(RoleEnum.ASSIST_SALES.getMsg());

        // 创建VO列表
        List<CollateralPlanVO> collateralPlanVOs = new ArrayList<>();
        for(CollateralPlan plan : collateralPlans){
            CollateralPlanVO vo = new CollateralPlanVO();
            BeanUtil.copyProperties(plan, vo);
            vo.setOperatorId(plan.getOperatorId());
            vo.setOperatorName(plan.getOperatorName());
            collateralPlanVOs.add(vo);
        }

        return ResultUtil.success("success",collateralPlanVOs);
    }

    /**
     * 上报计划
     * @return 响应
    */
    @PostMapping("/plan")
    @PreAuthorize("@pms.hasAnyRoles('LEAD_SALES','ASSIST_SALES')")
    @ApiOperation("上报计划")
    public Result createCollateralPlan(@RequestBody CollateralPlanDTO collateralPlanDTO){
        Collateral collaterals = collateralService.findCollateralById(collateralPlanDTO.getCollateralId());
        if (collaterals == null){
            return ResultUtil.error(COLLATERAL_NOT_EXIST.getCode(), "抵押物不存在");
        }
        List<CollateralPlan> collateralPlans=collateralPlanService.findByCollateralIdAndIsDelete(collateralPlanDTO.getCollateralId());
        // 修改后的代码
        for(CollateralPlan plan : collateralPlans){
            // 如果状态既不是拒绝也不是执行完成，则返回错误
            if(!plan.getStatus().equals(REJECTION.getMsg()) && !plan.getStatus().equals(EXECUTION_COMPLETE.getMsg())){
                return ResultUtil.error(COLLATERAL_PLAN_ALREADY_EXIST.getCode(), COLLATERAL_PLAN_ALREADY_EXIST.getMsg());
            }
        }

        Long userid = BaseContext.getCurrentId();
        CollateralPlan collateralPlan = CollateralPlan.builder()
                .collateralId(collateralPlanDTO.getCollateralId())
                .caseId(collateralPlanDTO.getCaseId())
                .time(collateralPlanDTO.getCollateralTime())
                .place(collateralPlanDTO.getCollateralPlace())
                .flag(collateralPlanDTO.getFlag())
                .userId(userid)
                .comments(collateralPlanDTO.getComments())
                .createTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .updateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .status(WAITING_APPROVAL.getMsg())
                .isDelete(false)
                .build();
        collateralPlanService.save(collateralPlan);
        return ResultUtil.success("success", "计划上报成功");
    }

    /**
     * 审批计划
     * @param collateralPlanApprovalDTO
     * @return 响应
    */
    @PostMapping("/plan/approval")
    @PreAuthorize("@pms.hasRole('APPROVER')")
    @ApiOperation("审批计划")
    public Result refuseCollateralPlan(@RequestBody CollateralPlanApprovalDTO collateralPlanApprovalDTO){
        CollateralPlan collateralPlan = collateralPlanService.findById(collateralPlanApprovalDTO.getId());
        if(collateralPlan == null){
            return ResultUtil.error(COLLATERAL_PLAN_NOT_EXIST.getCode(),"计划不存在");
        }
        log.info("collaterralplanid: " + collateralPlan.getId());
        if(!collateralPlan.getStatus().equals(WAITING_APPROVAL.getMsg())){
            return ResultUtil.error(COLLATERAL_PLAN_NOT_ALREADY_APPROVED.getCode(),COLLATERAL_PLAN_NOT_ALREADY_APPROVED.getMsg());
        }
        ApprovalRecord approvalRecord = ApprovalRecord.builder()
                .caseId(collateralPlanApprovalDTO.getCaseId())
                .stepName("押品管控环节")
                .approverId(BaseContext.getCurrentId())
                .decision(collateralPlanApprovalDTO.getDecision())
                .comments(collateralPlanApprovalDTO.getComments())
                .createTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .updateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .isDelete( false)
                .build();
        approvalService.save(approvalRecord);
        log.info(collateralPlanApprovalDTO.getDecision());
        log.info("操作者id"+collateralPlanApprovalDTO.getOperator().getId());
        if("拒绝".equals(collateralPlanApprovalDTO.getDecision())){
            collateralPlanService.updateCollateralStatusByid(collateralPlan.getId(), REJECTION.getMsg());
            //collateralPlanService.logic_delete(collateralPlanApprovalDTO.getId());
            return ResultUtil.success("success","计划已拒绝");
        }else if("通过".equals(collateralPlanApprovalDTO.getDecision())){
//            collateralPlanService.updateCollateraluserIdByid(collateralPlanApprovalDTO.getId(),collateralPlanApprovalDTO.getUserId());
            collateralPlanService.updateCollateralStatusByid(collateralPlanApprovalDTO.getId(),WAITING_EXECUTION.getMsg());
            // 修改 Controller 中的调用
            collateralPlanService.updateCollateraloperatorIdByid(
                    collateralPlan.getId(),
                    collateralPlanApprovalDTO.getOperator().getId(),
                    collateralPlanApprovalDTO.getOperator().getRealName()
            );
//TODO 改状态+微信推送下一个节点业务员
            return ResultUtil.success("success","计划已通过");
        }else{
            return ResultUtil.error(ExceptionEnum.UNKNOWN_ERROR,"请选择通过或者拒绝");
        }
    }



    /**确认抵押物入库，完成任务
     *ID:计划id
     */
    @PostMapping("/warehouse/{id}")
    @PreAuthorize("@pms.hasAnyRoles('LEAD_SALES','ASSIST_SALES')")
    @ApiOperation("确认抵押物入库")
    public Result warehouseCollateral(@PathVariable("id") Long id){
        CollateralPlan collateralPlan = collateralPlanService.findByCollateralPlanId(id);
        if(collateralPlan == null){
            return ResultUtil.error(COLLATERAL_PLAN_NOT_EXIST.getCode(),"计划不存在");
        }
        if(!collateralPlan.getStatus().equals(WAITING_EXECUTION.getMsg())){
            return ResultUtil.error(COLLATERAL_PLAN_NOT_ALREADY_EXECUTION.getCode(),COLLATERAL_PLAN_NOT_ALREADY_EXECUTION.getMsg());
        }
        if(!collateralPlan.getFlag().equals("入库")){
            return ResultUtil.error(COLLATERAL_PLAN_NOT_EQUAL_WAREHOUSE.getCode(),COLLATERAL_PLAN_NOT_EQUAL_WAREHOUSE.getMsg());
        }
        Collateral collateral = collateralService.findCollateralById(collateralPlan.getCollateralId());
        if(collateral == null){
            return ResultUtil.error(COLLATERAL_NOT_EXIST.getCode(),"抵押物不存在");
        }

        collateralService.updateCollateralStatusByid(collateral.getId(),"入库");
        collateralPlanService.updateCollateralStatusByid(id,EXECUTION_COMPLETE.getMsg());
        return ResultUtil.success("success","抵押物入库成功");
    }
    /**确认抵押物出库，完成任务
     *ID:计划id
     */
    @PostMapping("/outbound/{id}")
    @PreAuthorize("@pms.hasAnyRoles('LEAD_SALES','ASSIST_SALES')")
    @ApiOperation("确认抵押物出库")
    public Result outboundCollateral(@PathVariable("id") Long id){
        CollateralPlan collateralPlan = collateralPlanService.findByCollateralPlanId(id);
        if(collateralPlan == null){
            return ResultUtil.error(COLLATERAL_PLAN_NOT_EXIST.getCode(),"计划不存在");
        }
        if(!collateralPlan.getStatus().equals(WAITING_EXECUTION.getMsg())){
            return ResultUtil.error(COLLATERAL_PLAN_NOT_ALREADY_EXECUTION.getCode(),COLLATERAL_PLAN_NOT_ALREADY_EXECUTION.getMsg());
        }
        if(!collateralPlan.getFlag().equals("出库")){
            return ResultUtil.error(COLLATERAL_PLAN_NOT_EQUAL_OUTBOUND.getCode(),COLLATERAL_PLAN_NOT_EQUAL_OUTBOUND.getMsg());
        }
        Collateral collateral = collateralService.findCollateralById(collateralPlan.getCollateralId());
        if(collateral == null){
            return ResultUtil.error(COLLATERAL_NOT_EXIST.getCode(),"抵押物不存在");
        }
        collateralService.updateCollateralStatusByid(collateral.getId(),"出库");
        collateralPlanService.updateCollateralStatusByid(id,EXECUTION_COMPLETE.getMsg());
        return ResultUtil.success("success","抵押物出库成功");
    }
    /**删除抵押物
     *
     */
    @PostMapping("/delete/{id}")
    @PreAuthorize("@pms.hasAnyRoles('LEAD_SALES','ASSIST_SALES')")
    @ApiOperation("删除抵押物")
    public Result deleteCollateral(@PathVariable("id") Long id){
        Collateral collateral = collateralService.findCollateralById(id);
        if(collateral == null){
            return ResultUtil.error(COLLATERAL_NOT_EXIST.getCode(),"抵押物不存在");
        }
        collateralService.logic_delete(id);
        return ResultUtil.success("success","抵押物删除成功");
    }

}
