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

import cn.hutool.core.util.StrUtil;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.cplbusiness.entity.DataKcglCplkcbdDefault;
import com.unis.crk.cplbusiness.entity.DataKcglCplkcswDefault;
import com.unis.crk.cplbusiness.mapper.DataKcglCplkcbdDefaultMapper;
import com.unis.crk.cplbusiness.mapper.DataKcglCplkcswDefaultMapper;
import com.unis.crk.cplbusiness.service.IDataKcglCplkcbdDefaultService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.json.JSONObject;
import javax.annotation.Resource;
import com.unis.crk.cplbusiness.entity.vo.DataKcglCplkcbdDefaultVo;
import org.springframework.util.ObjectUtils;

/**
 * <p>
 * 成品粮库存变动 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2022-03-21
 */
@Service
public class DataKcglCplkcbdDefaultServiceImpl extends ServiceImpl<DataKcglCplkcbdDefaultMapper, DataKcglCplkcbdDefault> implements IDataKcglCplkcbdDefaultService {

    @Resource
    private DataKcglCplkcbdDefaultMapper dataKcglCplkcbdDefaultMapper;

    @Resource
    private DataKcglCplkcswDefaultMapper dataKcglCplkcswDefaultMapper;
    @Autowired
    private IDataKcglCplxckcDefaultService dataKcglCplxckcDefaultService;

    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;
    /**
     *修改成品粮库存变动
     * @param param 成品粮库存变动业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(DataKcglCplkcbdDefault param){
        return null;
    }
    /**
     *删除成品粮库存变动数据
     * @param id 成品粮库存变动主键尖
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject delete(String id){
        return null;
        }

    /**
     * 按照条件查询成品粮库存变动信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataKcglCplkcbdDefaultVo pageQuery){
        {
        //条形查询器
        QueryWrapper<DataKcglCplkcbdDefault> queryWrapper = new QueryWrapper<>();
        //分页相关
        Page<DataKcglCplkcbdDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());
        if(!ObjectUtils.isEmpty(pageQuery.getBdfs())){
            queryWrapper.eq("a.bdfs",pageQuery.getBdfs());
        }
        if(!ObjectUtils.isEmpty(pageQuery.getBddh())){
            queryWrapper.like("a.bddh",pageQuery.getBddh());
        }
        if(!ObjectUtils.isEmpty(pageQuery.getCh())){
            queryWrapper.eq("a.ch",pageQuery.getCh());
        }
            if(!ObjectUtils.isEmpty(pageQuery.getScpc())){
                queryWrapper.eq("a.scpc",pageQuery.getScpc());
            }
            if(!ObjectUtils.isEmpty(pageQuery.getUnitId())){
                queryWrapper.eq("a.unitid",pageQuery.getUnitId());
            }
            if(!ObjectUtils.isEmpty(pageQuery.getSjjlpzbh())){
                queryWrapper.eq("a.sjjlpzbh",pageQuery.getSjjlpzbh());
            }
            if(!ObjectUtils.isEmpty(pageQuery.getSjjlspmc())){
                queryWrapper.like("a.sjjlspmc", ResultUtil.getQueryWrapperformat(pageQuery.getSjjlspmc()));
            }
            if (StringUtils.isNotBlank(pageQuery.getYwStart()) && StringUtils.isNotBlank(pageQuery.getYwEnd())){
                queryWrapper.apply(" DATE_FORMAT(ifnull(a.ywsj,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getYwStart()+"' AND DATE_FORMAT(ifnull(a.ywsj,NOW()),'%Y-%m-%d') <= '"+pageQuery.getYwEnd()+" 23:59:59'");
            }
        IPage<Map<String,Object>> page = dataKcglCplkcbdDefaultMapper.selectMyMapsPage(p,queryWrapper);
        return page;
        }
    }

    @Override
    public List<Map<String,Object>> getKcsw(String ch, String hwh, String unitid) {
        List<Map<String,Object>> kcsw = dataKcglCplkcswDefaultMapper.getKcsw(ch, hwh, unitid);
        return kcsw;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveList(List<DataKcglCplkcbdDefault> param) throws Exception  {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        for(Iterator<DataKcglCplkcbdDefault> it = param.iterator(); it.hasNext();){
            DataKcglCplkcbdDefault next = it.next();
            next.setBdfs(StoreWorkType.KcbdPc.toString());
            //next.setYwsj(new Date());
            if (StrUtil.isBlank(next.getXz())){
                next.setXz("952751"); //默认值
            }

                if(!this.saveOrUpdate(next)){
                    throw  new Exception("盘点保存失败");
                }
            if("0".equals(next.getIsstaging())){
                continue;
            }
            EditStatus editStatus = EditStatus.New;
            //默认库存变动是益
            StoreWorkType workType = StoreWorkType.KcbdRk;
            //库存数量-盘点数量
            if(next.getBdqjs()-next.getBdhjs()>0){
                workType = StoreWorkType.KcbdCk;
            }
            //盘点件数和实际件数相等则只做记录不改变库存
            if(next.getBdqjs()-next.getBdhjs()==0){
                continue;
            }
            Boolean b = dataKcglCplxckcDefaultService.makeStockDetail(next.getDataId(), next.getUnitid(), next.getBuilder(), editStatus, workType);
            if (!b) {
                jsonObject.set("msg", "保存仓储数据失败");
                throw new RuntimeException("保存仓储数据失败");
            }
        }
        jsonObject.set("success", true);
        jsonObject.set("msg", "保存成功");
        return jsonObject;
    }

    @Override
    public JSONObject updateKcbd(DataKcglCplkcbdDefault param) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject deleteKcPd(String id) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        EditStatus editStatus = EditStatus.Deleted;
        DataKcglCplkcbdDefault byId = this.getById(id);
        if(byId==null){
            jsonObject.set("msg", "无数据");
            throw new RuntimeException("无数据");
        }
        //默认库存变动是益
        StoreWorkType workType = StoreWorkType.KcbdRk;
        //库存数量-盘点数量
        if(byId.getBdqjs()-byId.getBdhjs()>0){
            workType = StoreWorkType.KcbdCk;
        }
        //删除时 盘点件数和实际件数相等则删除盘点记录
        if(byId.getBdqjs()-byId.getBdhjs()==0){
            boolean b1 = this.removeById(id);
            if (!b1) {
                jsonObject.set("msg", "删除盘点数据失败");
                throw new RuntimeException("删除盘点数据失败");
            }else{
                jsonObject.set("success", true);
                jsonObject.set("msg", "删除成功");
                return jsonObject;
            }
        }
        Boolean b = dataKcglCplxckcDefaultService.makeStockDetail(byId.getDataId(), byId.getUnitid(), byId.getBuilder(), editStatus, workType);
        if (!b) {
            jsonObject.set("msg", "保存仓储数据失败");
            throw new RuntimeException("保存仓储数据失败");
        }

        boolean b1 = this.removeById(id);
        if (!b1) {
            jsonObject.set("msg", "删除盘点数据失败");
            throw new RuntimeException("删除盘点数据失败");
        }
        deleteDataRecordService.save(id,"data_kcgl_cplkcbd_default",byId.getUnitid(),new Date());
        jsonObject.set("success", true);
        jsonObject.set("msg", "删除成功");
        return jsonObject;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveListDbs(List<DataKcglCplkcbdDefault> param) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        for(Iterator<DataKcglCplkcbdDefault> it = param.iterator(); it.hasNext();) {

            DataKcglCplkcbdDefault next = it.next();
            String scpc = next.getScpc();
            String sjjlppbh = next.getSjjlppbh();
            String sjjlpzbh = next.getSjjlpzbh();
            String sjjlspmcbh = next.getSjjlspmcbh();
            String unitid = next.getUnitid();
            String yrch = next.getYrch();
            String yrhwh = next.getYrhwh();
            next.setBdfs(StoreWorkType.KcbdYc.toString());
            if (StrUtil.isBlank(next.getXz())){
                next.setXz("952751"); //默认值
            }
            next.setBdhjs(next.getBdhsl()/Double.parseDouble(next.getGg()));
            //查询调入库存信息，并为调拨数据赋值
            QueryWrapper<DataKcglCplkcswDefault> dataKcglCplkcswDefaultQueryWrapper = new QueryWrapper<>();
            dataKcglCplkcswDefaultQueryWrapper.eq("scpc",scpc);
            dataKcglCplkcswDefaultQueryWrapper.eq("sjjlppbh",sjjlppbh);
            dataKcglCplkcswDefaultQueryWrapper.eq("sjjlpzbh",sjjlpzbh);
            dataKcglCplkcswDefaultQueryWrapper.eq("sjjlspmcbh",sjjlspmcbh);
            dataKcglCplkcswDefaultQueryWrapper.eq("unitid",unitid);
            dataKcglCplkcswDefaultQueryWrapper.eq("ch",yrch);
            dataKcglCplkcswDefaultQueryWrapper.eq("hwh",yrhwh);
            DataKcglCplkcswDefault dataKcglCplkcswDefault = dataKcglCplkcswDefaultMapper.selectOne(dataKcglCplkcswDefaultQueryWrapper);
            if(dataKcglCplkcswDefault!=null){
                next.setYrcqjs(dataKcglCplkcswDefault.getJs());
                next.setYrcqsl(dataKcglCplkcswDefault.getKcsl());
                next.setYrchjs(dataKcglCplkcswDefault.getJs()+next.getBdjs());
                next.setYrchsl(dataKcglCplkcswDefault.getKcsl()+next.getBdsl());
            }else{
                next.setYrcqjs(0.0);
                next.setYrcqsl(0.0);
                next.setYrchjs(next.getBdjs());
                next.setYrchsl(next.getBdsl());
            }
            if (!this.saveOrUpdate(next)) {
                throw new Exception("保存失败");
            }
            if("0".equals(next.getIsstaging())){ //暂存直接跳出循环不修改库存
                continue;
            }
            EditStatus editStatus = EditStatus.New;
            //默认库存变动是益
            StoreWorkType workType = StoreWorkType.KcbdYc;//移仓
            Boolean b = dataKcglCplxckcDefaultService.makeStockDetail(next.getDataId(), next.getUnitid(), next.getBuilder(), editStatus, workType);
            if (!b) {
                jsonObject.set("msg", "保存仓储数据失败");
                throw new RuntimeException("保存仓储数据失败");
            }


        }
        jsonObject.set("success", true);
        jsonObject.set("msg", "保存成功");
        return jsonObject;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject deleteKcDb(String id) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        EditStatus editStatus = EditStatus.Deleted;
        DataKcglCplkcbdDefault byId = this.getById(id);
        StoreWorkType workType = StoreWorkType.KcbdYc;//移仓
        Boolean b = dataKcglCplxckcDefaultService.makeStockDetail(byId.getDataId(), byId.getUnitid(), byId.getBuilder(), editStatus, workType);
        if (!b) {
            jsonObject.set("msg", "保存仓储数据失败");
            throw new RuntimeException("保存仓储数据失败");
        }

        boolean b1 = this.removeById(id);
        if (!b1) {
            jsonObject.set("msg", "删除盘点数据失败");
            throw new RuntimeException("删除盘点数据失败");
        }
        deleteDataRecordService.save(id,"data_kcgl_cplkcbd_default",byId.getUnitid(),new Date());
        jsonObject.set("success", true);
        jsonObject.set("msg", "删除成功");
        return jsonObject;
    }

    @Override
    public IPage<Map<String, Object>> getCplPdList(DataKcglCplkcbdDefaultVo pageQuery) {
        QueryWrapper<DataKcglCplkcbdDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.bdfs","16");
        if(!ObjectUtils.isEmpty(pageQuery.getCh())){
            queryWrapper.eq("a.ch",pageQuery.getCh());
        }
        if(!ObjectUtils.isEmpty(pageQuery.getScpc())){
            queryWrapper.eq("a.scpc",pageQuery.getScpc());
        }
        if(!ObjectUtils.isEmpty(pageQuery.getUnitId())){
            queryWrapper.eq("a.unitid",pageQuery.getUnitId());
        }
        if(!ObjectUtils.isEmpty(pageQuery.getSjjlpzbh())){
            queryWrapper.eq("a.sjjlpzbh",pageQuery.getSjjlpzbh());
        }
        if(!ObjectUtils.isEmpty(pageQuery.getSjjlspmc())){
            queryWrapper.like("a.sjjlspmc", ResultUtil.getQueryWrapperformat(pageQuery.getSjjlspmc()));
        }
        if (StringUtils.isNotBlank(pageQuery.getYwStart()) && StringUtils.isNotBlank(pageQuery.getYwEnd())){
            queryWrapper.apply(" DATE_FORMAT(ifnull(a.ywsj,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getYwStart()+"' AND DATE_FORMAT(ifnull(a.ywsj,NOW()),'%Y-%m-%d') <= '"+pageQuery.getYwEnd()+" 23:59:59'");

        }
        queryWrapper.groupBy("a.bddh");
        IPage<DataKcglCplkcbdDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());
        IPage<Map<String, Object>> mapIPage = dataKcglCplkcbdDefaultMapper.selectMyMapsPage(p, queryWrapper);
        return mapIPage;
    }

    @Override
    public List<DataKcglCplkcbdDefault>getCplPdListflt(DataKcglCplkcbdDefaultVo pageQuery) {
        QueryWrapper<DataKcglCplkcbdDefault> queryWrapper = new QueryWrapper<>();

        if(!ObjectUtils.isEmpty(pageQuery.getSjjlpzbh())){
            queryWrapper.eq("a.bddh",pageQuery.getSjjlpzbh());
        }
        queryWrapper.groupBy("bddh");
        List<DataKcglCplkcbdDefault> dataKcglCplkcbdDefaults = dataKcglCplkcbdDefaultMapper.selectList(queryWrapper);
        return dataKcglCplkcbdDefaults;
    }


}
