package com.seer.teach.mp.admin.service;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.enums.RoleEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.mp.admin.controller.req.MpDealerApplyQueryReq;
import com.seer.teach.mp.admin.controller.resp.MpDealerApplyResp;
import com.seer.teach.mp.admin.convert.AdminDealerApplicationsConvert;
import com.seer.teach.mp.entity.MpDealerApplicationsEntity;
import com.seer.teach.mp.request.DealerApplyReq;
import com.seer.teach.mp.service.IMpDealerApplicationsService;
import com.seer.teach.user.api.UserInfoServiceApi;
import com.seer.teach.user.api.dto.UserInfoDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class AdminDealerApplicationsService {

    private final IMpDealerApplicationsService mpDealerApplicationsService;

    private final UserInfoServiceApi userInfoServiceApi;

    /**
     * 获取申请列表
     *
     * @param pageReq 分页参数
     * @return 申请列表
     */
    public PageListBean<MpDealerApplyResp> pageList(MpDealerApplyQueryReq pageReq) {
        Page<MpDealerApplicationsEntity> pageParm = new Page<>(pageReq.getPageNo(), pageReq.getPageSize());

        MpDealerApplicationsEntity query = AdminDealerApplicationsConvert.INSTANCE.convertOne(pageReq);
        IPage<MpDealerApplicationsEntity> resultPage = mpDealerApplicationsService.pageList(pageParm, query);

        return PageConverterUtils.convertPageListBean(resultPage, AdminDealerApplicationsConvert.INSTANCE::convertRespList);
    }

    /**
     * 获取申请记录
     *
     * @param id 申请Id
     * @return 申请记录
     */
    public MpDealerApplyResp getApplicationById(Integer id) {
        MpDealerApplicationsEntity dealerApplicationsEntity = mpDealerApplicationsService.getOneById(id);
        return AdminDealerApplicationsConvert.INSTANCE.convertOne(dealerApplicationsEntity);
    }

    /**
     * 审批申请
     *
     * @param id       申请Id
     * @param approved 是否通过
     * @param remark   备注
     * @return 是否成功
     */
    public Boolean approveApplication(Integer id, boolean approved, String remark) {
        MpDealerApplicationsEntity application = mpDealerApplicationsService.getById(id);
        if (application == null) {
            throw new CommonException(ResultCodeEnum.DEALER_APPLICATION_NOT_FOUND);
        }
        if(approved){
            UserInfoDTO userInfoDTO = new UserInfoDTO();
            userInfoDTO.setId(application.getApplicantUserId());
            userInfoDTO.setRealName(application.getApplicantName());
            userInfoDTO.setMobile(application.getPhone());
            userInfoDTO.setIdCardNumber(application.getIdCardNumber());
            userInfoDTO.setRoleCode(RoleEnum.DISTRIBUTOR);
            boolean updated = userInfoServiceApi.updateUserInfoAndAssignRole(userInfoDTO);
            log.info("更新用户[{}]信息结果: {}",application.getApplicantUserId(), updated);
            if(updated){
                log.info("更新用户[{}]信息成功",application.getApplicantUserId());
            }
        }
        application.setStatus(approved ? 1 : 2);
        boolean updated = mpDealerApplicationsService.updateById(application);
        log.info("更新申请记录结果: {}", updated);
        if (updated) {
            log.info("更新申请记录成功，申请记录Id: {}", id);
        }
        return updated;
    }

    /**
     * 删除审核信息
     * @param ids
     * @return
     */
    public Boolean deleteById(List<Integer> ids) {
        if(ids == null || ids.isEmpty()){
            throw new CommonException(ResultCodeEnum.DEALER_APPLICATION_NO_SELECTION);
        }
        List<MpDealerApplicationsEntity> list = mpDealerApplicationsService.listByIds(ids);
        for(MpDealerApplicationsEntity entity : list){
            if(entity.getStatus()==0 || entity.getStatus()==1){
                throw new CommonException(ResultCodeEnum.DEALER_APPLICATION_CANNOT_DELETE);
            }
        }
        boolean remove = mpDealerApplicationsService.removeByIds(ids);
        log.info("删除申请记录信息:{}",remove);
        if(remove){
            log.info("删除申请记录成功,Id:{}",ids);
        }
        return remove;
    }

    public boolean apply(DealerApplyReq req) {
        Integer userId = StpUtil.getLoginIdAsInt();
        log.info("用户[{}]申请", userId);
        return mpDealerApplicationsService.apply(req, userId);
    }
}