package com.fs.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.fs.audit.chain.AuditResult;
import com.fs.audit.common.Result;
import com.fs.audit.domain.AuditFlow;
import com.fs.audit.dto.AuditRequestDTO;
import com.fs.audit.dto.CustomerServicePendingAuditDTO;
import com.fs.audit.service.AuditService;
import com.fs.audit.service.IAuditDetailService;
import com.fs.audit.vo.AuditDetailVO;
import com.fs.audit.vo.QueryPendingAuditVO;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.page.TableDataInfo;
import com.fs.doctor.service.IDoctorLevelApplyService;
import com.fs.doctor.service.IDoctorService;
import com.fs.doctor.vo.DoctorApplyAuditReqVO;
import com.fs.doctor.vo.DoctorDoAuditReqVO;
import com.fs.task.domain.TaskDeliveryInfo;
import com.fs.task.service.ITaskDeliveryInfoService;
import com.fs.task.service.ITaskInfoService;
import com.fs.task.vo.TaskCreateAuditReqVO;
import com.fs.task.vo.TaskFinishAuditReqVO;
import com.fs.task.vo.audit_Info.TaskAuditInfoVO;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * 审核控制器
 */
@RestController
@RequestMapping("/company/audit")
@RequiredArgsConstructor
public class AuditController extends BaseController {
    @Lazy
    @Resource
    private AuditService auditService;
    @Lazy
    @Resource
    private ITaskInfoService taskInfoService;
    @Lazy
    @Resource
    private IAuditDetailService auditDetailService;
    @Lazy
    @Resource
    private IDoctorService doctorService;
    @Lazy
    @Resource
    private IDoctorLevelApplyService doctorLevelApplyService;
    @Lazy
    @Resource
    private ITaskDeliveryInfoService taskDeliveryInfoService;

    /**
     * 查询指定客服的待办审核列表
     *
     * @param param 请求参数
     * @return 待办审核列表
     */
    @PostMapping("/cus/pending")
    public TableDataInfo getCustomerServicePendingAudits(@RequestBody QueryPendingAuditVO param) {
        // 使用PageHelper进行分页
        if (param.getPageNum() != null && param.getPageSize() != null) {
            PageHelper.startPage(param.getPageNum().intValue(), param.getPageSize().intValue());
        }
        List<CustomerServicePendingAuditDTO> data = auditService.getPendingAuditsByCustomerServiceId(param);
        return getDataTable(data);
    }

    /**
     * 查询指定客服的各个类型审核总数
     *
     * @param param
     */
    @PostMapping("/cus/pendingCount")
    public JSONObject getCustomerServicePendingAuditsCount(@RequestBody QueryPendingAuditVO param) {
        param.setStatus(0);
        Long pendingCount = auditService.getPendingAuditsCount(param);
        param.setStatus(1);
        Long approvedCount = auditService.getPendingAuditsCount(param);
        param.setStatus(2);
        Long initiatedCount = auditService.getPendingAuditsCount(param);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pendingCount", pendingCount);
        jsonObject.put("approvedCount", approvedCount);
        jsonObject.put("initiatedCount", initiatedCount);
        return jsonObject;
    }


    /**
     * 查询指定客服的待办任务审核列表
     *
     * @param param 请求参数
     * @return 待办审核列表
     */
    @PostMapping("/cus/pendingtaskAudtList")
    public Result<List<CustomerServicePendingAuditDTO>> getCustomerServicePendingTaskAudits(@RequestBody QueryPendingAuditVO param) {
        HashMap<String, List<CustomerServicePendingAuditDTO>> map = new HashMap<>();
        // 使用PageHelper进行分页
        if (param.getPageNum() != null && param.getPageSize() != null) {
            PageHelper.startPage(param.getPageNum().intValue(), param.getPageSize().intValue());
        }

        List<CustomerServicePendingAuditDTO> pendingData = auditService.getPendingTaskAuditsByCustomerServiceId(param);

        return Result.success(pendingData);
    }


    /**
     * 执行审核
     *
     * @param param 审核参数
     * @return Result
     */
    @Transactional
    @PostMapping("/cus/doAudit")
    public Result<AuditResult> doAudit(@RequestBody AuditRequestDTO param) throws Exception {

        String businessType = param.getBusinessType();
//        //创建任务审核
        if ("ADUIT_CJRW".equals(businessType)) {
            TaskCreateAuditReqVO taskCreateAuditReqVO = new TaskCreateAuditReqVO();
            taskCreateAuditReqVO.setTaskId(param.getBusinessId());
            taskCreateAuditReqVO.setCreateAuditOpinion(param.getComment());
            taskCreateAuditReqVO.setCreateAuditStatus(param.getAction());
            taskCreateAuditReqVO.setCompanyId(param.getCompanyId());
            taskCreateAuditReqVO.setCreateAuditUserId(param.getUserId());


            taskInfoService.appDoCreateAudit(taskCreateAuditReqVO);
            //完成任务
        } else if ("ADUIT_WCRWSH".equals(businessType)) {
            TaskFinishAuditReqVO taskFinishAuditReqVO = new TaskFinishAuditReqVO();
            taskFinishAuditReqVO.setTaskId(param.getBusinessId());
            taskFinishAuditReqVO.setFinishAuditOpinion(param.getComment());
            taskFinishAuditReqVO.setFinishAuditStatus(param.getAction());
            taskFinishAuditReqVO.setCompanyId(param.getCompanyId());
            taskFinishAuditReqVO.setFinishAuditUserId(param.getUserId());
            TaskDeliveryInfo taskDeliveryInfo = new TaskDeliveryInfo();
            taskDeliveryInfo.setTaskId(taskDeliveryInfo.getTaskId());
            List<TaskDeliveryInfo> taskDeliveryInfos = taskDeliveryInfoService.selectTaskDeliveryInfoList(taskDeliveryInfo);
            if (Objects.isNull(taskDeliveryInfos) || taskDeliveryInfos.isEmpty()) {
                throw new Exception("医生交付物未提交，不能审核完成任务。");

            }
            taskInfoService.appDofinishAudit(taskFinishAuditReqVO);
            //讲者审核
        } else if ("ADUIT_JZSH".equals(businessType)) {
            DoctorDoAuditReqVO doctorDoAuditReqVO = new DoctorDoAuditReqVO();
            doctorDoAuditReqVO.setAuditStatus(param.getAction());
            doctorDoAuditReqVO.setCompanyId(param.getCompanyId());
            doctorDoAuditReqVO.setAuditOpinion(param.getComment());
            doctorDoAuditReqVO.setAuditUserId(param.getUserId());
            doctorDoAuditReqVO.setId(param.getUserId());
            doctorDoAuditReqVO.setId(param.getBusinessId());
            doctorService.appDoAudit(doctorDoAuditReqVO);
            //定级审核
        } else if ("ADUIT_DJSH".equals(businessType)) {
            DoctorApplyAuditReqVO doctorApplyAuditReqVO = new DoctorApplyAuditReqVO();
            doctorApplyAuditReqVO.setId(param.getBusinessId());
            doctorApplyAuditReqVO.setStatus(param.getAction());
            doctorApplyAuditReqVO.setRemark(param.getComment());
            doctorApplyAuditReqVO.setAuditUserId(param.getUserId());
            doctorApplyAuditReqVO.setCompanyId(param.getCompanyId());
            doctorLevelApplyService.appDoAudit(doctorApplyAuditReqVO);
        } else if ("ADUIT_TXSH".equals(businessType)) {

        }

//        AuditResult auditResult = auditService.doAudit(param);
        return Result.success(null);
    }

    /**
     * 获取审核流程记录
     *
     * @param auditId 审核实例ID
     * @return Result
     */
    @GetMapping("/cus/getAuditFlows")
    public Result<List<AuditFlow>> getAuditFlows(@RequestParam("auditId") Long auditId) {
        List<AuditFlow> auditFlows = auditService.getAuditFlows(auditId);
        return Result.success(auditFlows);
    }

    /**
     * 根据任务ID获取任务创建审核详细信息
     *
     * @param taskId 任务ID
     * @return 任务审核详细信息，包括任务信息、医生信息、项目信息、业务人员信息和审核流程
     */
    @GetMapping("/task/createAuditInfo")
    public Result<TaskAuditInfoVO> getTaskCreateAuditInfo(@RequestParam("taskId") Long taskId) {
        TaskAuditInfoVO auditInfo = taskInfoService.getTaskCreateAuditInfo(taskId);
        return Result.success(auditInfo);
    }

    /**
     * 根据任务ID获取任务完成审核详细信息
     *
     * @param taskId 任务ID
     * @return 任务审核详细信息，包括任务信息、医生信息、项目信息、业务人员信息和审核流程
     */
    @GetMapping("/task/finishAuditInfo")
    public Result<TaskAuditInfoVO> getTaskFinishAuditInfo(@RequestParam("taskId") Long taskId) {
        TaskAuditInfoVO auditInfo = taskInfoService.getTaskFinishAuditInfo(taskId);
        return Result.success(auditInfo);
    }

    /**
     * 获取审核详情（通用接口）
     * 根据审核实例ID动态返回不同业务类型的完整数据
     * 适用于待办中心的待办详情页面
     *
     * @param auditId 审核实例ID
     * @return 审核详情，包含审核信息、审核流程和对应的业务数据
     * 业务数据根据审核类型动态变化：
     * - 讲者审核：Doctor 信息
     * - 提现审核：WithdrawRecords 信息
     * - 定级审核：DoctorLevelApply 信息
     * - 创建任务审核：TaskAuditInfoVO（包含任务、医生、项目、业务员信息）
     * - 完成任务审核：TaskAuditInfoVO（包含任务、医生、项目、业务员、交付物信息）
     */
    @GetMapping("/detail")
    public Result<AuditDetailVO<?>> getAuditDetail(@RequestParam("auditId") Long auditId) {
        AuditDetailVO<?> auditDetail = auditDetailService.getAuditDetail(auditId);
        return Result.success(auditDetail);
    }

}
