package com.testor.module.contractor.ledger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.module.contractor.ledger.dao.TContractorProjectDao;
import com.testor.module.contractor.ledger.model.domain.TContractorProject;
import com.testor.module.contractor.ledger.model.dto.TContractorProjectParam;
import com.testor.module.contractor.ledger.service.TContractorProjectService;
import com.testor.module.sys.service.NewSysOrgService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.springframework.stereotype.Service;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 项目台账Service业务层处理
 * 
 * @author testor-framework
 * @date 2024-11-20 09:46:08
 */
@Service
public class TContractorProjectServiceImpl extends SuperServiceImpl<TContractorProjectDao, TContractorProject> implements TContractorProjectService
{

    private static final String PROJECT_PREFIX = "XM"; // 项目编号前缀

    @Autowired(required = false)
    private TContractorProjectDao tContractorProjectDao;

    @Autowired
    private NewSysOrgService newSysOrgService;

    @Override
    public String generateProjectCode() {
        String orgId = ContextUtils.getLoginUser().getOrgId();

        // 获取当前日期
        String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());

        // 查询当前日期下最大的项目编号
        QueryWrapper<TContractorProject> wrapper = new QueryWrapper<>();
        wrapper.likeRight("code", PROJECT_PREFIX + currentDate) // 匹配指定日期的项目编号
                .eq(TContractorProject.ORG_ID, orgId)
                .orderByDesc("code") // 按项目编号降序排列
                .last("LIMIT 1"); // 只查询一条记录

        TContractorProject maxProject = this.getOne(wrapper);

        // 生成新的项目编号
        String newProjectCode;
        if (maxProject != null) {
            // 提取当前序号并自增
            String maxCode = maxProject.getCode();
            int currentSerial = Integer.parseInt(maxCode.substring(maxCode.length() - 3)) + 1;
            newProjectCode = PROJECT_PREFIX + currentDate + String.format("%03d", currentSerial);
        } else {
            // 如果没有找到最大编号，从001开始
            newProjectCode = PROJECT_PREFIX + currentDate + "001";
        }

        return newProjectCode;
    }

    @Override
    public TContractorProject addEntity(TContractorProject addRequest) {
        UserInfo loginUser = ContextUtils.getLoginUser();
        // TODO 按需求添加数据去重，特殊值设定，业务异常
        String id = IdHelper.getId32bit();
        TContractorProject data= BeanHelper.beanToBean(addRequest,  TContractorProject.class);
        data.setId(id);
        String code = generateProjectCode();
        data.setCode(code);
        data.setOrgId(loginUser.getOrgId());
        this.save(data);
        return data;
    }

    @Override
    public Page<TContractorProject> pageList(TContractorProjectParam param) {
        Long page=
                StringHelper.isEmpty(param.getPage())? BizConstants.PAGE:Long.valueOf(param.getPage());
        Long limit=
                StringHelper.isEmpty(param.getLimit())?BizConstants.LIMIT:Long.valueOf(param.getLimit());
        Page<TContractorProject> resultPage=new Page<>(page,limit);
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TContractorProject> queryWrapper=this.createQuery(param);
        return this.page(resultPage, queryWrapper);
    }

    @Override
    public List<TContractorProject> listAllEntity(TContractorProjectParam param) {
        QueryWrapper<TContractorProject> queryWrapper=this.createQuery(param);
        return this.list(queryWrapper);
    }

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TContractorProject> createQuery(TContractorProjectParam queryParam){
        QueryWrapper<TContractorProject> queryWrapper=new QueryWrapper<>();
        UserInfo loginUser = ContextUtils.getLoginUser();
        String orgId = loginUser.getOrgId();
        List<String> idsChildrenById = newSysOrgService.getIdsChildrenById(orgId);
        //查询下级机构id
        queryWrapper.in("org_id", idsChildrenById);
        if (ObjectHelper.isNotEmpty(queryParam.getIds())) {
            if ("0".equals(queryParam.getTypeQuery())){
                queryWrapper.notIn("id", queryParam.getIds());
            }else {
                queryWrapper.in("id", queryParam.getIds());
            }
        }
        if(StringHelper.isNotEmpty(queryParam.getName())){
            queryWrapper.like(TContractorProject.NAME,queryParam.getName());
        }
        if(StringHelper.isNotEmpty(queryParam.getCode())){
            queryWrapper.eq(TContractorProject.CODE,queryParam.getCode());
        }
        if(StringHelper.isNotEmpty(queryParam.getLevel())){
            queryWrapper.eq(TContractorProject.LEVEL,queryParam.getLevel());
        }
        if(StringHelper.isNotEmpty(queryParam.getCycle())){
            queryWrapper.eq(TContractorProject.CYCLE,queryParam.getCycle());
        }
        if(StringHelper.isNotEmpty(queryParam.getAmount())){
            queryWrapper.eq(TContractorProject.AMOUNT,queryParam.getAmount());
        }
        if(ObjectHelper.isNotEmpty(queryParam.getCreationTime())){
            queryWrapper.eq(TContractorProject.CREATION_TIME,queryParam.getCreationTime());
        }
        if(StringHelper.isNotEmpty(queryParam.getDepartmentMajor())){
            queryWrapper.eq(TContractorProject.DEPARTMENT_MAJOR,queryParam.getDepartmentMajor());
        }
        if(StringHelper.isNotEmpty(queryParam.getDepartmentBelong())){
            queryWrapper.eq(TContractorProject.DEPARTMENT_BELONG,queryParam.getDepartmentBelong());
        }
        if(ObjectHelper.isNotEmpty(queryParam.getPlanStartTime())){
            queryWrapper.eq(TContractorProject.PLAN_START_TIME,queryParam.getPlanStartTime());
        }
        if(ObjectHelper.isNotEmpty(queryParam.getPlanEndTime())){
            queryWrapper.eq(TContractorProject.PLAN_END_TIME,queryParam.getPlanEndTime());
        }
        if(StringHelper.isNotEmpty(queryParam.getIntroduction())){
            queryWrapper.eq(TContractorProject.INTRODUCTION,queryParam.getIntroduction());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TContractorProject.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TContractorProject.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())){
            if(StringHelper.isNotEmpty(queryParam.getOrderType())
                    &&BizConstants.ASC.equals(queryParam.getOrderType())){
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            }else{
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        }else{
            queryWrapper.orderByDesc(TContractorProject.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
