package com.gree.mall.manager.logic.workorder;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.workorder.AbnormalVO;
import com.gree.mall.manager.bean.workorder.IncreVO;
import com.gree.mall.manager.commonmapper.workorder.IncreMapper;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.Abnormal;
import com.gree.mall.manager.plus.service.AbnormalService;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class AbnormalLogic {

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    IncreMapper increMapper;

    @Autowired
    AbnormalService abnormalService;


    public IPage<AbnormalVO> list(Page page, ZfireParamBean zfireParam) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        List<String> adminCompanyIds = adminUser.getCompanyWechatIds();
        //1.组装查询条件
        zfireParam = FieldUtils.supplyParam(zfireParam, AbnormalVO.class);

        IPage<AbnormalVO> abnormalVOIPage = increMapper.listAbnormal(page, zfireParam,adminCompanyIds);
        return abnormalVOIPage;
    }

    public Abnormal detail(String id) {
        return abnormalService.getById(id);
    }

    public void add(Abnormal abnormal) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (abnormalService.lambdaQuery().eq(Abnormal::getExType,abnormal.getExType())
                .eq(Abnormal::getCompanyWechatId,adminUser.getCompanyWechatId())
                .eq(Abnormal::getExNote,abnormal.getExNote()).count() > 0) {
            throw new RemoteServiceException("存在相同原因");
        }

        abnormal.setCompanyWechatId(adminUser.getCompanyWechatId());
        abnormal.setCompanyWechatName(adminUser.getCompanyName());
        abnormal.insert();
    }

    public void update(Abnormal abnormal) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (abnormalService.lambdaQuery().eq(Abnormal::getExType,abnormal.getExType())
                .eq(Abnormal::getCompanyWechatId,adminUser.getCompanyWechatId())
                .eq(Abnormal::getExNote,abnormal.getExNote())
                .ne(Abnormal::getId,abnormal.getId())
                .count() > 0) {
            throw new RemoteServiceException("存在相同原因");
        }
        abnormal.updateById();
    }
}
