package com.aiotagro.cattletrade.business.service.impl;

import com.aiotagro.cattletrade.business.dto.SlaughterHouseCreateDto;
import com.aiotagro.cattletrade.business.dto.SlaughterHouseDto;
import com.aiotagro.cattletrade.business.dto.SlaughterHouseEditDto;
import com.aiotagro.cattletrade.business.entity.SlaughterHouse;
import com.aiotagro.cattletrade.business.mapper.SlaughterHouseMapper;
import com.aiotagro.cattletrade.business.service.ISlaughterHouseService;
import com.aiotagro.common.core.utils.SecurityUtil;
import com.aiotagro.common.core.utils.bean.BeanUtils;
import com.aiotagro.common.core.web.domain.AjaxResult;
import com.aiotagro.common.core.web.domain.PageResultResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

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

/**
 * 屠宰场管理服务实现
 *
 * @author System
 * @date 2025-12-09
 */
@Service
public class SlaughterHouseServiceImpl extends ServiceImpl<SlaughterHouseMapper, SlaughterHouse> implements ISlaughterHouseService {

    @Autowired
    private SlaughterHouseMapper slaughterHouseMapper;

    @Override
    public PageResultResponse<SlaughterHouse> pageQuery(SlaughterHouseDto dto) {
        Integer pageNum = dto.getPageNum() != null ? dto.getPageNum() : 1;
        Integer pageSize = dto.getPageSize() != null ? dto.getPageSize() : 10;

        Page<SlaughterHouse> page = PageHelper.startPage(pageNum, pageSize);

        LambdaQueryWrapper<SlaughterHouse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper.eq(SlaughterHouse::getIsDelete, 0).or().isNull(SlaughterHouse::getIsDelete));

        if (StringUtils.hasText(dto.getHouseName())) {
            queryWrapper.like(SlaughterHouse::getHouseName, dto.getHouseName());
        }
        if (StringUtils.hasText(dto.getSlaughterCode())) {
            queryWrapper.like(SlaughterHouse::getSlaughterCode, dto.getSlaughterCode());
        }
        if (dto.getStatus() != null) {
            queryWrapper.eq(SlaughterHouse::getStatus, dto.getStatus());
        }

        queryWrapper.orderByDesc(SlaughterHouse::getCreateTime);

        List<SlaughterHouse> list = slaughterHouseMapper.selectList(queryWrapper);
        return new PageResultResponse<>(page.getTotal(), list);
    }

    @Override
    @Transactional
    public AjaxResult addHouse(SlaughterHouseCreateDto dto) {
        String code = dto.getSlaughterCode();
        if (!StringUtils.hasText(code)) {
            code = generateSlaughterCode();
        } else {
            SlaughterHouse exist = slaughterHouseMapper.selectByCode(code);
            if (exist != null) {
                return AjaxResult.error("屠宰场编码已存在");
            }
        }

        SlaughterHouse house = new SlaughterHouse();
        BeanUtils.copyProperties(dto, house);
        house.setSlaughterCode(code);
        if (house.getStatus() == null) {
            house.setStatus(1);
        }

        Integer userId = SecurityUtil.getCurrentUserId();
        house.setCreatedBy(userId);
        house.setCreateTime(new Date());

        try {
            int inserted = slaughterHouseMapper.insert(house);
            return inserted > 0 ? AjaxResult.success("新增屠宰场成功") : AjaxResult.error("新增屠宰场失败");
        } catch (DuplicateKeyException e) {
            return AjaxResult.error("屠宰场编码已存在，请使用其他编码");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("新增屠宰场失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public AjaxResult updateHouse(SlaughterHouseEditDto dto) {
        if (dto.getId() == null) {
            return AjaxResult.error("屠宰场ID不能为空");
        }

        SlaughterHouse exist = slaughterHouseMapper.selectById(dto.getId());
        if (exist == null || (exist.getIsDelete() != null && exist.getIsDelete() == 1)) {
            return AjaxResult.error("屠宰场不存在");
        }

        SlaughterHouse codeHouse = slaughterHouseMapper.selectByCode(dto.getSlaughterCode());
        if (codeHouse != null && !codeHouse.getId().equals(dto.getId())) {
            return AjaxResult.error("屠宰场编码已存在");
        }

        SlaughterHouse house = new SlaughterHouse();
        BeanUtils.copyProperties(dto, house);

        Integer userId = SecurityUtil.getCurrentUserId();
        house.setUpdatedBy(userId);
        house.setUpdateTime(new Date());

        try {
            int updated = slaughterHouseMapper.updateById(house);
            return updated > 0 ? AjaxResult.success("更新屠宰场成功") : AjaxResult.error("更新屠宰场失败");
        } catch (DuplicateKeyException e) {
            return AjaxResult.error("屠宰场编码已存在，请使用其他编码");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("更新屠宰场失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public AjaxResult deleteHouse(Integer id) {
        if (id == null) {
            return AjaxResult.error("屠宰场ID不能为空");
        }
        SlaughterHouse house = slaughterHouseMapper.selectById(id);
        if (house == null || (house.getIsDelete() != null && house.getIsDelete() == 1)) {
            return AjaxResult.error("屠宰场不存在");
        }

        Integer userId = SecurityUtil.getCurrentUserId();

        UpdateWrapper<SlaughterHouse> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).eq("is_delete", 0)
                .set("is_delete", 1)
                .set("updated_by", userId)
                .set("update_time", new Date());

        int result = slaughterHouseMapper.update(null, updateWrapper);
        return result > 0 ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    @Override
    public AjaxResult detail(Integer id) {
        if (id == null) {
            return AjaxResult.error("屠宰场ID不能为空");
        }
        SlaughterHouse house = slaughterHouseMapper.selectById(id);
        if (house == null || (house.getIsDelete() != null && house.getIsDelete() == 1)) {
            return AjaxResult.error("屠宰场不存在");
        }
        return AjaxResult.success("查询成功", house);
    }

    @Override
    public List<SlaughterHouse> getAllEnabled() {
        return slaughterHouseMapper.selectAllEnabled();
    }

    /**
     * 生成屠宰场编码：SLyyyyMMdd + 4位流水
     */
    private String generateSlaughterCode() {
        String dateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String prefix = "SL" + dateStr;
        SlaughterHouse last = slaughterHouseMapper.selectLastCode(prefix + "%");
        int next = 1;
        if (last != null && StringUtils.hasText(last.getSlaughterCode())) {
            String lastCode = last.getSlaughterCode();
            if (lastCode.startsWith(prefix)) {
                String seq = lastCode.substring(prefix.length());
                try {
                    next = Integer.parseInt(seq) + 1;
                } catch (NumberFormatException ignored) {
                    next = 1;
                }
            }
        }
        return String.format("%s%04d", prefix, next);
    }
}

