package shop.alien.storeplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.result.R;
import shop.alien.entity.store.ContractBundle;
import shop.alien.entity.store.StoreContract;
import shop.alien.entity.store.dto.StoreContractQueryDto;
import shop.alien.entity.store.vo.StoreContractVo;
import shop.alien.mapper.ContractBundleMapper;
import shop.alien.mapper.StoreContractMapper;
import shop.alien.storeplatform.service.StoreContractService;

import java.util.Date;
import java.util.List;

/**
 * 合同服务实现类
 *
 * @author alien
 * @since 2025-01-XX
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class StoreContractServiceImpl implements StoreContractService {

    /** contract_bundle.subject_type，门店场景固定为 store */
    private static final String CONTRACT_BUNDLE_SUBJECT_TYPE_STORE = "store";

    private final StoreContractMapper storeContractMapper;
    private final ContractBundleMapper contractBundleMapper;

    @Override
    public R<IPage<StoreContractVo>> getContractList(StoreContractQueryDto queryDto) {
        try {
            log.info("StoreContractServiceImpl.getContractList?queryDto={}", queryDto);

            // 构建分页对象
            Page<StoreContractVo> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());

            // 执行分页查询
            IPage<StoreContractVo> result = storeContractMapper.selectContractPage(
                    page,
                    queryDto.getContractName(),
                    queryDto.getStatus(),
                    queryDto.getStoreId()
            );

            // 设置状态名称
            for (StoreContractVo vo : result.getRecords()) {
                if (vo.getStatus() != null) {
                    vo.setStatusName(vo.getStatus());
                }
            }

            return R.data(result);
        } catch (Exception e) {
            log.error("StoreContractServiceImpl.getContractList ERROR: {}", e.getMessage(), e);
            return R.fail("查询合同列表失败: " + e.getMessage());
        }
    }

    @Override
    public R<StoreContractVo> getContractDetail(Integer id) {
        try {
            log.info("StoreContractServiceImpl.getContractDetail?id={}", id);

            StoreContract contract = storeContractMapper.selectById(id);
            if (contract == null) {
                return R.fail("合同不存在");
            }

            StoreContractVo vo = new StoreContractVo();
            BeanUtils.copyProperties(contract, vo);

            // 设置状态名称
            if (vo.getSigningStatus() != null) {
                vo.setStatusName(vo.getSigningStatus());
            }

            return R.data(vo);
        } catch (Exception e) {
            log.error("StoreContractServiceImpl.getContractDetail ERROR: {}", e.getMessage(), e);
            return R.fail("查询合同详情失败: " + e.getMessage());
        }
    }

    @Override
    public R<StoreContract> addContract(StoreContract contract) {
        try {
            log.info("StoreContractServiceImpl.addContract?contract={}", contract);

            // 设置默认值
            if (contract.getSigningStatus() == null) {
                contract.setSigningStatus("未签署"); // 默认未签署
            }
            if (contract.getDeleteFlag() == null) {
                contract.setDeleteFlag(0);
            }
            contract.setCreatedTime(new Date());

            int result = storeContractMapper.insert(contract);
            if (result > 0) {
                return R.data(contract);
            }
            return R.fail("新增合同失败");
        } catch (Exception e) {
            log.error("StoreContractServiceImpl.addContract ERROR: {}", e.getMessage(), e);
            return R.fail("新增合同失败: " + e.getMessage());
        }
    }

    @Override
    public R<StoreContract> updateContract(StoreContract contract) {
        try {
            log.info("StoreContractServiceImpl.updateContract?contract={}", contract);

            if (contract.getId() == null) {
                return R.fail("合同ID不能为空");
            }

            contract.setUpdatedTime(new Date());
            int result = storeContractMapper.updateById(contract);
            if (result > 0) {
                StoreContract updated = storeContractMapper.selectById(contract.getId());
                return R.data(updated);
            }
            return R.fail("更新合同失败");
        } catch (Exception e) {
            log.error("StoreContractServiceImpl.updateContract ERROR: {}", e.getMessage(), e);
            return R.fail("更新合同失败: " + e.getMessage());
        }
    }

    @Override
    public R<Boolean> signContract(Long id) {
        try {
            log.info("StoreContractServiceImpl.signContract?id={}", id);

            StoreContract contract = storeContractMapper.selectById(id);
            if (contract == null) {
                return R.fail("合同不存在");
            }

            if ("已签署".equals(contract.getSigningStatus())) {
                return R.fail("合同已签署，无需重复签署");
            }

            // 更新合同状态为已签署
            StoreContract updateContract = new StoreContract();
            updateContract.setId(id);
            updateContract.setSigningStatus("已签署");
            updateContract.setSigningTime(new Date());
            updateContract.setUpdatedTime(new Date());

            int result = storeContractMapper.updateById(updateContract);
            if (result > 0) {
                return R.success("合同签署成功");
            }
            return R.fail("合同签署失败");
        } catch (Exception e) {
            log.error("StoreContractServiceImpl.signContract ERROR: {}", e.getMessage(), e);
            return R.fail("合同签署失败: " + e.getMessage());
        }
    }

    @Override
    public R<Boolean> deleteContract(Integer id) {
        try {
            log.info("StoreContractServiceImpl.deleteContract?id={}", id);

            StoreContract contract = storeContractMapper.selectById(id);
            if (contract == null) {
                return R.fail("合同不存在");
            }

            // 逻辑删除
            StoreContract updateContract = new StoreContract();
            updateContract.setDeleteFlag(1);
            updateContract.setUpdatedTime(new Date());

            int result = storeContractMapper.updateById(updateContract);
            if (result > 0) {
                return R.success("删除合同成功");
            }
            return R.fail("删除合同失败");
        } catch (Exception e) {
            log.error("StoreContractServiceImpl.deleteContract ERROR: {}", e.getMessage(), e);
            return R.fail("删除合同失败: " + e.getMessage());
        }
    }

    @Override
    public R<String> getSigningStatus(Integer storeId) {
        try {
            log.info("StoreContractServiceImpl.getSigningStatus?storeId={}", storeId);

            if (storeId == null) {
                return R.fail("店铺ID不能为空");
            }

            // contract_bundle：subject_id=店铺ID，subject_type=store，取最新一条
            List<ContractBundle> bundles = contractBundleMapper.selectList(
                    new LambdaQueryWrapper<ContractBundle>()
                            .eq(ContractBundle::getSubjectId, storeId.longValue())
                            .eq(ContractBundle::getSubjectType, CONTRACT_BUNDLE_SUBJECT_TYPE_STORE)
                            .eq(ContractBundle::getDeleteFlag, 0)
                            .orderByDesc(ContractBundle::getCreatedTime)
                            .last("LIMIT 1")
            );

            if (bundles == null || bundles.isEmpty()) {
                return R.fail("该店铺暂无合同");
            }

            return R.data(bundles.get(0).getStatus());
        } catch (Exception e) {
            log.error("StoreContractServiceImpl.getSigningStatus ERROR: {}", e.getMessage(), e);
            return R.fail("获取签署状态失败: " + e.getMessage());
        }
    }
}

