package cn.hanghui.outapi.platform.ldrk.service.impl;

import cn.hanghui.outapi.platform.common.entity.po.Account;
import cn.hanghui.outapi.platform.common.exception.CommonException;
import cn.hanghui.outapi.platform.common.mapper.AccountMapper;
import cn.hanghui.outapi.platform.ldrk.api.LdrkApi;
import cn.hanghui.outapi.platform.ldrk.entity.dto.LdrkReportDto;
import cn.hanghui.outapi.platform.ldrk.entity.param.LdrkReportParam;
import cn.hanghui.outapi.platform.ldrk.service.LdrkService;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service
@AllArgsConstructor(onConstructor_ = @Autowired)
public class LdrkServiceImpl implements LdrkService {

    private final LdrkApi ldrkApi;

    @Resource
    private AccountMapper accountMapper;

    /**
     * 流动人口自主申报
     *
     * @param ldrkReportDto LdrkReportDto
     */
    @Override
    public void reportPersonInfo(LdrkReportDto ldrkReportDto, String username) {
        //校验是否有权限访问
        if (!checkReportAuth(ldrkReportDto.getPcs(), username)) {
            throw new CommonException("调用流动人口自主申报没有权限");
        }
        LdrkReportParam ldrkReportParam = new LdrkReportParam();
        BeanUtil.copyProperties(ldrkReportDto, ldrkReportParam);
        ldrkApi.reportPersonInfo(ldrkReportParam);
    }

    private boolean checkReportAuth(String pcs, String username) {
        try {
            Account account = accountMapper.selectOne(Wrappers.lambdaQuery(Account.class).eq(Account::getName, username));
            if (account == null
                    || account.getIsDeleted()
                    || pcs == null
                    || "".equals(pcs.trim())
                    || account.getPcsCode() == null
                    || "".equals(account.getPcsCode().trim())) {
                return false;
            }
            List<String> pcsCodes = Arrays.asList(account.getPcsCode().trim().split(","));
            if (pcsCodes.contains(pcs)) {
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }
}
