package com.propertyManagement.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.propertyManagement.business.domain.WxAccount;
import com.propertyManagement.business.domain.vo.LoginWxUser;
import com.propertyManagement.business.domain.vo.WxAccountVo;
import com.propertyManagement.business.mapper.WxAccountMapper;
import com.propertyManagement.business.support.util.AuthUtil;
import com.propertyManagement.common.core.domain.BaseEntity;
import com.propertyManagement.common.enums.AccountType;
import com.propertyManagement.common.utils.StringUtils;
import com.propertyManagement.common.core.page.TableDataInfo;
import com.propertyManagement.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.propertyManagement.business.domain.bo.WxRepairsBo;
import com.propertyManagement.business.domain.vo.WxRepairsVo;
import com.propertyManagement.business.domain.WxRepairs;
import com.propertyManagement.business.mapper.WxRepairsMapper;
import com.propertyManagement.business.service.IWxRepairsService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 报修Service业务层处理
 *
 * @author liushuai
 * @date 2025-05-14
 */
@RequiredArgsConstructor
@Service
public class WxRepairsServiceImpl implements IWxRepairsService {

    private final WxRepairsMapper baseMapper;
    private final WxAccountMapper wxAccountMapper;

    /**
     * 查询报修
     */
    @Override
    public WxRepairsVo queryById(Long repairsId){
        return baseMapper.selectVoById(repairsId);
    }

    /**
     * 查询报修列表
     */
    @Override
    public TableDataInfo<WxRepairsVo> queryPageList(WxRepairsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WxRepairs> lqw = buildQueryWrapper(bo);
        Page<WxRepairsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询报修列表
     */
    @Override
    public List<WxRepairsVo> queryList(WxRepairsBo bo) {
        LambdaQueryWrapper<WxRepairs> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }


    private LambdaQueryWrapper<WxRepairs> buildQueryWrapper(WxRepairsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WxRepairs> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getAccountId() != null, WxRepairs::getAccountId, bo.getAccountId());
        lqw.eq(bo.getAccountName() != null, WxRepairs::getAccountName, bo.getAccountName());
        lqw.eq(bo.getAccountMobile() != null, WxRepairs::getAccountMobile, bo.getAccountMobile());
        lqw.eq(bo.getUserId() != null, WxRepairs::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), WxRepairs::getUserName, bo.getUserName());
        lqw.eq(bo.getCommunityId() != null, WxRepairs::getCommunityId, bo.getCommunityId());
        lqw.like(StringUtils.isNotBlank(bo.getCommunityName()), WxRepairs::getCommunityName, bo.getCommunityName());
        lqw.like(StringUtils.isNotBlank(bo.getProprietorName()), WxRepairs::getProprietorName, bo.getProprietorName());
        lqw.eq(StringUtils.isNotBlank(bo.getProprietorPhone()), WxRepairs::getProprietorPhone, bo.getProprietorPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getRoom()), WxRepairs::getRoom, bo.getRoom());
        lqw.eq(StringUtils.isNotBlank(bo.getRepairsDescription()), WxRepairs::getRepairsDescription, bo.getRepairsDescription());
        lqw.eq(StringUtils.isNotBlank(bo.getRepairsImg()), WxRepairs::getRepairsImg, bo.getRepairsImg());
        lqw.eq(bo.getRepairsTime() != null, WxRepairs::getRepairsTime, bo.getRepairsTime());
        lqw.eq(bo.getCompleteTime() != null, WxRepairs::getCompleteTime, bo.getCompleteTime());
        lqw.eq(bo.getCloseTime() != null, WxRepairs::getCloseTime, bo.getCloseTime());
        lqw.eq(bo.getState() != null, WxRepairs::getState, bo.getState());
        lqw.eq(bo.getType() != null, WxRepairs::getType, bo.getType());
        lqw.orderByDesc(WxRepairs::getCreateTime);
        return lqw;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean add(WxRepairsBo bo) {
        WxRepairs add = BeanUtil.toBean(bo, WxRepairs.class);
        validEntityBeforeSave(add);
        LoginWxUser wxUser = AuthUtil.getWxUser();
        /**
         * 正序查询当前小区所有维修人员，分配维修人员
         */
        LambdaQueryWrapper<WxAccount> accountLambdaQueryWrapper = Wrappers.lambdaQuery();
        accountLambdaQueryWrapper
            .eq(WxAccount::getCommunityId, wxUser.getCommunityId())
            .eq(WxAccount::getType, AccountType.THREE.getCode())
            .orderByAsc(BaseEntity::getUpdateTime);
        List<WxAccount> accountList = wxAccountMapper.selectList(accountLambdaQueryWrapper);
        if (!accountList.isEmpty()) {
            WxAccount wxAccount = accountList.get(0);
            add.setAccountId(wxAccount.getAccountId());
            add.setAccountName(wxAccount.getName());
            add.setAccountMobile(wxAccount.getMobile());
            /**
             * 更新维修人员更新时间
             */
            wxAccount.setUpdateTime(new Date());
            wxAccountMapper.updateById(wxAccount);
        }

        add.setRepairsTime(new Date());
        add.setUserId(wxUser.getId());
        add.setUserName(wxUser.getNickName());
        add.setCommunityId(wxUser.getCommunityId());
        add.setCommunityName(wxUser.getCommunityName());
        add.setProprietorName(wxUser.getName());
        add.setProprietorPhone(wxUser.getMobile());
        add.setRoom(wxUser.getRoom());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setRepairsId(add.getRepairsId());
        }
        return flag;
    }

    /**
     * 新增报修
     */
    @Override
    public Boolean insertByBo(WxRepairsBo bo) {
        WxRepairs add = BeanUtil.toBean(bo, WxRepairs.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setRepairsId(add.getRepairsId());
        }
        return flag;
    }

    /**
     * 修改报修
     */
    @Override
    public Boolean updateByBo(WxRepairsBo bo) {
        WxRepairs update = BeanUtil.toBean(bo, WxRepairs.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(WxRepairs entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除报修
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
