package com.hotent.surveyinfo.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.base.query.PageList;
import com.hotent.base.util.StringUtil;

import com.hotent.surveyinfo.dao.CostVerifyTemplateDao;
import com.hotent.surveyinfo.dao.CostVerifyTemplateHeadersDao;
import com.hotent.surveyinfo.manager.CostVerifyTemplateItemsManager;
import com.hotent.surveyinfo.manager.CostVerifyTemplateManager;
import com.hotent.surveyinfo.model.*;
import com.hotent.surveyinfo.req.ConstVerifyPageParam;
import com.hotent.surveyinfo.req.ConstVerifyPageReq;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.manager.UserManager;
import com.hotent.uc.model.User;
import com.hotent.uc.util.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.List;

/**
 * 成本核定表模板表 服务实现类
 *
 * @company 山西清众科技股份有限公司
 * @author 超级管理员
 * @since 2025-09-19
 */
@Service
public class CostVerifyTemplateManagerImpl extends BaseManagerImpl<CostVerifyTemplateDao, CostVerifyTemplate> implements CostVerifyTemplateManager {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	CostVerifyTemplateHeadersDao costSurveyTemplateheaderMapper;
	@Autowired
	CostVerifyTemplateItemsManager costSurveyTemplateItemsManager;
//	@Autowired
//	CostSurveyTemplateVersionDao costSurveyTemplateVersionMapper;
	@Autowired
	private DataSource dataSource;
	@Autowired
	private UserManager userService;
	@Override
	public IPage<CostVerifyTemplate> getCostSurveyList(ConstVerifyPageReq req) {
		// 构建查询条件
		LambdaQueryWrapper<CostVerifyTemplate> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(CostVerifyTemplate::getIsDelete, "0")	;
		IUser user = ContextUtil.getCurrentUser();
		queryWrapper.eq(CostVerifyTemplate::getCreateBy, user.getAccount())	;
		// 根据查询条件过滤
		if (StringUtil.isNotEmpty(req.getType())) {
			queryWrapper.eq(CostVerifyTemplate::getType, req.getType());
		}
		if (StringUtil.isNotEmpty(req.getContentType())) {
			queryWrapper.like(CostVerifyTemplate::getContentType, req.getContentType());
		}
		if (StringUtil.isNotEmpty(req.getKeyword())) {
			queryWrapper.like(CostVerifyTemplate::getSurveyTemplateName, req.getKeyword()).or().like(CostVerifyTemplate::getSurveyTemplateNameYw, req.getKeyword());
		}
		if (req.getStatus() != null) {
			queryWrapper.eq(CostVerifyTemplate::getStatus, req.getStatus());
		}
		if (StringUtil.isNotEmpty(req.getCatalogId())) {
			queryWrapper.like(CostVerifyTemplate::getCatalogId, req.getCatalogId());
		}
		queryWrapper.orderByDesc(CostVerifyTemplate::getCreateTime);

		// 排序：按编码排序
//        queryWrapper.orderByAsc("code");

		// 创建分页对象
		Page<CostVerifyTemplate> page = new Page<>(req.getPageNum(), req.getPageSize());
		return this.page(page,queryWrapper);
	}

//	@Override
//	public List<CostSurveyTemplate> selectByCondition(CostSurveyTemplate costSurveyTemplate) {
//		return costSurveyTemplateDao.selectByCondition(costSurveyTemplate);
//	}

	@Override
	public CostVerifyTemplate getDetail(String id) {
		CostVerifyTemplate costSurveyTemplate = this.get(id);


		return costSurveyTemplate;
	}
	@Override
	@Transactional
	public void createOrUpdate(CostVerifyTemplate costSurveyTemplate) {
		//新建或更新
		this.saveOrUpdate(costSurveyTemplate);
	}

	@Override
	public void batchRemove(List<String> ids) {
		if (ids != null && !ids.isEmpty()) {
			super.removeByIds(ids);
		}
	}

	@Override
	public List<CostVerifyTemplateHeaders> getHeadersByTemplateId(String templateId) {
		return Collections.emptyList();
	}

	@Override
	public List<CostVerifyTemplateItems> getItemsByTemplateId(String templateId) {
		return Collections.emptyList();
	}


	@Override
	public String selectMaxVersionByDate(String dateStr) {
		QueryWrapper<CostVerifyTemplate> wrapper = new QueryWrapper<>();
		// 查询以指定日期开头的版本号
		wrapper.likeRight("version_no", dateStr);
		// 按版本号降序排列，获取最大的版本号
		wrapper.orderByDesc("version_no");
		wrapper.last("LIMIT 1");

		CostVerifyTemplate version = this.getOne(wrapper);
		if (version != null) {
			return version.getVersionNo();
		}
		return null;
	}
	/**
	 * 生成版本号，格式为：yyyyMMdd + 4位流水号（如：202509270001）
	 * @param
	 * @return 生成的版本号
	 */
	@Override
	public String generateVersionNumber() {
		// 1. 获取当前日期字符串
		String dateStr = new java.text.SimpleDateFormat("yyyyMMdd").format(new java.util.Date());

		// 2. 查询当日最大版本号
		String maxVersion = this.selectMaxVersionByDate(dateStr);

		int sequence = 1;
		if (maxVersion != null && maxVersion.startsWith(dateStr)) {
			// 3. 提取流水号部分并加1
			String sequenceStr = maxVersion.substring(8); // 取后4位
			sequence = Integer.parseInt(sequenceStr) + 1;
		}

		// 4. 格式化生成版本号
		return String.format("%s%04d", dateStr, sequence);
	}

	@Override
	public PageList<CostVerifyTemplate> listPage(ConstVerifyPageParam param) throws Exception {
		IUser iUser = ContextUtil.getCurrentUser();
		User user = userService.getByAccount(iUser.getAccount());
		if(iUser.isAdmin()){
			param.setDataScope(null);
		}else{
			param.setDataScope(user.getDataScope());
		}
		param.setProvinceCode(user.getProvinceCode());
		param.setCityCode(user.getCityCode());
		param.setCountyCode(user.getCountyCode());
		Page<CostVerifyTemplate> objectPage = new Page<>(param.getPage(),param.getPageSize());
		//Page<CostSurveyTemplate> page =baseMapper.getCostSurveyTemplatePage(objectPage,params);
		Page<CostVerifyTemplate> page =baseMapper.getConstVerifyPage(objectPage,param.getContentType()
				,param.getType(),param.getDataScope()
				,param.getProvinceCode(),param.getCityCode()
				,param.getCountyCode(),param.getKeyword(),param.getStatus());
		return new PageList<>(page);
	}


}
