package org.dromara.payment.worker.service.impl;

import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.service.BaseService;
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.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.payment.worker.domain.UserWorker;
import org.dromara.payment.worker.domain.bo.UserWokerOperBo;
import org.dromara.payment.worker.mapper.UserWorkerMapper;
import org.dromara.settlement.api.RemoteAccountService;
import org.dromara.settlement.api.domain.Account;
import org.dromara.settlement.api.domain.Result;
import org.springframework.stereotype.Service;
import org.dromara.payment.worker.domain.bo.UserWorkerAccountBo;
import org.dromara.payment.worker.domain.vo.UserWorkerAccountVo;
import org.dromara.payment.worker.domain.UserWorkerAccount;
import org.dromara.payment.worker.mapper.UserWorkerAccountMapper;
import org.dromara.payment.worker.service.IUserWorkerAccountService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 自雇者账户Service业务层处理
 *
 * @author LionLi
 * @date 2024-04-28
 */
@RequiredArgsConstructor
@Service
public class UserWorkerAccountServiceImpl extends BaseService implements IUserWorkerAccountService {

    private final UserWorkerAccountMapper baseMapper;

    @DubboReference
    private RemoteAccountService accountService;
    @Resource
    private UserWorkerMapper userWorkerMapper;
    /**
     * 查询自雇者账户
     */
    @Override
    public UserWorkerAccountVo queryById(Long id){
        UserWorkerAccountVo vo = baseMapper.selectVoById(id);
        return vo;
    }

    /**
     * 查询自雇者账户列表
     */
    @Override
    public TableDataInfo<UserWorkerAccountVo> queryPageList(UserWorkerAccountBo bo, PageQuery pageQuery) {
        bo.setStatus(1);
        QueryWrapper<UserWorkerAccount> lqw = buildQueryWrapper(bo);
        Page<UserWorkerAccountVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询自雇者账户列表
     */
    @Override
    public List<UserWorkerAccountVo> queryList(UserWorkerAccountBo bo) {

        if(bo.getWorkId() == null){
            this.invalidationParamsException("用工ID不能为空");
        }

        QueryWrapper<UserWorkerAccount> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private QueryWrapper<UserWorkerAccount> buildQueryWrapper(UserWorkerAccountBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<UserWorkerAccount> lqw = new QueryWrapper<>();
        lqw.eq(bo.getWorkId() != null, "work_id", bo.getWorkId());
        lqw.eq(bo.getAccId() != null, "acc_id", bo.getAccId());
        lqw.eq(StringUtils.isNotBlank(bo.getBankType()), "bank_type", bo.getBankType());
        lqw.eq(StringUtils.isNotBlank(bo.getBankCard()), "bank_card", bo.getBankCard());
        lqw.eq(bo.getIsDefault() != null, "is_default", bo.getIsDefault());
        lqw.eq(bo.getAddTime() != null, "add_time", bo.getAddTime());
        lqw.eq(StringUtils.isNotBlank(bo.getBankCardPic()), "bank_card_pic", bo.getBankCardPic());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), "phone", bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getPassage()), "passage", bo.getPassage());
        lqw.orderByDesc("create_time");
        return lqw;
    }

    /**
     * 新增自雇者账户
     */
    @Override
    public Boolean insertByBo(UserWorkerAccountBo bo) {
        UserWorkerAccount add = MapstructUtils.convert(bo, UserWorkerAccount.class);
        validEntityBeforeSave(add);
        UserWokerOperBo bno = new UserWokerOperBo();
        bno.setWork_id(bo.getWorkId());
        bno.setChannelName(bo.getPassage());
        List<UserWorkerAccountVo>  accountVo = this.baseMapper.selctBankInfoByUidChannelBankNo(bno);
        boolean isDefault = false;
        boolean cz = false;
        UserWorkerAccountVo  selVo = null;

        if(accountVo != null && !accountVo.isEmpty()){
            for(UserWorkerAccountVo vo :accountVo){
                if(vo.getIsDefault() == 1){
                    isDefault = true;
                }
                if(vo.getBankCard().equals(bo.getBankCard())){
                    cz = true;
                    selVo = vo;
                }
            }
        }

        if(cz){
            UserWorkerAccount  uwab = new UserWorkerAccount();
            uwab.setId(selVo.getId());
            uwab.setStatus(1);
            uwab.setPhone(bo.getPhone());
            this.baseMapper.updateById(uwab);
        }else if(!cz){

            UserWorker uw = this.userWorkerMapper.selectById(bo.getWorkId());
            //先生成账号
            Account bankAcc = new Account();
            bankAcc.setType((short)2);//2:真实个人账户
            bankAcc.setBankCard(bo.getBankCard());
            bankAcc.setBankType(bo.getBankType());
            bankAcc.setUnitId(0L);
            bankAcc.setName(uw.getName());
            Result<Account> result = this.accountService.addAccount(bankAcc);
            Integer accountId = result.getRtnData().getId();
            if(accountId == null){
                this.invalidationParamsException("创建账号失败!");
            }

            //添加银行卡
            UserWorkerAccount  uwab = new UserWorkerAccount();
            uwab.setWorkId(bo.getWorkId());
            uwab.setAccId(Long.valueOf(accountId));
            uwab.setBankCard(bo.getBankCard());
            uwab.setPassage(bo.getPassage());
            uwab.setBankType(bo.getBankType());
            uwab.setCreateTime(new Date());
            uwab.setPhone(bo.getPhone());
            uwab.setCreateBy(LoginHelper.getUserId());
            if(!isDefault){
                uwab.setIsDefault(1L);
            }else{
                uwab.setIsDefault(0L);
            }
            this.baseMapper.insert(uwab);
        }
        return true;
    }

    /**
     * 修改自雇者账户
     */
    @Override
    public Boolean updateByBo(UserWorkerAccountBo bo) {
        UserWorkerAccount update = MapstructUtils.convert(bo, UserWorkerAccount.class);
        validEntityBeforeSave(update);
        update.setUpdateBy(LoginHelper.getUserId());
        update.setCreateTime(new Date());

        UserWorkerAccountVo  uwav = this.baseMapper.selectVoById(bo.getId());
        if(uwav != null){
            if(uwav.getBankCard().equals(bo.getBankCard())){
                baseMapper.updateById(update);
            }else{
                UserWorkerAccount b = new UserWorkerAccount();
                b.setId(bo.getId());
                b.setStatus(0);
                baseMapper.updateById(b);
                this.insertByBo(bo);
            }
        }
        return true;
    }

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

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

    @Override
    public UserWorkerAccount rePayMdyWorkerBank(UserWorkerAccountBo bo) {
        UserWorkerAccount add = MapstructUtils.convert(bo, UserWorkerAccount.class);
        validEntityBeforeSave(add);
        UserWokerOperBo bno = new UserWokerOperBo();
        bno.setWork_id(bo.getWorkId());
        bno.setChannelName(bo.getPassage());
        List<UserWorkerAccountVo>  accountVo = this.baseMapper.selctBankInfoByUidChannelBankNo(bno);
        boolean isDefault = false;
        boolean cz = false;
        UserWorkerAccountVo  defaultVo = null;
        UserWorkerAccountVo  selVo = null;

        if(accountVo != null && !accountVo.isEmpty()){
            for(UserWorkerAccountVo vo :accountVo){
                if(vo.getIsDefault() == 1){
                    isDefault = true;
                    defaultVo = vo;
                }
                if(vo.getBankCard().equals(bo.getBankCard())){
                    cz = true;
                    selVo = vo;
                }
            }
        }

        if(defaultVo != null){
            UserWorkerAccount  uwab = new UserWorkerAccount();
            uwab.setId(defaultVo.getId());
            uwab.setIsDefault(0L);
            this.baseMapper.updateById(uwab);
        }

        if(cz){


            UserWorkerAccount  uwab = new UserWorkerAccount();
            uwab.setId(selVo.getId());
            uwab.setStatus(1);
            uwab.setIsDefault(1L);
            uwab.setPhone(bo.getPhone());
            this.baseMapper.updateById(uwab);
            uwab.setAccId(selVo.getAccId());
            uwab.setBankType(selVo.getBankType());
            uwab.setBankCard(selVo.getBankCard());
            uwab.setWorkId(selVo.getWorkId());
            return uwab;
        }else if(!cz){

            UserWorker uw = this.userWorkerMapper.selectById(bo.getWorkId());
            //先生成账号
            Account bankAcc = new Account();
            bankAcc.setType((short)2);//2:真实个人账户
            bankAcc.setBankCard(bo.getBankCard());
            bankAcc.setBankType(bo.getBankType());
            bankAcc.setUnitId(0L);
            bankAcc.setName(uw.getName());
            Result<Account> result = this.accountService.addAccount(bankAcc);
            Integer accountId = result.getRtnData().getId();
            if(accountId == null){
                this.invalidationParamsException("创建账号失败!");
            }

            if(defaultVo != null){
                UserWorkerAccount  uwab = new UserWorkerAccount();
                uwab.setId(defaultVo.getId());
                uwab.setIsDefault(0L);
                this.baseMapper.updateById(uwab);
            }

            //添加银行卡
            UserWorkerAccount  uwab = new UserWorkerAccount();
            uwab.setWorkId(bo.getWorkId());
            uwab.setAccId(Long.valueOf(accountId));
            uwab.setBankCard(bo.getBankCard());
            uwab.setPassage(bo.getPassage());
            uwab.setBankType(bo.getBankType());
            uwab.setCreateTime(new Date());
            uwab.setPhone(bo.getPhone());
            uwab.setCreateBy(LoginHelper.getUserId());
            uwab.setIsDefault(1L);
//            if(!isDefault){
//                uwab.setIsDefault(1L);
//            }else{
//                uwab.setIsDefault(0L);
//            }
            this.baseMapper.insert(uwab);

            return uwab;
        }
        return null;
    }
}
