package com.jeeplus.psimanage.dishManage.service;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.psimanage.dishManage.domain.PsiCreditCustomer;
import com.jeeplus.psimanage.dishManage.mapper.PsiCreditCustomerMapper;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

/**
 * 挂账人信息登记
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PsiCreditCustomerService extends ServiceImpl<PsiCreditCustomerMapper, PsiCreditCustomer> {

    @Resource
    private PsiCreditCustomerMapper mapper;

    public IPage<PsiCreditCustomer> list(Page<PsiCreditCustomer> page, PsiCreditCustomer info) {
        QueryWrapper<PsiCreditCustomer> wrapper = new QueryWrapper<>();
        wrapper.eq("a.del_flag", "0");
        if (StringUtils.isNotBlank(info.getCustomerName())) {
            wrapper.like("a.customer_name", info.getCustomerName());
        }
        if (StringUtils.isNotBlank(info.getMobile())) {
            wrapper.like("a.mobile", info.getMobile());
        }
        if (StringUtils.isNotBlank(info.getCreditStatus())) {
            wrapper.eq("a.credit_status", info.getCreditStatus());
        }
        if (StringUtils.isNotBlank(info.getCompanyName())) {
            wrapper.like("a.company_name", info.getCompanyName());
        }
        return mapper.findList(page, wrapper);
    }

    public PsiCreditCustomer findById(String id) {
        return mapper.queryById(id);
    }

    public void updateStatusById(PsiCreditCustomer info) {
        String auditorId = null;
        if ("4".equals(info.getStatus()) || "5".equals(info.getStatus())) {
            UserDTO userDto = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
            auditorId = userDto.getId();
        }
        mapper.updateStatusById(info.getId(), info.getStatus(), auditorId);
    }

    public String saveCreditCustomer(PsiCreditCustomer info) {
        String errorMessage = validateCreditCustomer(info);
        if (StringUtils.isNotBlank(errorMessage)) {
            return errorMessage;
        }
        saveCreditCustomerAndReturnId(info);
        return "操作完成";
    }

    public String saveCreditCustomerForFlow(PsiCreditCustomer info) {
        String errorMessage = validateCreditCustomer(info);
        if (StringUtils.isNotBlank(errorMessage)) {
            throw new IllegalArgumentException(errorMessage);
        }
        return saveCreditCustomerAndReturnId(info);
    }

    private String validateCreditCustomer(PsiCreditCustomer info) {
        if (StringUtils.isBlank(info.getCustomerName())) {
            return "姓名不能为空";
        }
        if (StringUtils.isBlank(info.getMobile())) {
            return "手机号不能为空";
        }
        Integer mobileCount = mapper.checkMobileIsExist(info.getMobile(), info.getId());
        if (mobileCount != null && mobileCount > 0) {
            return "手机号重复，请重新填写";
        }
        return null;
    }

    private String saveCreditCustomerAndReturnId(PsiCreditCustomer info) {
        UserDTO userDto = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        if (StringUtils.isNotBlank(info.getId())) {
            info.setUpdateById(userDto.getId());
            info.setUpdateTime(new Date());
            mapper.updateById(info);
        } else {
            info.setId(UUID.randomUUID().toString().replace("-", ""));
            info.setCreateById(userDto.getId());
            info.setCreateTime(new Date());
            info.setUpdateById(userDto.getId());
            info.setUpdateTime(new Date());
            info.setDelFlag(0);
            if (StringUtils.isBlank(info.getCreditStatus())) {
                info.setCreditStatus("1");
            }
            if (info.getTotalArrearsAmount() == null) {
                info.setTotalArrearsAmount(BigDecimal.ZERO);
            }
            if (info.getUnsettledBillCount() == null) {
                info.setUnsettledBillCount(0);
            }
            mapper.insert(info);
        }
        return info.getId();
    }

    public String deleteByIds(String ids) {
        if (StringUtils.isBlank(ids)) {
            return "请选择要删除的数据";
        }
        mapper.deleteBatchIds(Arrays.asList(ids.split(",")));
        return "删除成功";
    }

    public String changeStatus(String id, String creditStatus) {
        if (StringUtils.isBlank(id)) {
            return "请选择要操作的数据";
        }
        PsiCreditCustomer info = new PsiCreditCustomer();
        info.setId(id);
        info.setCreditStatus(creditStatus);
        info.setUpdateTime(new Date());
        mapper.updateById(info);
        return "操作成功";
    }
}
