package com.sqx.modules.material.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.Result;
import com.sqx.modules.artificer.dao.ArtificerDao;
import com.sqx.modules.artificer.dao.MassageTypeDao;
import com.sqx.modules.artificer.entity.Artificer;
import com.sqx.modules.artificer.entity.MassageType;
import com.sqx.modules.material.dao.MaterialArtificerMapper;
import com.sqx.modules.material.dao.MaterialMapper;
import com.sqx.modules.material.dao.MaterialMassageMapper;
import com.sqx.modules.material.entity.Material;
import com.sqx.modules.material.entity.MaterialArtificer;
import com.sqx.modules.material.entity.MaterialMassage;
import com.sqx.modules.material.entity.MaterialRecord;
import com.sqx.modules.material.service.MaterialArtificerService;
import com.sqx.modules.material.service.MaterialRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
* @author Administrator
* @description 针对表【material_artificer(物料包与技师中间表)】的数据库操作Service实现
* @createDate 2024-02-27 15:30:46
*/
@Service
public class MaterialArtificerServiceImpl extends ServiceImpl<MaterialArtificerMapper, MaterialArtificer> implements MaterialArtificerService {
    @Autowired
    private MaterialRecordService materialRecordService;
    @Autowired
    private MaterialMapper materialMapper;
    @Autowired
    private MaterialMassageMapper materialMassageMapper;
    @Autowired
    private MassageTypeDao massageTypeDao;
    @Autowired
    private ArtificerDao artificerDao;
    @Override
    public Result insertMaterialArtificer(MaterialArtificer materialArtificer) {
        materialArtificer.setCreateTime(new Date());
        materialArtificer.setUpdateTime(new Date());
        QueryWrapper<MaterialArtificer> queryWrapper = new QueryWrapper();
        queryWrapper.eq("material_id", materialArtificer.getMaterialId());
        queryWrapper.eq("artificer_id", materialArtificer.getArtificerId());
        List<MaterialArtificer> materialArtificerList = baseMapper.selectList(queryWrapper);
        if(materialArtificerList.size()>0){
            return Result.error("该物料包已被添加，请重新选择");
        }
        int result = baseMapper.insert(materialArtificer);
        return Result.success(String.valueOf(result));
    }

    @Override
    public Result materialArtificerDelete(MaterialArtificer materialArtificer) {
        MaterialArtificer materialArtificer1  = baseMapper.selectById(materialArtificer.getId());
        if(materialArtificer1 == null){
            return Result.error("该技师物料包不存在，请重新选择");
        }
        if(materialArtificer1.getResidue().compareTo(BigDecimal.ZERO) == 1){
            return Result.error("该技师物料包未消耗空，请勿删除");
        }
        int result = baseMapper.deleteById(materialArtificer.getId());
        return  Result.success(result == 1 ?"删除成功":"删除失败");
    }

    @Override
    public Result materialArtificerUpdata(MaterialArtificer materialArtificer) {
        MaterialArtificer materialArtificerData = baseMapper.selectById(materialArtificer.getId());
        materialArtificer.setUpdateTime(new Date());
        //如果类型为1则执行添加剩余数量 否则执行减少剩余数量
        if(materialArtificer.getType().equals(1)){
            materialArtificer.setResidue(materialArtificerData.getResidue().add(materialArtificer.getBalance()));
        }else {
            materialArtificer.setResidue(materialArtificerData.getResidue().subtract(materialArtificer.getBalance()));
        }
        int result = baseMapper.updateById(materialArtificer);
        if(!materialArtificer.getBalance().equals(0)){
            //修改过剩余量，执行新增历史记录
            MaterialRecord materialRecord = new MaterialRecord();
            materialRecord.setMaterialId(materialArtificerData.getMaterialId());
            materialRecord.setType(materialArtificer.getType());
            materialRecord.setTotal(materialArtificer.getResidue());
            materialRecord.setNumber(materialArtificer.getBalance());
            materialRecord.setUpdateTime(new Date());
            materialRecord.setCreateTime(new Date());
            materialRecord.setCreateUser(materialArtificer.getUpdateUser());
            materialRecord.setArtificerId(materialArtificerData.getArtificerId());
            materialRecord.setUpdateUser(materialArtificer.getUpdateUser());
            materialRecord.setRecordDescribe(DateUtil.date()+"管理员:"+materialArtificer.getUpdateUser()+(materialArtificer.getType().equals(1)?"新增剩余数量：":"减少剩余数量：")+materialArtificer.getBalance()+"总和："+materialArtificer.getResidue());
            materialRecordService.addMaterialRecord(materialRecord);
        }
        return Result.success(result == 1 ?"修改成功":"修改失败");
    }

    @Override
    public String accomplishOrders(Long messageTypeId, Long artificerId) {
        QueryWrapper<MaterialMassage> materialMassageQueryWrapper = new QueryWrapper();
        QueryWrapper<MaterialArtificer> materialArtificerQueryWrapper = new QueryWrapper();
        QueryWrapper<MassageType> massageTypeQueryWrapper = new QueryWrapper();
        //查询所有含有messageTypeId或者parent_id的数据
        massageTypeQueryWrapper.eq("massage_type_id",messageTypeId).or().eq("parent_id",messageTypeId);
        List<MassageType> massageTypeList = massageTypeDao.selectList(massageTypeQueryWrapper);
        //查询id为messageTypeId或者parent_id为messageTypeId
        materialMassageQueryWrapper.in("massage_type_id",massageTypeList.stream().map(MassageType::getMassageTypeId).toArray());
        List<MaterialMassage> materialMassageList = materialMassageMapper.selectList(materialMassageQueryWrapper);
        materialMassageQueryWrapper.eq("artificer_id",artificerId);
        List<MaterialArtificer> materialArtificers = baseMapper.selectList(materialArtificerQueryWrapper);
        //循环列表消耗物料包
        for (int i = 0; i < materialMassageList.size(); i++){
            for (int j = 0; j < materialArtificers.size(); j++){
                if(materialMassageList.get(i).getMaterialId().equals(materialArtificers.get(j).getMaterialId())){
                    materialArtificers.get(j).setResidue(materialArtificers.get(j).getResidue().subtract(materialMassageList.get(i).getConsume()));
                    baseMapper.updateById(materialArtificers.get(j));
                    //修改剩余量，执行新增历史记录
                    MaterialRecord materialRecord = new MaterialRecord();
                    materialRecord.setMaterialId(materialMassageList.get(i).getMaterialId());
                    materialRecord.setType(2);
                    materialRecord.setTotal(materialArtificers.get(i).getResidue());
                    materialRecord.setNumber(materialMassageList.get(i).getConsume());
                    materialRecord.setUpdateTime(new Date());
                    materialRecord.setCreateTime(new Date());
                    materialRecord.setCreateUser(Long.valueOf(materialArtificers.get(i).getArtificerId()));
                    materialRecord.setArtificerId(materialArtificers.get(i).getArtificerId());
                    materialRecord.setUpdateUser(Long.valueOf(materialArtificers.get(i).getArtificerId()));
                    materialRecord.setRecordDescribe(DateUtil.date()+(materialRecord.getType().equals(1)?"新增剩余数量：":"减少剩余数量：")+materialMassageList.get(i).getConsume()+"总和："+materialRecord.getTotal());
                    materialRecordService.addMaterialRecord(materialRecord);
                }
            }
        }
        return null;
    }

    @Override
    public void changePay(Long id, Long userId, Integer number) {
        //查询技师id
       Artificer artificer =  artificerDao.selectOne(new QueryWrapper<Artificer>().eq("user_id",userId));
       //查询物料包id
       Material material =  materialMapper.selectOne(new QueryWrapper<Material>().eq("goods_id",id));
       if(ObjectUtil.isEmpty(material)){
           return;
       }
       //根据物料包id和技师id查询技师对应物料包
       MaterialArtificer materialArtificer = baseMapper.selectOne(new QueryWrapper<MaterialArtificer>().eq("artificer_id",artificer.getArtificerId()).eq("material_id",material.getId()));
      //修改物料包数量
       materialArtificer.setResidue(materialArtificer.getResidue().add(new BigDecimal(number)));
       baseMapper.updateById(materialArtificer);
        //修改剩余量，执行新增历史记录
        MaterialRecord materialRecord = new MaterialRecord();
        materialRecord.setMaterialId(materialArtificer.getMaterialId());
        materialRecord.setType(1);
        materialRecord.setTotal(materialArtificer.getResidue());
        materialRecord.setNumber(BigDecimal.valueOf(number));
        materialRecord.setUpdateTime(new Date());
        materialRecord.setCreateTime(new Date());
        materialRecord.setCreateUser(Long.valueOf(materialArtificer.getArtificerId()));
        materialRecord.setArtificerId(materialArtificer.getArtificerId());
        materialRecord.setUpdateUser(Long.valueOf(materialArtificer.getArtificerId()));
        materialRecord.setRecordDescribe(DateUtil.date()+"通过商城购买"+(materialRecord.getType().equals(1)?"新增剩余数量：":"减少剩余数量：")+materialArtificer.getResidue()+"总和："+materialRecord.getTotal());
        materialRecordService.addMaterialRecord(materialRecord);
    }
}




