package org.dromara.zhishu.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.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.dromara.zhishu.domain.NewUserInfo;
import org.dromara.zhishu.domain.TBookAudit;
import org.dromara.zhishu.domain.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.dromara.zhishu.domain.bo.TAuditBo;
import org.dromara.zhishu.domain.vo.TAuditVo;
import org.dromara.zhishu.domain.TAudit;
import org.dromara.zhishu.mapper.TAuditMapper;
import org.dromara.zhishu.service.ITAuditService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * 审核Service业务层处理
 *
 * @author Lion Li
 * @date 2025-04-01
 */
@RequiredArgsConstructor
@Service
public class TAuditServiceImpl implements ITAuditService {

    private static final Logger log = LoggerFactory.getLogger(TAuditServiceImpl.class);

    @Autowired
    private final TAuditMapper baseMapper;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 查询审核
     *
     * @param id 主键
     * @return 审核
     */
    @Override
    public TAuditVo queryById(Long id) {
        TAuditVo tAuditVo = baseMapper.selectVoById(id);
        NewUserInfo infor = baseMapper.selectUserList(id);
        tAuditVo.setCompanyName(infor.getCompanyName());
        tAuditVo.setCompanyType(infor.getCompanyType());
        tAuditVo.setContactPerson(infor.getContactPerson());
        tAuditVo.setContactPhone(infor.getContactPhone());
        tAuditVo.setEmail(infor.getEmail());
        tAuditVo.setLicense(infor.getLicense());
        tAuditVo.setRemark(infor.getRemark());
        tAuditVo.setLicenseNumber(infor.getLicenseNumber());
        tAuditVo.setLicenseName(infor.getLicenseName());
        tAuditVo.setCardIdentity(infor.getCardIdentity());
        tAuditVo.setLicenseTime(infor.getLicenseTime());
        tAuditVo.setBusinessLicense(infor.getBusinessLicense());
        tAuditVo.setBusinessLicenseTime(infor.getBusinessLicenseTime());
        tAuditVo.setAdress(infor.getAdress());
        return tAuditVo;
    }

    /**
     * 分页查询审核列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 审核分页列表
     */
    @Override
    public TableDataInfo<TAuditVo> queryPageList(TAuditBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TAudit> lqw = buildQueryWrapper(bo);
//        Page<TAuditVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<TAuditVo> result = baseMapper.selectPageVo(pageQuery.build(), bo);
//        //获取result.getRecords()数据，并将里面内容进行赋值
        // 遍历result.getRecords()
        for (int i = 0; i < result.getRecords().size(); i++) {
            // 获取当前行的id
            Long id = result.getRecords().get(i).getAuditId();
            // 获取当前行的用户名称
            TAudit tAudit = baseMapper.selectId(id);
            if (tAudit != null) {
                String name = baseMapper.selectUserName(tAudit.getUserId());

                result.getRecords().get(i).setUserName(name);
                result.getRecords().get(i).setAdminId(tAudit.getAdminId());
//            result.getRecords().get(i).setUserId(tAudit.getUserId());
                result.getRecords().get(i).setStatus(tAudit.getStatus());
                result.getRecords().get(i).setId(tAudit.getId());
            }

        }

        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的审核列表
     *
     * @param bo 查询条件
     * @return 审核列表
     */
    @Override
    public List<TAuditVo> queryList(TAuditBo bo) {
        LambdaQueryWrapper<TAudit> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }


    private LambdaQueryWrapper<TAudit> buildQueryWrapper(TAuditBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TAudit> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(TAudit::getId);
        lqw.eq(bo.getUserId() != null, TAudit::getUserId, bo.getUserId());
        lqw.eq(bo.getAdminId() != null, TAudit::getAdminId, bo.getAdminId());
//        lqw.like(StringUtils.isNotBlank(bo.getCompanyName()), TAudit::getCompanyName, bo.getCompanyName())
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), TAudit::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增审核
     *
     * @param bo 审核
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TAuditBo bo) {
        TAudit add = MapstructUtils.convert(bo, TAudit.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
//            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改审核
     *
     * @param bo 审核
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TAuditBo bo) {
        // 修改用户信息
        bo.setStatus("2");
        TAudit update = MapstructUtils.convert(bo, TAudit.class);
        NewUserInfo newUserInfo = new NewUserInfo();
        newUserInfo.setCompanyName(bo.getCompanyName());
        newUserInfo.setCompanyType(bo.getCompanyType());
        newUserInfo.setContactPerson(bo.getContactPerson());
        newUserInfo.setContactPhone(bo.getContactPhone());
        newUserInfo.setEmail(bo.getEmail());
        newUserInfo.setLicense(bo.getLicense());
        newUserInfo.setRemark(bo.getRemark());
        newUserInfo.setAuditId(update.getId());
        baseMapper.updateByUser(newUserInfo);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

    /**
     * 校验并批量删除审核信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Transactional
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
            baseMapper.deleteUser(ids);
        }
        return baseMapper.deleteByIds(ids) > 0;
    }


    @Override
    public int updateByStatus(TAuditBo bo) {
        //获取用户id
        Long userId = baseMapper.selectUserId(bo.getId());
        if (bo.getStatus().equals("0")) {
            //删除当前用户角色（游客）
            Integer message = baseMapper.deleteUserRole(userId, 1906216348137664514L);
            //新增角色（入驻书店）
            Integer message1 = baseMapper.insertUserRole(userId, 1905510246538407937L);
//            1906216348137664514 --->Visitor
//            1905510246538407937--->Settled
            
            // 调用外部接口添加会员
            try {
                String url = "https://newadmin.buzhiyushu.cn/settledMember/record/addMember?userId=" + userId;
                ResponseEntity<String> response = restTemplate.postForEntity(url, null, String.class);
                log.info("调用添加会员接口结果: {}", response.getBody());
            } catch (Exception e) {
                log.error("调用添加会员接口失败: {}", e.getMessage(), e);
            }
        }
        
//修改审核状态
        return baseMapper.updateStatus(bo);
    }

    @Override
    public Integer InsertLog(TAuditBo bo) {
        Integer message = baseMapper.insertAuditLog(bo);
        return message;
    }
}
