package com.unis.crk.cplbusiness.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
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.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.cplbusiness.entity.CommoditySplitting;
import com.unis.crk.cplbusiness.entity.vo.CommoditySplittingVo;
import com.unis.crk.cplbusiness.mapper.CommoditySplittingMapper;
import com.unis.crk.cplbusiness.service.ICommoditySplittingService;
import com.unis.crk.cplbusiness.service.IDataKcglCplkcbdDefaultService;
import com.unis.crk.cplbusiness.service.IDataKcglCplkcswDefaultService;
import com.unis.crk.cplbusiness.service.IDataKcglCplxckcDefaultService;
import com.unis.crk.enums.EditStatus;
import com.unis.crk.enums.StoreWorkType;
import com.unis.crk.utils.ResultUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 商品拆分 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2022-05-23
 */
@Service
public class CommoditySplittingServiceImpl extends ServiceImpl<CommoditySplittingMapper, CommoditySplitting> implements ICommoditySplittingService {

    @Resource
    private CommoditySplittingMapper commoditySplittingMapper;


    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;


    @Autowired
    private IDataKcglCplxckcDefaultService dataKcglCplxckcDefaultService;
    /**
     *修改商品拆分
     * @param param 商品拆分业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(CommoditySplitting param){
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        if(!super.saveOrUpdate(param)){
            jsonObject.set("msg", "修改数据失败");
            return jsonObject;
        }
        jsonObject.set("success", true);
        jsonObject.set("msg", "修改成功");
        return jsonObject;
    }
    /**
     *删除商品拆分数据
     * @param id 商品拆分主键尖
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject delete(String id){
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        CommoditySplitting commoditySplitting = commoditySplittingMapper.selectById(id);
        if(!super.removeById(id)){
            jsonObject.set("msg", "删除数据失败");
            return jsonObject;
        }
        deleteDataRecordService.save(id,"commodity_splitting",commoditySplitting.getUnitid(),new Date());
        jsonObject.set("success", true);
        jsonObject.set("msg", "删除成功");
        return jsonObject;
        }

    /**
     * 按照条件查询商品拆分信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(CommoditySplittingVo pageQuery){
        {
        //条形查询器
        QueryWrapper<CommoditySplitting> queryWrapper = new QueryWrapper<>();
        //分页相关
        Page<CommoditySplitting> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());
            if(StringUtils.isNotBlank(pageQuery.getUnitId())) {
                queryWrapper.eq("a.unitid", pageQuery.getUnitId());
            }
        if(StrUtil.isNotBlank(pageQuery.getCommodityName())){
            queryWrapper.like("mxpz_enum.sjjlspmc", ResultUtil.getQueryWrapperformat(pageQuery.getCommodityName()));
        }
        if (StringUtils.isNotBlank(pageQuery.getYwStart()) && StringUtils.isNotBlank(pageQuery.getYwEnd())){
            queryWrapper.apply(" DATE_FORMAT(ifnull(plit_time,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getYwStart()+"' AND DATE_FORMAT(ifnull(plit_time,NOW()),'%Y-%m-%d') <= '"+pageQuery.getYwEnd()+" 23:59:59'");

        }
            queryWrapper.eq("mainDataId",null);
        IPage<Map<String,Object>> page = commoditySplittingMapper.selectMyMapsPage(p,queryWrapper);
        return page;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveSplits(List<CommoditySplitting> param) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        Iterator<CommoditySplitting> iterator = param.iterator();
        String dataid = IdUtil.simpleUUID();
        EditStatus editStatus = EditStatus.New;
        StoreWorkType workType;
        while (iterator.hasNext()){
            CommoditySplitting next = iterator.next();
            //判断是否为拆分商品
            Boolean b;
            if(StringUtils.isNotBlank(next.getDataId())){
                next.setDataId(dataid);
                workType = StoreWorkType.CplCfCk;//成品商品拆分出库
                 b = dataKcglCplxckcDefaultService.makeStockDetail(next.getDataId(), next.getUnitid(), next.getBuilder(), editStatus, workType);

            }else{
                next.setMainDataId(dataid);
                workType = StoreWorkType.CplCfRk;//成品商品拆分入库
                 b = dataKcglCplxckcDefaultService.makeStockDetail(next.getDataId(), next.getUnitid(), next.getBuilder(), editStatus, workType);
            }
            if(!b){
                jsonObject.set("msg", "保存仓储数据失败");
                throw new RuntimeException("保存仓储数据失败");
            }
            super.saveOrUpdate(next);
        }
        return jsonObject;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject delSplits(List<CommoditySplitting> param) throws Exception {
        return null;
    }


}
