package cn.iocoder.yudao.module.bpm.controller.admin.oa;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.idempotent.core.annotation.Idempotent;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.vo.contract.BpmOAContractCreateReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.vo.contract.BpmOAContractPageReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.vo.contract.BpmOAContractRespVO;
import cn.iocoder.yudao.module.bpm.controller.admin.oa.vo.contract.ContractStatisticsRespVO;
import cn.iocoder.yudao.module.bpm.convert.oa.BpmOAContractConvert;
import cn.iocoder.yudao.module.bpm.dal.dataobject.oa.BpmOAContractDO;
import cn.iocoder.yudao.module.bpm.service.oa.BpmOAContractService;
import cn.iocoder.yudao.module.hrm.api.crmbusiness.BusinessApi;
import cn.iocoder.yudao.module.hrm.api.crmbusiness.dto.CrmBusinessDTO;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * OA 合同审批 Controller
 *
 * @author 符溶馨
 */
@Tag(name = "管理后台 - OA 合同审批")
@RestController
@RequestMapping("/bpm/oa/contract")
@Validated
public class BpmOAContractController {

    @Resource
    private BpmOAContractService contractService;

    @Resource
    private AdminUserApi userApi;

    @Resource
    private DeptApi deptApi;

    @Resource
    private BusinessApi businessApi;

    @PostMapping("/create")
    @Operation(summary = "创建请求申请")
    @Idempotent(timeout = 10)
    public CommonResult<Long> createContract(@Valid @RequestBody BpmOAContractCreateReqVO createReqVO) {
        return success(contractService.createContract(getLoginUserId(), createReqVO));
    }

    @GetMapping("/get")
    @Operation(summary = "获得合同审批")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<BpmOAContractRespVO> getContract(@RequestParam("id") Long id) {
        BpmOAContractDO contract = contractService.getContract(id);
        BpmOAContractRespVO respVO = BpmOAContractConvert.INSTANCE.convert(contract);
        if (respVO != null) {
            // 获取用户和签约人信息
            List<Long> userIds = Arrays.asList(contract.getUserId(), contract.getSignatoryId());
            Map<Long, AdminUserRespDTO> userMap = userApi.getUserMap(userIds);
            if (CollectionUtil.isNotEmpty(userMap)) {
                // 设置创建人、签约人名称
                respVO.setSignatoryName(userMap.get(contract.getSignatoryId()) != null ? userMap.get(contract.getSignatoryId()).getNickname() : null);
                respVO.setCreateName(userMap.get(contract.getUserId()) != null ? userMap.get(contract.getUserId()).getNickname() : null);
            }

            // 获取公司信息
            DeptRespDTO dto = deptApi.getDept(contract.getCompanyId()).getCheckedData();
            if (dto != null) {
                respVO.setCompanyName(dto.getName());
            }

            if (respVO.getBusinessId() != null) {
                // 获取商机信息
                CrmBusinessDTO businessDTO = businessApi.getBusiness(respVO.getBusinessId()).getCheckedData();
                respVO.setBusinessName(businessDTO != null ? businessDTO.getName() : null);
            }
        }

        return success(respVO);
    }

    @GetMapping("/getByProcessInstanceId")
    @Operation(summary = "获得合同审批")
    @Parameter(name = "processInstanceId", description = "流程实例编号", required = true, example = "1024")
    public CommonResult<BpmOAContractRespVO> getContractByProcessInstanceId(@RequestParam("processInstanceId") String processInstanceId) {

        BpmOAContractDO contract = contractService.getByProcessInstanceId(processInstanceId);
        BpmOAContractRespVO respVO = BpmOAContractConvert.INSTANCE.convert(contract);
        if (respVO != null) {
            // 获取用户和签约人信息
            List<Long> userIds = Arrays.asList(contract.getUserId(), contract.getSignatoryId());
            Map<Long, AdminUserRespDTO> userMap = userApi.getUserMap(userIds);
            if (CollectionUtil.isNotEmpty(userMap)) {
                // 设置创建人、签约人名称
                respVO.setSignatoryName(userMap.get(contract.getSignatoryId()).getNickname());
                respVO.setCreateName(userMap.get(contract.getUserId()).getNickname());
            }

            // 获取公司信息
            DeptRespDTO dto = deptApi.getDept(contract.getCompanyId()).getCheckedData();
            if (dto != null) {
                respVO.setCompanyName(dto.getName());
            }

            if (respVO.getBusinessId() != null) {
                // 获取商机信息
                CrmBusinessDTO businessDTO = businessApi.getBusiness(respVO.getBusinessId()).getCheckedData();
                respVO.setBusinessName(businessDTO != null ? businessDTO.getName() : null);
            }
        }

        return success(respVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得合同审批分页列表")
    public CommonResult<PageResult<BpmOAContractRespVO>> getPage(@Valid BpmOAContractPageReqVO pageReqVO) {

        return success(contractService.getContractPage(pageReqVO));
    }

    @GetMapping("/getList")
    @Operation(summary = "获取下属和自己的合同列表")
    public CommonResult<List<BpmOAContractRespVO>> getList(@RequestParam(required = false) String relation,
                                                           @RequestParam(required = false) Integer contractType,
                                                           @RequestParam(required = false) String contractName) {
        List<BpmOAContractDO> contracts = contractService.getList(relation, contractType, contractName);
        return success(BeanUtils.toBean(contracts, BpmOAContractRespVO.class));
    }

    @GetMapping("/get-contract-statistics")
    @Operation(summary = "获得当日合同统计 | 新增数量、新增金额")
    @Parameter(name = "relation", description = "查询类型 my我的 sub下属| ", required = true)
    public CommonResult<ContractStatisticsRespVO> getListByDeptId(@RequestParam("relation") String relation) {

        ContractStatisticsRespVO respVO = contractService.getContractStatistics(getLoginUserId(), relation);

        return success(respVO);
    }

    @GetMapping("/getContractByCustomerId")
    @Operation(summary = "获得指定客户的合同列表")
    @Parameter(name = "customerId", description = "客户编号", required = true)
    public CommonResult<List<BpmOAContractRespVO>> getListByCustomerId(@RequestParam("customerId") Long customerId) {

        List<BpmOAContractDO> respVOs = contractService.getListByCustomerId(customerId);

        return success(BeanUtils.toBean(respVOs, BpmOAContractRespVO.class));
    }
}
