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

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.enums.BusRole;
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.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.payment.common.domain.BusOperLog;
import org.dromara.payment.common.domain.vo.BusOperLogVo;
import org.dromara.payment.common.mapper.BusOperLogMapper;
import org.dromara.payment.merchant.domain.BusMerchant;
import org.dromara.payment.merchant.domain.BusMerchantConfig;
import org.dromara.payment.merchant.domain.bo.BusMerchantBo;
import org.dromara.payment.merchant.domain.vo.BusOperAndAgentAndMer;
import org.dromara.payment.merchant.mapper.BusMerchantConfigMapper;
import org.dromara.payment.merchant.mapper.BusMerchantMapper;
import org.dromara.payment.sys.domain.SysSyd;
import org.dromara.payment.sys.domain.vo.SysSydVo;
import org.dromara.payment.sys.mapper.SysSydMapper;
import org.dromara.payment.task.domain.MerTaskDetail;
import org.dromara.payment.task.domain.MerTaskEnroll;
import org.dromara.payment.task.domain.vo.MerTaskEnrollVo;
import org.dromara.payment.task.mapper.MerTaskEnrollMapper;
import org.dromara.payment.thirdPlatform.base.domain.SysThirdPlatform;
import org.dromara.payment.thirdPlatform.base.mapper.SysThirdPlatformMapper;
import org.dromara.payment.thirdPlatform.xinyujian.service.IXyjService;
import org.dromara.system.api.model.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.dromara.payment.task.domain.bo.MerTaskBo;
import org.dromara.payment.task.domain.vo.MerTaskVo;
import org.dromara.payment.task.domain.MerTask;
import org.dromara.payment.task.mapper.MerTaskMapper;
import org.dromara.payment.task.service.IMerTaskService;

import javax.annotation.Resource;
import java.security.SecureRandom;
import java.util.*;

/**
 * 项目Service业务层处理
 *
 * @author LionLi
 * @date 2024-04-08
 */
@RequiredArgsConstructor
@Service
public class MerTaskServiceImpl  extends BaseService implements IMerTaskService {

    @Resource
    private final MerTaskMapper baseMapper;

    @Resource
    private final MerTaskEnrollMapper merTaskEnrollMapper;

    @Resource
    private final BusOperLogMapper  busOperLogMapper;

    @Resource
    private final SysSydMapper sysSydMapper;


    @Resource
    private final BusMerchantMapper busMerchantMapper;


    @Resource
    private final BusMerchantConfigMapper merchantConfigMapperConfig;

    @Resource
    private final IXyjService xyjService;

    @Resource
    private final SysThirdPlatformMapper sysThirdPlatformMapper;

    /**
     * 查询项目
     */
    @Override
    public MerTaskDetail queryById(Long id, PageQuery pageQuery){
        MerTaskDetail detail = new MerTaskDetail();
        detail.setMerTask(baseMapper.selectMerTaskById(id));

        LambdaQueryWrapper<BusOperLog> lqw = Wrappers.lambdaQuery();
        lqw.eq(BusOperLog::getBusId, id);
        lqw.eq(BusOperLog::getBusType, 1);
        lqw.orderBy(true, true, BusOperLog::getCreateTime);
        detail.setLogRecords(busOperLogMapper.selectVoList( lqw));

        detail.setEnrolls(merTaskEnrollMapper.selectPageList(pageQuery.build(),Wrappers.query(MerTaskEnroll.class).eq("mer_task_enroll.task_id", id)));
        return detail;
    }

    /**
     * 查询项目列表
     */
    @Override
    public TableDataInfo<MerTaskVo> queryPageList(MerTaskBo bo, PageQuery pageQuery) {
        //数据权限控制
        valQueryContion(bo);
        //判断角色
        QueryWrapper<MerTask> lqw = buildQueryWrapper2(bo);

        Page<MerTaskVo> result = baseMapper.selectPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 判断角色查询条件 拒绝全部数据输出
     */
    private void valQueryContion(MerTaskBo bo) {
        Integer busRole = LoginHelper.getBusRole();
        if(busRole == BusRole.MERCHANT.getId() ){
            bo.setMerId(LoginHelper.getBusId());
            if(null == bo.getSydId() ){
                throw new IllegalArgumentException("请选择服务商");
            }
        }else if(busRole == BusRole.OPERATOR.getId() ){
            bo.setOpId(LoginHelper.getBusId());
        }else if(busRole == BusRole.AGENT.getId() ){
            bo.setChannelNo(LoginHelper.getNo());
//            bo.setChannelId(LoginHelper.getBusId());
        }else if(busRole == BusRole.SERVICE.getId() ){
            bo.setSydId(LoginHelper.getBusId());
        }else if(busRole == BusRole.PLATFORM.getId() ){


        }
    }

    /**
     * 查询审核数据
     */
    @Override
    public TableDataInfo<MerTaskVo> queryCheckList(MerTaskBo bo, PageQuery pageQuery) {
        //判断角色
        Integer busRole = LoginHelper.getBusRole();

        //数据权限控制
        String phone = "";
        if(busRole == BusRole.OPERATOR.getId() ){
            bo.setOpId(LoginHelper.getBusId());
            bo.setTaskStatus(1);
        }else if(busRole == BusRole.SERVICE.getId() ){
            bo.setSydId(LoginHelper.getBusId());
        }else if(busRole == BusRole.PLATFORM.getId() ){
            //查询所有数据
        }else if(busRole == BusRole.MERCHANT.getId()){
            bo.setMerId(LoginHelper.getBusId());
        }else{
            throw new IllegalArgumentException("当前账号没有权限，请联系管理员");
        }


        QueryWrapper<MerTask> lqw = buildQueryWrapper2(bo);

        Page<MerTaskVo> result = baseMapper.selectPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询项目列表
     */
    @Override
    public List<MerTaskVo> queryList(MerTaskBo bo) {
        //判断角色
        valQueryContion(bo);
        LambdaQueryWrapper<MerTask> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private QueryWrapper<MerTask> buildQueryWrapper2(MerTaskBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<MerTask> lqw = Wrappers.query();

        lqw.eq(bo.getId() != null, "mer_task.id", bo.getId());
        lqw.eq(bo.getClassify() != null, "mer_task.classify", bo.getClassify());
        lqw.eq(StringUtils.isNotBlank(bo.getNo()), "mer_task.no", bo.getNo());
        lqw.like(StringUtils.isNotBlank(bo.getName()), "mer_task.name", bo.getName());
        lqw.eq(bo.getCost() != null, "mer_task.cost", bo.getCost());
        lqw.eq(bo.getCostMax() != null, "mer_task.cost_max", bo.getCostMax());
        lqw.eq(StringUtils.isNotBlank(bo.getIndustry()), "mer_task.industry", bo.getIndustry());
        lqw.eq(bo.getLimitNum() != null, "mer_task.limit_num", bo.getLimitNum());
        lqw.eq(bo.getStatus() != null, "mer_task.Status", bo.getStatus());
        lqw.eq(bo.getPublicTime() != null, "mer_task.public_time", bo.getPublicTime());
        lqw.eq(bo.getTaskStatus() != null, "mer_task.task_status", bo.getTaskStatus());
        lqw.eq(bo.getSubmitTime() != null, "mer_task.submit_time", bo.getSubmitTime());
        lqw.eq(bo.getOpVerifyStatus() != null, "mer_task.op_verify_status", bo.getOpVerifyStatus());
        lqw.eq(bo.getOpVerifyTime() != null, "mer_task.op_verify_time", bo.getOpVerifyTime());
        lqw.eq(StringUtils.isNotBlank(bo.getOpVerifyBy()), "mer_task.op_verify_by", bo.getOpVerifyBy());
        lqw.eq(bo.getEditTime() != null, "mer_task.edit_time", bo.getEditTime());
        lqw.eq(bo.getFrozenAmount() != null, "mer_task.frozen_amount", bo.getFrozenAmount());
        lqw.eq(bo.getRelAmount() != null, "mer_task.rel_amount", bo.getRelAmount());
        lqw.eq(bo.getRelAmountTime() != null, "mer_task.rel_amount_time", bo.getRelAmountTime());
        lqw.eq(bo.getInvoiceAmount() != null, "mer_task.invoice_amount", bo.getInvoiceAmount());
        lqw.eq(bo.getIsOut() != null, "mer_task.is_out", bo.getIsOut());
        lqw.eq(bo.getSydId() != null, "mer_task.syd_id", bo.getSydId());
        lqw.eq(StringUtils.isNotBlank(bo.getSydNo()), "mer_task.syd_no", bo.getSydNo());
        lqw.eq(bo.getBusType() != null, "mer_task.bus_type", bo.getBusType());
        lqw.eq(StringUtils.isNotBlank(bo.getOpNo()), "mer_task.op_no", bo.getOpNo());
        lqw.eq(bo.getOpId() != null, "mer_task.op_id", bo.getOpId());
        lqw.eq(bo.getChannelId() != null, "mer_task.channel_id", bo.getChannelId());
        lqw.likeRight(StringUtils.isNotBlank(bo.getChannelNo()), "mer_task.channel_no", bo.getChannelNo());
        lqw.eq(StringUtils.isNotBlank(bo.getChannelCode()), "mer_task.channel_code", bo.getChannelCode());
        lqw.eq(bo.getMerId() != null, "mer_task.mer_id", bo.getMerId());
        lqw.eq(StringUtils.isNotBlank(bo.getMerNo()), "mer_task.mer_no", bo.getMerNo());
        lqw.eq(bo.getSydVerifyStatus() != null, "mer_task.syd_verify_status", bo.getSydVerifyStatus());
        lqw.eq(bo.getSydVerifyTime() != null, "mer_task.syd_verify_time", bo.getSydVerifyTime());
        lqw.eq(StringUtils.isNotBlank(bo.getSydVerifyBy()), "mer_task.syd_verify_by", bo.getSydVerifyBy());
        lqw.eq(StringUtils.isNotBlank(bo.getSydVerifyReason()), "mer_task.syd_verify_reason", bo.getSydVerifyReason());
        lqw.like(StringUtils.isNotEmpty(bo.getMerName()),"bus_merchant.name",bo.getMerName());
        lqw.between(bo.getBeginDate() != null, "mer_task.add_time", bo.getBeginDate(), bo.getEndDate());
        lqw.in(bo.getTaskStatusList() != null && bo.getTaskStatusList().size() > 0, "mer_task.task_status" ,bo.getTaskStatusList());
        return lqw;
    }

    private LambdaQueryWrapper<MerTask> buildQueryWrapper(MerTaskBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MerTask> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getClassify() != null, MerTask::getClassify, bo.getClassify());
        lqw.eq(StringUtils.isNotBlank(bo.getNo()), MerTask::getNo, bo.getNo());
        lqw.like(StringUtils.isNotBlank(bo.getName()), MerTask::getName, bo.getName());
        lqw.eq(bo.getCost() != null, MerTask::getCost, bo.getCost());
        lqw.eq(bo.getCostMax() != null, MerTask::getCostMax, bo.getCostMax());
        lqw.eq(StringUtils.isNotBlank(bo.getIndustry()), MerTask::getIndustry, bo.getIndustry());
        lqw.eq(bo.getLimitNum() != null, MerTask::getLimitNum, bo.getLimitNum());
        lqw.eq(bo.getCostUnit() != null, MerTask::getCostUnit, bo.getCostUnit());
        lqw.eq(bo.getBeginDate() != null, MerTask::getBeginDate, bo.getBeginDate());
        lqw.eq(bo.getEndDate() != null, MerTask::getEndDate, bo.getEndDate());
        lqw.eq(bo.getStatus() != null, MerTask::getStatus, bo.getStatus());
        lqw.eq(bo.getPublicTime() != null, MerTask::getPublicTime, bo.getPublicTime());
        lqw.eq(bo.getIsOffline() != null, MerTask::getIsOffline, bo.getIsOffline());
        lqw.eq(bo.getTaskStatus() != null, MerTask::getTaskStatus, bo.getTaskStatus());
        lqw.eq(bo.getSubmitTime() != null, MerTask::getSubmitTime, bo.getSubmitTime());
        lqw.eq(bo.getOpVerifyStatus() != null, MerTask::getOpVerifyStatus, bo.getOpVerifyStatus());
        lqw.eq(bo.getOpVerifyTime() != null, MerTask::getOpVerifyTime, bo.getOpVerifyTime());
        lqw.eq(StringUtils.isNotBlank(bo.getOpVerifyBy()), MerTask::getOpVerifyBy, bo.getOpVerifyBy());
        lqw.eq(StringUtils.isNotBlank(bo.getOpVerifyReason()), MerTask::getOpVerifyReason, bo.getOpVerifyReason());
        lqw.eq(bo.getAddTime() != null, MerTask::getAddTime, bo.getAddTime());
        lqw.eq(StringUtils.isNotBlank(bo.getAddBy()), MerTask::getAddBy, bo.getAddBy());
        lqw.eq(StringUtils.isNotBlank(bo.getEditer()), MerTask::getEditer, bo.getEditer());
        lqw.eq(bo.getEditTime() != null, MerTask::getEditTime, bo.getEditTime());
        lqw.eq(bo.getFrozenAmount() != null, MerTask::getFrozenAmount, bo.getFrozenAmount());
        lqw.eq(bo.getRelAmount() != null, MerTask::getRelAmount, bo.getRelAmount());
        lqw.eq(bo.getRelAmountTime() != null, MerTask::getRelAmountTime, bo.getRelAmountTime());
        lqw.eq(bo.getInvoiceAmount() != null, MerTask::getInvoiceAmount, bo.getInvoiceAmount());
        lqw.eq(bo.getIsOut() != null, MerTask::getIsOut, bo.getIsOut());
        lqw.eq(bo.getSydId() != null, MerTask::getSydId, bo.getSydId());
        lqw.eq(StringUtils.isNotBlank(bo.getSydNo()), MerTask::getSydNo, bo.getSydNo());
        lqw.eq(bo.getBusType() != null, MerTask::getBusType, bo.getBusType());
        lqw.eq(StringUtils.isNotBlank(bo.getOpNo()), MerTask::getOpNo, bo.getOpNo());
        lqw.eq(bo.getOpId() != null, MerTask::getOpId, bo.getOpId());
        lqw.eq(bo.getChannelId() != null, MerTask::getChannelId, bo.getChannelId());
        lqw.eq(StringUtils.isNotBlank(bo.getChannelNo()), MerTask::getChannelNo, bo.getChannelNo());
        lqw.eq(StringUtils.isNotBlank(bo.getChannelCode()), MerTask::getChannelCode, bo.getChannelCode());
        lqw.eq(bo.getMerId() != null, MerTask::getMerId, bo.getMerId());
        lqw.eq(StringUtils.isNotBlank(bo.getMerNo()), MerTask::getMerNo, bo.getMerNo());
        lqw.eq(bo.getSydVerifyStatus() != null, MerTask::getSydVerifyStatus, bo.getSydVerifyStatus());
        lqw.eq(bo.getSydVerifyTime() != null, MerTask::getSydVerifyTime, bo.getSydVerifyTime());
        lqw.eq(StringUtils.isNotBlank(bo.getSydVerifyBy()), MerTask::getSydVerifyBy, bo.getSydVerifyBy());
        lqw.eq(StringUtils.isNotBlank(bo.getSydVerifyReason()), MerTask::getSydVerifyReason, bo.getSydVerifyReason());
        lqw.in(bo.getTaskStatusList() != null && bo.getTaskStatusList().size() > 0, MerTask::getTaskStatus,bo.getTaskStatusList());
        return lqw;
    }

    /**
     * 新增项目
     */
    @Override
    public Boolean insertByBo(MerTaskBo bo) {
        MerTask add = MapstructUtils.convert(bo, MerTask.class);
        Integer busRole = LoginHelper.getBusRole();
        if(busRole == BusRole.MERCHANT.getId() ){
            bo.setMerId(LoginHelper.getBusId());
            if(null == bo.getSydId() ){
                throw new IllegalArgumentException("请选择服务商");
            }

           SysSydVo sydVo =  this.sysSydMapper.selectVoById(bo.getSydId());
            if(sydVo == null){
                this.invalidationParamsException("无效服务商!");
            }
            if(!(sydVo.getStatus() != null && sydVo.getStatus().intValue() == 1)){
                this.invalidationParamsException("服务商停止接单");
            }

        }else{
            throw new IllegalArgumentException("只有企业角色才能发布项目");
        }
        validEntityBeforeSave(add);
        add.setNo("S" + getNo()); //mer
        add.setAddBy(LoginHelper.getUsername());
        add.setAddTime(new Date());
        add.setCreateTime(add.getAddTime());

        BusMerchantBo mer = new BusMerchantBo();
        mer.setNo(LoginHelper.getNo());
        BusOperAndAgentAndMer busOperAndAgentAndMer = this.busMerchantMapper.selOpAndAgentInfosByMerInfo(mer);

        add.setOpId(busOperAndAgentAndMer.getOpId());
        add.setOpNo(busOperAndAgentAndMer.getOpNo());
        add.setSydId(bo.getSydId());
        add.setSydNo(bo.getSydNo());
        add.setChannelId(busOperAndAgentAndMer.getChannelId());
        add.setChannelNo(busOperAndAgentAndMer.getChannelNo());
        add.setChannelCode(busOperAndAgentAndMer.getChannelCode());
        add.setMerNo(LoginHelper.getNo());
        add.setStatus(1); //保存的话 是不会上架

        if(0 == add.getTaskStatus()){
            add.setOpVerifyStatus(0);
            add.setSydVerifyStatus(0);
        }


        BusOperLog merLog = new BusOperLog();
        BusOperLog opLog = new BusOperLog();
        BusOperLog sydLog = new BusOperLog();
        //自动审核
        BusMerchantConfig merchantConfig = merchantConfigMapperConfig.selectByMerId(bo.getMerId());

        // 项目状态 0 待发布 1 保存并发布
        if(1 == add.getTaskStatus()){
            add.setPublicTime(new Date());

            add.setTaskStatus(1);
            add.setOpVerifyStatus(1);//发布完  可以 运营商审核
            //判断是否自动审核
            merLog = new BusOperLog("发布上线", BusRole.MERCHANT, add.getId(), 1);

            if(1 == merchantConfig.getAutoApprove()){
                add.setSubmitTime(new Date());

                //插入 运营商日志 服务商日志
                opLog = new BusOperLog("运营商审核成功", BusRole.OPERATOR, add.getId(), 1);
                add.setTaskStatus(2);
                add.setOpVerifyStatus(3);
                add.setOpVerifyTime(new Date());
                add.setOpVerifyBy(busOperAndAgentAndMer.getOpId() + "");
                add.setOpVerifyReason("自动审核通过");

                add.setStatus(1);
                //抢单需要 人员抢单
                if(add.getClassify().intValue() == 2){
                    sydLog = new BusOperLog("项目发布", BusRole.SERVICE, add.getId(), 1);
                    add.setTaskStatus(6);
                    add.setSydVerifyStatus(3);
                    add.setSydVerifyReason("自动审核通过");
                }

                //派单  服务商审核完 直接开始
                if(add.getClassify().intValue() == 1){
                    sydLog = new BusOperLog("项目开始", BusRole.SERVICE, add.getId(), 1);
                    add.setTaskStatus(7);
                    add.setSydVerifyStatus(3);
                    add.setBeginDate(new Date());
                    add.setSydVerifyReason("自动审核通过");
                }
            }
        }
        boolean flag;


        SysSyd sysSyd = sysSydMapper.selectSysSydById(add.getSydId());


        SysThirdPlatform sysThirdPlatform = sysThirdPlatformMapper.selectThirdAppInfo(sysSyd.getId());


        if(Objects.nonNull(sysThirdPlatform) && sysThirdPlatform.getPlatformName().equals("薪遇见")){
            BusMerchant merchant = busMerchantMapper.selectById(bo.getMerId());
            flag = xyjService.createProjectTask(add, merchant);
        }else{
            flag = baseMapper.insert(add) > 0;
        }

        if (flag) {
            if(1 == add.getTaskStatus()){
                merLog.setBusId(add.getId());
                busOperLogMapper.insert(merLog);
                if(1 == merchantConfig.getAutoApprove()){
                    opLog.setBusId(add.getId());
                    busOperLogMapper.insert(opLog);
                    sydLog.setBusId(add.getId());
                    busOperLogMapper.insert(sydLog);
                }
            }
        }

        return flag;
    }

    private int insertTask(MerTask addTask){
        try{
            return baseMapper.insert(addTask);
        }catch(Exception e){
            if( e instanceof DuplicateKeyException){
                addTask.setNo("S" + getNo());
                return this.baseMapper.insert(addTask);
            }
            throw e;
        }
    }

    /**
     * 发布上线
     */
    @Override
    public Boolean updateByBo(MerTaskBo bo) {
        MerTask entity = MapstructUtils.convert(bo, MerTask.class);
        validEntityBeforeSave(entity);

        if(null == entity.getId()){
            throw new IllegalArgumentException("项目ID不能为空");
        }

        Integer busRole = LoginHelper.getBusRole();
        if(busRole != BusRole.MERCHANT.getId() ){
            throw new IllegalArgumentException("只有企业角色才能发布项目");
        }

        BusMerchantBo mer = new BusMerchantBo();
        mer.setNo(LoginHelper.getNo());
        BusOperAndAgentAndMer busOperAndAgentAndMer = this.busMerchantMapper.selOpAndAgentInfosByMerInfo(mer);

        BusOperLog merLog = new BusOperLog();
        BusOperLog opLog = new BusOperLog();
        BusOperLog sydLog = new BusOperLog();

        if(1 == entity.getTaskStatus()){
            entity.setOpVerifyStatus(0);
            entity.setSydVerifyStatus(0);
        }

        // 项目状态 0 待发布 1 保存并发布
        if(1 == entity.getTaskStatus()){
            entity.setPublicTime(new Date());

            entity.setTaskStatus(1);
            //判断是否自动审核
            merLog = new BusOperLog("发布上线", BusRole.MERCHANT, entity.getId(), 1);
            busOperLogMapper.insert(merLog);

            //自动审核
            BusMerchantConfig merchantConfig = merchantConfigMapperConfig.selectByMerId(bo.getMerId());
            if(1 == merchantConfig.getAutoApprove()){
                entity.setSubmitTime(new Date());

                //插入 运营商日志 服务商日志
                opLog = new BusOperLog("运营商审核成功", BusRole.OPERATOR, entity.getId(), 1);
                busOperLogMapper.insert(opLog);

                entity.setTaskStatus(2);
                entity.setOpVerifyStatus(3);
                entity.setOpVerifyTime(new Date());
                entity.setOpVerifyBy(busOperAndAgentAndMer.getOpId() + "");
                entity.setOpVerifyReason("自动审核通过");

                entity.setStatus(1);
                //抢单需要 人员抢单
                if(entity.getClassify().intValue() == 2){
                    sydLog = new BusOperLog("项目发布", BusRole.SERVICE, entity.getId(), 1);
                    entity.setTaskStatus(6);
                    entity.setSydVerifyReason("自动审核通过");
                }

                //派单  服务商审核完 直接开始
                if(entity.getClassify().intValue() == 1){
                    sydLog = new BusOperLog("项目开始", BusRole.SERVICE, entity.getId(), 1);
                    entity.setTaskStatus(7);
                    entity.setBeginDate(new Date());
                    entity.setSydVerifyReason("自动审核通过");
                }
                busOperLogMapper.insert(sydLog);
            }
        }
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public Boolean updateInfoByBo(MerTaskBo bo) {
        MerTask entity = MapstructUtils.convert(bo, MerTask.class);
        validEntityBeforeSave(entity);

        if(null == entity.getId()){
            throw new IllegalArgumentException("项目ID不能为空");
        }

        return baseMapper.updateById(entity) > 0;
    }


    @Override
    public Boolean checkInfoByBo(MerTaskBo bo) {
        MerTask entity = MapstructUtils.convert(bo, MerTask.class);
//        validEntityBeforeSave(entity);

        if(null == entity.getId()){
            throw new IllegalArgumentException("项目ID不能为空");
        }

        Integer busRole = LoginHelper.getBusRole();
        if(busRole != BusRole.SERVICE.getId()
            && busRole != BusRole.OPERATOR.getId() ){
            throw new IllegalArgumentException("当前用户没有审核项目权限，请联系管理员");
        }

        if(busRole == BusRole.OPERATOR.getId()) {
            entity.setOpVerifyTime(new Date());
            entity.setOpVerifyBy(LoginHelper.getUsername() + "");

            BusOperLog opLog = new BusOperLog("", BusRole.OPERATOR, entity.getId(), 1);
            //通过
            if(3 == entity.getOpVerifyStatus()){
                entity.setTaskStatus(2);
                opLog.setLogDesc("运营商审核通过");
                entity.setSydVerifyStatus(1);// 运营商神完成 待服务商审核
            }else{
                //驳回
                entity.setTaskStatus(3);
                opLog.setLogDesc("运营商审核拒绝");
            }
            busOperLogMapper.insert(opLog);
        }

        if(busRole == BusRole.SERVICE.getId()) {
            BusOperLog sydLog = new BusOperLog("", BusRole.SERVICE, entity.getId(), 1);
            entity.setOpVerifyTime(new Date());
            entity.setOpVerifyBy(LoginHelper.getUsername() + "");
            //通过
            if(3 == entity.getSydVerifyStatus()){
                entity.setTaskStatus(4);

                if(2 == entity.getClassify()){
                    sydLog.setLogDesc("项目发布");
                    entity.setTaskStatus(6);
                }
                //派单  服务商审核完 直接开始
                if(entity.getClassify().intValue() == 1){
                    sydLog.setLogDesc("项目开始");
                    entity.setTaskStatus(7);
                }
            }else{
                //驳回
                entity.setTaskStatus(5);
                sydLog.setLogDesc("服务商拒绝转包");
            }
            busOperLogMapper.insert(sydLog);
        }

        return baseMapper.updateById(entity) > 0;
    }



    @Override
    public Boolean rejectCommitByBo(MerTaskBo bo) {
        MerTask entity = MapstructUtils.convert(bo, MerTask.class);
//        validEntityBeforeSave(entity);

        if(null == entity.getId()){
            throw new IllegalArgumentException("项目ID不能为空");
        }

        Integer busRole = LoginHelper.getBusRole();
        if(busRole != BusRole.MERCHANT.getId()){
            throw new IllegalArgumentException("当前用户没有该操作权限，请联系管理员");
        }

        if(2 == entity.getOpVerifyStatus()) {
            BusOperLog opLog = new BusOperLog("", BusRole.MERCHANT, entity.getId(), 1);
            entity.setOpVerifyStatus(1);
            opLog.setLogDesc("提交运营商审核");
            busOperLogMapper.insert(opLog);
        }
        if(2 == entity.getSydVerifyStatus()) {
            BusOperLog opLog = new BusOperLog("", BusRole.MERCHANT, entity.getId(), 1);
            entity.setSydVerifyStatus(1);
            opLog.setLogDesc("提交服务商审核");
            busOperLogMapper.insert(opLog);
        }
        return baseMapper.updateById(entity) > 0;
    }

    public Boolean updateStateByBo(MerTaskBo bo) {
        MerTask entity = MapstructUtils.convert(bo, MerTask.class);
        if (null == entity.getId()) {
            throw new IllegalArgumentException("项目ID不能为空");
        }
        if (null == entity.getMerId()) {
            throw new IllegalArgumentException("企业ID不能为空");
        }
        if (null == entity.getStatus()) {
            throw new IllegalArgumentException("上架状态不能为空");
        }
        Integer busRole = LoginHelper.getBusRole();
        if(busRole != BusRole.MERCHANT.getId() ){
            throw new IllegalArgumentException("只有企业角色才能上架下架项目");
        }

        if(!entity.getMerId().equals(LoginHelper.getBusId() )){
            throw new IllegalArgumentException("只能操作自己企业的数据");
        }

        BusOperLog merLog = new BusOperLog("", BusRole.MERCHANT, entity.getId(), 1);
        if(1 == bo.getStatus()){
            merLog.setLogDesc("项目下架");
        }else if(2 == bo.getStatus()){
            merLog.setLogDesc("项目上架");
        }
        busOperLogMapper.insert(merLog);

        return baseMapper.updateById(entity) > 0;
    }
    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MerTask entity){
        if(null == entity.getBusType()){
            throw new IllegalArgumentException("请选择业务类型");
        }
        if(StringUtils.isEmpty(entity.getName())){
            throw new IllegalArgumentException("请填写项目名称");
        }
        if(StringUtils.isEmpty(entity.getIndustry())){
            throw new IllegalArgumentException("请选择所属行业");
        }
        if(StringUtils.isEmpty(entity.getIndustryName())){
            throw new IllegalArgumentException("请选择所属行业");
        }
        if(null == entity.getClassify()){
            throw new IllegalArgumentException("请选择项目类型");
        }

        if(null == entity.getSydId()){
            throw new IllegalArgumentException("请选择服务商");
        }

        if(StringUtils.isEmpty(entity.getSydNo())){
            throw new IllegalArgumentException("请选择服务商");
        }

        //派单类型 1:派单、2:抢单
        if(entity.getClassify().intValue() == 1){
            if(null == entity.getCost()){
                throw new IllegalArgumentException("请填写最小项目总金额(分)");
            }
            if(null == entity.getCostMax()){
                throw new IllegalArgumentException("请填写最大项目总金额(分)");
            }

        }
        if(entity.getClassify().intValue() == 2){
            if(null == entity.getCost()){
                throw new IllegalArgumentException("请填写项目总金额(分)");
            }

            if(null == entity.getLimitNum()){
                throw new IllegalArgumentException("请填写用工人数");
            }
            if(null == entity.getJiezhiDate()){
                throw new IllegalArgumentException("请选择报名截至日期");
            }
        }


        if(null == entity.getProContent()){
            throw new IllegalArgumentException("请填写项目内容");
        }

    }

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

    private String getNo(){
        // 创建SecureRandom对象，更安全的随机数生成器
        SecureRandom secureRandom = new SecureRandom();

        // 生成16位的随机数字，范围是0到9999999999999999L  130652799162
        long randomNumber = secureRandom.nextLong(1000000000000L);

        // 打印随机数，确保是16位，不足前面补0
        String formattedNumber = String.format("%012d", randomNumber);
        System.out.println("随机12位数字: " + formattedNumber);
        return formattedNumber;
    }

}
