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

import cn.hutool.core.util.StrUtil;
import com.unis.crk.basic.service.IBasicEnumService;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.cplbusiness.entity.*;
import com.unis.crk.cplbusiness.mapper.DataCrkywCplfjDefaultMapper;
import com.unis.crk.cplbusiness.service.IDataCrkywCplfjDefaultService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.crk.cplbusiness.service.IDataCrkywCplfjFlt001Service;
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.*;

import cn.hutool.json.JSONObject;
import com.unis.crk.cplbusiness.entity.vo.DataCrkywCplfjDefaultVo;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 成品粮分拣 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2022-07-19
 */
@Service
public class DataCrkywCplfjDefaultServiceImpl extends ServiceImpl<DataCrkywCplfjDefaultMapper, DataCrkywCplfjDefault> implements IDataCrkywCplfjDefaultService {

    @Resource
    private DataCrkywCplfjDefaultMapper dataCrkywCplfjDefaultMapper;
    @Autowired
    private IDataCrkywCplfjFlt001Service dataCrkywCplfjFlt001Service;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;
    @Autowired
    private IBasicEnumService basicEnumService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveFj(DataCrkywCplfjDefault param) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        param.setDeptId(param.getUnitid());//部门id
        if (StringUtils.isBlank(param.getBuilder())){
            param.setBuilder(param.getUnitid());
            param.setEditor(param.getUnitid());
        }
//        param.setYwlx("1");//业务类型，1入库
        if (!super.saveOrUpdate(param)) { //
            throw new Exception("保存成品粮分拣失败");
        }

        String dataId = param.getDataId();
        String unitId = param.getUnitid();
        //得到从表数据
        List<DataCrkywCplfjFlt001> flt001s = param.getFltList();
        if (flt001s == null || flt001s.size() <= 0){
            throw new Exception("成品粮分拣商品信息为空失败");
        }
        for (int i = 0; i < flt001s.size(); i++) {
            //保存从表数据，有错误抛异常
            DataCrkywCplfjFlt001 flt001 = flt001s.get(i);
            flt001.setMainDataId(dataId);// 设置主表ID
            flt001.setUnitid(unitId);// 设置单位id
            //性质默认值
            if(StrUtil.isBlank(flt001.getXz())){
                flt001.setXz("952751");
            }
            //数量=件数*规格
            flt001.setSjjlsl(flt001.getJs()*Double.parseDouble(flt001.getGg()) );
            //金额=数理*单价
            flt001.setJe(flt001.getSjjlsl()*flt001.getDj());

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject updateFj(DataCrkywCplfjDefault param) throws Exception {
        //保存库存相关数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        //得到对象
        DataCrkywCplfjDefault entity = super.getById(param.getDataId());
        if (entity == null) {
            jsonObject.set("msg", "此数据已被删除");
            return jsonObject;
        }
        List<DataCrkywCplfjFlt001> insertFlt = new ArrayList<>(); //新增
        List<DataCrkywCplfjFlt001> updateFlt = new ArrayList<>(); //修改
        List<String> deleteFlt = new ArrayList<>(); //删除
        //得到从表数据
        QueryWrapper<DataCrkywCplfjFlt001> Wrapper = new QueryWrapper<>();
        Wrapper.eq("MainDataID", param.getDataId());
        List<DataCrkywCplfjFlt001> oldFlt001s = dataCrkywCplfjFlt001Service.list(Wrapper);

        List<DataCrkywCplfjFlt001> newFlt001s = param.getFltList();
        for (int j = 0; j < newFlt001s.size(); j++) {
            DataCrkywCplfjFlt001 newFlt001 = newFlt001s.get(j);
            if (StrUtil.isBlank(newFlt001.getDataId())){ //新增
                insertFlt.add(newFlt001);
            }
        }
        newFlt001s.removeAll(insertFlt); //去掉新增

        for (int i = 0; i < oldFlt001s.size(); i++) {
            DataCrkywCplfjFlt001 oldFlt001 = oldFlt001s.get(i);
            boolean flag  = false;
            for (int j = 0; j < newFlt001s.size(); j++) {
                DataCrkywCplfjFlt001 newFlt001 = newFlt001s.get(j);
                if ( StrUtil.equals(newFlt001.getDataId(),oldFlt001.getDataId())){ //修改
                    updateFlt.add(newFlt001);
                    flag = true;
                    continue;
                }
            }
            if (!flag){
                deleteFlt.add(oldFlt001.getDataId()); //删除内容
            }
        }
        if (!super.updateById(param)) { //修改成品粮分拣
            throw new Exception("修改成品粮分拣失败");
        }
        if (insertFlt.size() >0){ //新增内容
            for (int j = 0; j < insertFlt.size(); j++) {
                //保存从表数据，有错误抛异常
                DataCrkywCplfjFlt001 flt001 = insertFlt.get(j);
                flt001.setMainDataId(param.getDataId());// 设置主表
                flt001.setUnitid(param.getUnitid());//
                //性质默认值
                if(StrUtil.isBlank(flt001.getXz())){
                    flt001.setXz("952751");
                }
                //数量=件数*规格
                flt001.setSjjlsl(flt001.getJs()*Double.parseDouble(flt001.getGg()) );
                //金额=数理*单价
                flt001.setJe(flt001.getSjjlsl()*flt001.getDj());

//                dataCrkywCplfjFlt001Service.saveFlt(flt001);
                dataCrkywCplfjFlt001Service.save(flt001);
            }
        }
        if (updateFlt.size() >0){ //修改内容
            for (int j = 0; j < updateFlt.size(); j++) {
                //修改从表数据，有错误抛异常
                DataCrkywCplfjFlt001 flt001 = updateFlt.get(j);
                flt001.setMainDataId(param.getDataId());// 设置主表
                flt001.setUnitid(param.getUnitid());
                //数量=件数*规格
                flt001.setSjjlsl(flt001.getJs()*Double.parseDouble(flt001.getGg()) );
                //金额=数理*单价
                flt001.setJe(flt001.getSjjlsl()*flt001.getDj());
//                JSONObject flag = dataCrkywCplfjFlt001Service.updateFlt(flt001);
                 dataCrkywCplfjFlt001Service.updateById(flt001);

            }
        }
        if (deleteFlt.size() >0){ //删除内容
            for (int j = 0; j < deleteFlt.size(); j++) {
                //删除从表数据，有错误抛异常
                DataCrkywCplfjFlt001 byId = dataCrkywCplfjFlt001Service.getById(deleteFlt.get(j));
                dataCrkywCplfjFlt001Service.removeById(deleteFlt.get(j));
                deleteDataRecordService.save(deleteFlt.get(j),"data_crkyw_cplfj_flt_001",byId.getUnitid(),new Date());
            }
        }
        jsonObject.set("success", true);
        jsonObject.set("msg", "修改成功");
        return jsonObject;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject deleteFj(String id) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        //得到对象
        DataCrkywCplfjDefault entity = super.getById(id);
        if (entity == null) {
            jsonObject.set("msg", "此数据已被删除");
            return jsonObject;
        }
        if (!super.removeById(id)) {
            jsonObject.set("msg", "删除成品粮分拣数据失败");
            return jsonObject;
        }

        //得到从表数据
        QueryWrapper<DataCrkywCplfjFlt001> flt001QueryWrapper = new QueryWrapper<>();
        flt001QueryWrapper.eq("mainDataId",id);
        List<DataCrkywCplfjFlt001> flt001s = dataCrkywCplfjFlt001Service.list(flt001QueryWrapper);
        if (flt001s != null || flt001s.size() > 0){
            for (int i = 0; i < flt001s.size(); i++) {
                //删除从表数据，有错误抛异常
                DataCrkywCplfjFlt001 flt001 = flt001s.get(i);
                dataCrkywCplfjFlt001Service.removeById(flt001.getDataId());
                deleteDataRecordService.save(flt001.getDataId(),"data_crkyw_cplfj_flt_001",flt001.getUnitid(),new Date());
            }
        }
        deleteDataRecordService.save(id,"data_crkyw_cplfj_default",entity.getUnitid(),new Date());
        jsonObject.set("success", true);
        jsonObject.set("msg", "删除成功");
        return jsonObject;
    }

    /**
     * 得到回显数据
     *
     * @param id
     * @return
     */
    @Override
    public DataCrkywCplfjDefault getOneData(String id) {
        DataCrkywCplfjDefault dataCrkywCplfjDefault = super.getById(id);
        QueryWrapper<DataCrkywCplfjFlt001> Wrapper = new QueryWrapper<>();
        Wrapper.eq("MainDataID", id);
        List<DataCrkywCplfjFlt001> list = dataCrkywCplfjFlt001Service.list(Wrapper);
        if(list!=null && list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                DataCrkywCplfjFlt001 flt001 = list.get(i);
                flt001.setJldwmc(basicEnumService.getById(flt001.getJldw()).getEnumName());
            }
            dataCrkywCplfjDefault.setFltList(list);
        }

        return dataCrkywCplfjDefault;
    }

    /**
     * 按照条件查询成品粮分拣信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataCrkywCplfjDefaultVo pageQuery){
        {
        //条件查询器
        QueryWrapper<DataCrkywCplfjDefault> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(pageQuery.getUnitId())){
             queryWrapper.eq("unitId",pageQuery.getUnitId());
        }
            if(StringUtils.isNotBlank(pageQuery.getFjdh())){
                queryWrapper.like("fjdh",ResultUtil.getQueryWrapperformat(pageQuery.getFjdh()));
            }
            if (StringUtils.isNotBlank(pageQuery.getYwsjStart()) && StringUtils.isNotBlank(pageQuery.getYwsjEnd())){
                queryWrapper.apply(" DATE_FORMAT(ifnull(ywsj,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getYwsjStart()+"' AND DATE_FORMAT(ifnull(ywsj,NOW()),'%Y-%m-%d') <= '"+pageQuery.getYwsjEnd()+" 23:59:59'");

            }
        //分页相关
        Page<DataCrkywCplfjDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

        IPage<Map<String,Object>> page = dataCrkywCplfjDefaultMapper.selectMyMapsPage(p,queryWrapper);
        return page;
        }
    }
}
