package com.fjhx.mes.service.production.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.mes.entity.production.dto.ProductionReportingDetailDto;
import com.fjhx.mes.entity.production.dto.ProductionReportingDetailSelectDto;
import com.fjhx.mes.entity.production.po.ProductionReportingDetail;
import com.fjhx.mes.entity.production.vo.ProductionReportingDetailVo;
import com.fjhx.mes.mapper.production.ProductionReportingDetailMapper;
import com.fjhx.mes.service.production.ProductionReportingDetailService;
import com.fjhx.tenant.utils.DeptUstil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 生产报工明细 服务实现类
 * </p>
 *
 * @author
 * @since 2023-03-30
 */
@Service
public class ProductionReportingDetailServiceImpl extends ServiceImpl<ProductionReportingDetailMapper, ProductionReportingDetail> implements ProductionReportingDetailService {

    private final ISysUserService sysUserService;

    @Autowired
    public ProductionReportingDetailServiceImpl(ISysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    @Override
    public Page<ProductionReportingDetailVo> getPage(ProductionReportingDetailSelectDto dto) {
        IWrapper<ProductionReportingDetail> wrapper = getWrapper();
        wrapper.orderByDesc("prd", ProductionReportingDetail::getId);

        //权限过滤：生产报工-子公司看自己的,总公司看全部
        Long companyId = SecurityUtils.getCompanyId();
        if (!Objects.equals(companyId, 100L)) {
            wrapper.eq("prd", ProductionReportingDetail::getCompanyId, companyId);
        } else {
            wrapper.eq("prd", ProductionReportingDetail::getCompanyId, dto.getCompanyId());
        }

        //工序过滤
        wrapper.eq("prd", ProductionReportingDetail::getProductionProcessesId, dto.getProductionProcessesId());

        //关键字检索
        if (ObjectUtil.isNotEmpty(dto.getKeyword())) {
            List<SysUser> list = sysUserService.list(IWrapper.<SysUser>getWrapper().like(SysUser::getNickName, dto.getKeyword()));
            List<Long> uIds = list.stream().map(SysUser::getUserId).collect(Collectors.toList());
            wrapper.and(q -> q
                    .like("po.code", dto.getKeyword())
                    .or().in("prd.user_id", uIds)
            );
        }

        Page<ProductionReportingDetailVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        List<ProductionReportingDetailVo> records = page.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return page;
        }
        //赋值创建人名称
        UserUtil.assignmentNickName(records, ProductionReportingDetail::getCreateUser, ProductionReportingDetailVo::setCreateUserName);
        //赋值报工人名称
        UserUtil.assignmentNickName(records, ProductionReportingDetail::getUserId, ProductionReportingDetailVo::setUserName);

        //获取生产公司信息
        List<Long> companyIds = records.stream().map(ProductionReportingDetail::getCompanyId).collect(Collectors.toList());
        Map<Long, String> companyNameMap = DeptUstil.getDeptNameMap(companyIds);

        for (ProductionReportingDetailVo record : records) {
            //赋值生产公司名称
            record.setCompanyName(companyNameMap.get(record.getCompanyId()));
        }

        return page;
    }

    @Override
    public ProductionReportingDetailVo detail(Long id) {
        ProductionReportingDetail ProductionReportingDetail = this.getById(id);
        ProductionReportingDetailVo result = BeanUtil.toBean(ProductionReportingDetail, ProductionReportingDetailVo.class);
        return result;
    }

    @Override
    @DSTransactional
    public synchronized void add(ProductionReportingDetailDto dto) {
//        Long productionTaskId = dto.getProductionTaskId();
//        Long productionProcessesId = dto.getProductionProcessesId();
//        BigDecimal reportingQuantity = dto.getQuantity();
//
//        Assert.notEmpty(productionTaskId, "生产任务id不能为空！");
//        Assert.notEmpty(productionProcessesId, "生产工序id不能为空！");
//        Assert.notEmpty(reportingQuantity, "报工数量不能为空！");
//
//
//        ProductionTaskProgress productionTaskProgress = productionTaskProgressService.getOne(q -> q
//                .eq(ProductionTaskProgress::getTaskId, productionTaskId)
//                .eq(ProductionTaskProgress::getProcessesId, productionProcessesId)
//        );
//
//        Assert.notEmpty(productionTaskProgress, "查询不到生产进度信息");
//
//        //更新生产进度信息
//        productionTaskProgressService.update(q -> q
//                .eq(ProductionTaskProgress::getId, productionTaskProgress.getId())
//                .setSql("finish_quantity = finish_quantity + " + dto.getQuantity())
//                .set(BasePo::getUpdateTime, new Date())
//                .set(BasePo::getUpdateUser, SecurityUtils.getUserId())
//        );
//
//        //更新完工数量
//        ProductionOrderDetail productionOrderDetail = produceOrderDetailService.getById(productionTaskId);
//        Assert.notEmpty(productionOrderDetail, "查询不到生产任务信息！");
//        ProductInfo productInfo = productInfoService.getById(productionOrderDetail.getProductId());
//        Assert.notEmpty(productInfo, "查询不到生产产品信息！");
//        Long technologyId = productInfo.getTechnologyId();
//        //判断报工工序是不是最后一道工序,是增加完工数量
//        long count = technologyProcessLineService.count(q -> q
//                .eq(TechnologyProcessLine::getTechnologyId, technologyId)
//                .eq(TechnologyProcessLine::getSourceProcessesId, productionProcessesId)
//                .eq(TechnologyProcessLine::getTargetProcessesId, 99)
//        );
//        if (count > 0) {
//            //是最后一道工序添加完工数量
//            BigDecimal quantity = productionOrderDetail.getQuantity();
//            BigDecimal finishQuantity = productionOrderDetail.getFinishQuantity();
//            //计算完工数量
//            BigDecimal add = finishQuantity.add(reportingQuantity);
//            productionOrderDetail.setFinishQuantity(add);
//            //全部完成赋值完工时间
//            if (add.compareTo(quantity) >= 0) {
//                productionOrderDetail.setFinishTime(new Date());
//                productionOrderDetail.setProduceStatus(2);
//            }
//            produceOrderDetailService.updateById(productionOrderDetail);
//        }
//        //检查订单下的任务是否完成，更改状态
//        Long produceOrderId = productionOrderDetail.getProduceOrderId();
//        long count1 = produceOrderDetailService.count(q -> q
//                .eq(ProductionOrderDetail::getProduceOrderId, produceOrderId)
//                .ne(ProductionOrderDetail::getProduceStatus, 2)
//        );
//        if (count1 == 0) {
//            produceOrderService.update(q -> q
//                    .eq(BasePo::getId, produceOrderId)
//                    .set(BasePo::getUpdateUser, SecurityUtils.getUserId())
//                    .set(BasePo::getUpdateTime, new Date())
//                    .set(ProductionOrder::getProduceStatus, 2)
//            );
//        }
//
//        this.save(dto);
    }

    @Override
    public void edit(ProductionReportingDetailDto productionReportingDetailDto) {
        this.updateById(productionReportingDetailDto);
    }

    @Override
    public void delete(Long id) {
        this.removeById(id);
    }

}
