package com.chushang.inspection.project.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chushang.common.core.exception.utils.AssertUtil;
import com.chushang.common.mybatis.enums.Operator;
import com.chushang.common.mybatis.page.CommonParam;
import com.chushang.common.mybatis.utils.PageResult;
import com.chushang.common.mybatis.utils.WrapperUtils;
import com.chushang.datascope.annotation.DataScope;
import com.chushang.inspection.project.dto.ContractDTO;
import com.chushang.inspection.project.dto.ProjectDTO;
import com.chushang.inspection.project.po.WrkAudit;
import com.chushang.inspection.project.po.WrkProjectContract;
import com.chushang.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chushang.inspection.project.po.WrkProject;
import com.chushang.inspection.project.mapper.WrkProjectMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
  * @auther: zhao
  * @date: 2024/6/15 10:51
  */
@Slf4j
@Service
public class WrkProjectService extends ServiceImpl<WrkProjectMapper, WrkProject> implements IService<WrkProject> {
    @Resource
    WrkProjectContractService contractService;

    @DataScope
    public PageResult pageList(WrkProject project, CommonParam commonParam) {
        LambdaQueryWrapper<WrkProject> queryWrapper = WrapperUtils.builder(project, commonParam);
        IPage<WrkProject> page = this.page(
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(commonParam.getPage(), commonParam.getLimit()),
                queryWrapper
        );

        List<WrkProject> recordList = page.getRecords();
        // 查询出全部项目id
        recordList.forEach(item->{
            WrkProjectContract wrkProjectContract = contractService.queryListByProjectIds(item.getProjectId());
            if(null != wrkProjectContract){
                item.setRemark(wrkProjectContract.getRemark());
                item.setContractStartTime(wrkProjectContract.getContractStartTime());
                item.setContractEndTime(wrkProjectContract.getContractEndTime());
                item.setContractUrl(wrkProjectContract.getContractUrl());
            }
        });
        return new PageResult(recordList,page.getTotal(),page.getSize(),page.getCurrent());
    }

    /**
     * 保存项目
     */
    @Transactional
    public Long save(ProjectDTO project)
    {
        WrkProject wrkProject = new WrkProject();
        BeanUtil.copyProperties(project, wrkProject);
        Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
//        Long deptId = 200L;
        wrkProject.setDeptId(deptId);
        ContractDTO contract = project.getContract();
        LocalDateTime now = LocalDateTime.now();
        // 项目合同
        if (now.isBefore(contract.getContractStartTime()) && now.isAfter(contract.getContractEndTime())) {
            wrkProject.setProjectEffect(0);
        }else {
            wrkProject.setProjectEffect(1);
        }
        this.save(wrkProject);
        contract.setProjectId(wrkProject.getProjectId());
        // 项目合同
        saveContract(contract);
        return wrkProject.getProjectId();
    }

    /**
     * 修改项目 -- 不同时修改 合同
     */
    @Transactional
    public Long update(ProjectDTO project)
    {
        WrkProject wrkProject = new WrkProject();
        BeanUtil.copyProperties(project, wrkProject);
        this.updateById(wrkProject);
        // 项目合同
//        WrkProjectContract contract = WrkProjectContract.builder().build();
//        BeanUtil.copyProperties(project.getContract(), contract);
//        LocalDateTime now = LocalDateTime.now();
//        // 在 之前 && 在 之后 无效
//        if (now.isBefore(contract.getContractStartTime()) && now.isAfter(contract.getContractEndTime())) {
//            contract.setProjectEffect(0);
//        }else {
//            contract.setProjectEffect(1);
//        }
//        // 未回款完成
//        contract.setPaymentState(0);
        // 项目合同 修改时不需要 项目id
//        contractService.updateById(contract);
        return wrkProject.getProjectId();
    }

    public void updateState(Long projectId, Integer projectEffect)
    {
        WrkProject project = new WrkProject();
        project.setProjectId(projectId);
        project.setProjectEffect(projectEffect);
        updateById(project);
    }

    @Transactional
    public Long delete(Long projectId)
    {
        WrkProject project = getById(projectId);
        if (null != project){
            // 项目有效状态
            Integer projectEffect = project.getProjectEffect();
            if (1 == projectEffect){
                log.info("删除了有效项目, 但是此处不管");
            }
        }
        removeById(projectId);
        return projectId;
    }

    @Transactional
    public Long saveContract(ContractDTO contract) {
        // 项目合同
        WrkProjectContract projectContract = WrkProjectContract.builder().build();
        BeanUtil.copyProperties(contract, projectContract);
        projectContract.setProjectId(contract.getProjectId());
        // 未回款完成
        projectContract.setPaymentState(0);
        LocalDateTime now = LocalDateTime.now();
        boolean projectEffect = !now.isBefore(contract.getContractStartTime()) || !now.isAfter(contract.getContractEndTime());
        // 在 之前 && 在 之后 无效
        projectContract.setProjectEffect(projectEffect ? 1 : 0);

        Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        projectContract.setDeptId(deptId);
        // 新增合同的时候, 为待初审状态
        projectContract.setAuditStatus(1);
        contractService.save(projectContract);
        updateState(contract.getProjectId(), projectEffect ? 1 : 0 );
        // 新增合同的时候, 项目状态为待初审状态
//        updateAuditStatus(contract.getProjectId(), 1);

//        Integer auditStatus = contract.getAuditStatus();
//        if (null != auditStatus && (1 == auditStatus || 2 == auditStatus)){
//            // 新增合同的审核记录
//            WrkAudit audit = new WrkAudit();
//            audit.setThirdType(1);
//            audit.setDeptId(deptId);
//            audit.setAuditStatus(auditStatus);
//            audit.setThirdId(projectContract.getContractId());
//            audit.setRemark(contract.getRemark());
//            auditService.save(audit);
//        }
        return projectContract.getContractId();
    }

    @Transactional
    public Long updateContract(ContractDTO contract) {
        // 修改 合同时必须未提交或者已经撤销
        LambdaQueryWrapper<WrkProjectContract> contractSql = WrapperUtils.builder(contract, null);
        contractSql.last(Operator.LIMIT_ONE.getCharacter());
        WrkProjectContract projectContract = contractService.getOne(contractSql);
        AssertUtil.invalidate(null == projectContract, "合同不存在");
        Integer auditStatus = projectContract.getAuditStatus();
        AssertUtil.invalidate(0 != auditStatus
                && 7 != auditStatus
                        && 5 != auditStatus
                , "当前合同已提交审核, 无法修改");

        projectContract = new WrkProjectContract();
        // 项目合同
        BeanUtil.copyProperties(contract, projectContract);
        projectContract.setProjectId(null);

        LocalDateTime now = LocalDateTime.now();
        boolean projectEffect = !now.isBefore(contract.getContractStartTime()) || !now.isAfter(contract.getContractEndTime());
        // 在 之前 && 在 之后 无效
        projectContract.setProjectEffect(projectEffect ? 1 : 0);
        // 未回款完成
        projectContract.setPaymentState(0);

        contractService.updateById(projectContract);
        updateState(contract.getProjectId(), projectEffect ? 1 : 0 );
        return projectContract.getContractId();
    }

    public void deleteContract(Long contractId) {
        contractService.delete(contractId);
    }

    /**
     * 获取项目详细信息
     */
    @DataScope
    public WrkProject getProject(Long projectId)
    {
        CommonParam commonParam = CommonParam.buildAllRequest();
        WrkProject wrkProject = new WrkProject();
        wrkProject.setProjectId(projectId);
        LambdaQueryWrapper<WrkProject> projectSql = WrapperUtils.builder(wrkProject, commonParam);
        projectSql.last(Operator.LIMIT_ONE.getCharacter());
        wrkProject = getOne(projectSql);
        if (null != wrkProject){
            // 查询 合同集合
            WrkProjectContract projectContract = new WrkProjectContract();
            projectContract.setProjectId(projectId);
            LambdaQueryWrapper<WrkProjectContract> contractSql = WrapperUtils.builder(projectContract, commonParam);
            List<WrkProjectContract> list = contractService.list(contractSql);
            wrkProject.setContracts(list);
        }
        return wrkProject;
    }

    public void updateAuditStatus(Long projectId, Integer auditStatus) {
        WrkProject project = new WrkProject();
        project.setProjectId(projectId);
        project.setAuditStatus(auditStatus);
        updateById(project);
    }
}
