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.aop.SystemLog;
import com.unis.crk.basic.entity.BasicEnum;
import com.unis.crk.basic.entity.SysParams;
import com.unis.crk.basic.service.IBasicEnumService;
import com.unis.crk.basic.service.ISysParamsService;
import com.unis.crk.common.service.IBillnonewService;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.cplbusiness.entity.*;
import com.unis.crk.cplbusiness.entity.vo.DataCrkywCplrkDefaultVo;
import com.unis.crk.cplbusiness.mapper.DataCrkywCplrkDefaultMapper;
import com.unis.crk.cplbusiness.service.*;
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 javax.xml.soap.Detail;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 成品粮入库 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2022-03-21
 */
@Service
public class DataCrkywCplrkDefaultServiceImpl extends ServiceImpl<DataCrkywCplrkDefaultMapper, DataCrkywCplrkDefault> implements IDataCrkywCplrkDefaultService {

    @Resource
    private DataCrkywCplrkDefaultMapper dataCrkywCplrkDefaultMapper;
    @Autowired
    private IDataCrkywCplrkFlt001Service dataCrkywCplrkFlt001Service;
    @Autowired
    private IBasicEnumService basicEnumService;
    @Autowired
    private IDataCrkywCplpfDefaultService dataCrkywCplpfDefaultService;
    @Autowired
    private IBillnonewService billnonewService;
    @Autowired
    private ISettlementManagementService settlementManagementService;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;
    @Autowired
    private ISysParamsService sysParamsService;
    @Autowired
    private IDataCrkywCpltzdxxDefaultService dataCrkywCpltzdxxDefaultService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveRk(DataCrkywCplrkDefault param) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        if (isExist(param.getRkbh())){
            jsonObject.set("msg","此单据号已存在");
            return jsonObject;
        }
        param.setDeptId(param.getUnitid());//部门id
        if (StringUtils.isBlank(param.getBuilder())){
            param.setBuilder(param.getUnitid());
            param.setEditor(param.getUnitid());
        }
        if (param.getFltList() == null || param.getFltList().size() <= 0) { //
            throw new Exception("成品粮入库无从表数据");
        }
//        param.setYwlx("1");//业务类型，1入库
        if (!super.saveOrUpdate(param)) { //
            throw new Exception("保存成品粮入库失败");
        }

        String dataId = param.getDataId();
        String unitId = param.getUnitid();
        String s = IdUtil.simpleUUID();
        if(StringUtils.isBlank(dataId)){
            dataId=s;
            param.setDataId(s);
        }
        //非暂存保存结算数据
        if(!"0".equals(param.getIsstaging())){
            SettlementManagement settlementManagement = new SettlementManagement();
            settlementManagement.setReceiptDocNo(param.getRkbh());//入库编号
            settlementManagement.setOrderNo(param.getDdbh());//订单编号
            settlementManagement.setSupplierName(param.getGys());
            settlementManagement.setTradeName(param.getSjjlspmc());
            settlementManagement.setUnitid(unitId);
            settlementManagement.setBuilderDate(new Date());
            settlementManagement.setBuilder("系统自动生成");
            settlementManagement.setWarehousingTime(param.getYwsj());
            settlementManagement.setAuditStatus("0");
            settlementManagementService.save(settlementManagement);
        }
        //得到从表数据
        List<DataCrkywCplrkFlt001> flt001s = param.getFltList();
        if (flt001s == null || flt001s.size() <= 0){
            throw new Exception("成品粮入库商品信息为空失败");
        }
        String spmc = "";
        for (int i = 0; i < flt001s.size(); i++) {
            //保存从表数据，有错误抛异常
            DataCrkywCplrkFlt001 flt001 = flt001s.get(i);
            flt001.setMainDataId(dataId);// 设置主表ID
            flt001.setUnitid(unitId);// 设置单位id
            SysParams byId = sysParamsService.getById("sy.url");
            String paramVal = byId.getParamVal();
            String syurl=paramVal+"/"+unitId+"/"+param.getCh()+"/"+param.getHwh()+"/"+flt001.getSjjlspmcbh()+"/"+param.getRkbh()+"/"+flt001.getScpc();
            flt001.setSyurl(syurl);
            //非暂存保存入库数据和评分数据
            if(!"0".equals(param.getIsstaging())) {
                spmc += flt001.getSjjlspmc() + ",";
                flt001.setIsstaging("1");
                //有订单时，自动新增评分数据
                if (StrUtil.isNotBlank(param.getDdbh())) {
                    DataCrkywCplpfDefault dataCrkywCplpfDefault = new DataCrkywCplpfDefault();
                    dataCrkywCplpfDefault.setScpc(flt001.getScpc());
                    dataCrkywCplpfDefault.setSjjlspmcbh(flt001.getSjjlspmcbh());
                    dataCrkywCplpfDefault.setTzdbm(param.getDdbh());
                    dataCrkywCplpfDefault.setUnitid(param.getUnitid());
                    dataCrkywCplpfDefault.setCjsj(param.getCjsj());
                    dataCrkywCplpfDefault.setRkbh(param.getRkbh());
                    dataCrkywCplpfDefault.setRksj(param.getYwsj());
                    dataCrkywCplpfDefaultService.save(dataCrkywCplpfDefault);
                    dataCrkywCplrkFlt001Service.saveFlt(flt001);
                }
            }else{ //暂存只保存数据，不涉及业务
                flt001.setIsstaging("0");
                dataCrkywCplrkFlt001Service.save(flt001);
            }
        }
        if (StrUtil.isNotBlank(spmc)){
            param.setSjjlspmc(spmc.substring(0,spmc.length()-1));
            if (!super.saveOrUpdate(param)) { //
                throw new Exception("保存成品粮入库失败");
            }
        }
        jsonObject.set("success", true);
        jsonObject.set("msg", "保存成功");
        return jsonObject;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject updateRk(DataCrkywCplrkDefault param) throws Exception {
        //保存库存相关数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        //得到对象
        String unitId = param.getUnitid();
        String dataId = param.getDataId();
        DataCrkywCplrkDefault entity = super.getById(param.getDataId());
        if (entity == null) {
            jsonObject.set("msg", "此数据已被删除");
            return jsonObject;
        }
        if (param.getFltList() == null || param.getFltList().size() <= 0) { //
            throw new Exception("成品粮入库无从表数据");
        }
        List<DataCrkywCplrkFlt001> insertFlt = new ArrayList<>(); //新增
        List<DataCrkywCplrkFlt001> updateFlt = new ArrayList<>(); //修改
        List<String> deleteFlt = new ArrayList<>(); //删除
        //得到从表数据
        QueryWrapper<DataCrkywCplrkFlt001> Wrapper = new QueryWrapper<>();
        Wrapper.eq("MainDataID", param.getDataId());
        List<DataCrkywCplrkFlt001> oldFlt001s = dataCrkywCplrkFlt001Service.list(Wrapper);
        //得到结算数据并修改结算数据
        QueryWrapper<SettlementManagement> settlementQueryWrapper = new QueryWrapper<>();
        Wrapper.eq("receipt_doc_no", param.getRkbh());
        List<SettlementManagement> list = settlementManagementService.list(settlementQueryWrapper);
        if(list.size()>0 && "1".equals(param.getIsstaging())){ //非暂存时修改结算数据
            SettlementManagement settlementManagement = list.get(0);
            settlementManagement.setReceiptDocNo(param.getRkbh());//入库编号
            settlementManagement.setOrderNo(param.getDdbh());//订单编号
            settlementManagement.setSupplierName(param.getGys());
            settlementManagement.setTradeName(param.getSjjlspmc());
            settlementManagement.setUpdateTime(new Date());
            settlementManagement.setWarehousingTime(param.getYwsj());
            settlementManagement.setAuditStatus("0");
            settlementManagementService.update(settlementManagement);
        }
        String isstaging = param.getIsstaging();

        List<DataCrkywCplrkFlt001> newFlt001s = param.getFltList();
        String spmcz = "";
        for (int j = 0; j < newFlt001s.size(); j++) {
            DataCrkywCplrkFlt001 newFlt001 = newFlt001s.get(j);
            SysParams byId = sysParamsService.getById("sy.url");
            String syurl=byId+"/"+param.getUnitid()+"/"+param.getCh()+"/"+param.getHwh()+"/"+newFlt001.getSjjlspmcbh()+"/"+param.getRkbh()+"/"+newFlt001.getScpc();
            spmcz += newFlt001.getSjjlspmc() + ",";
            newFlt001.setSyurl(syurl);
            if (StrUtil.isBlank(newFlt001.getDataId())){ //新增
                insertFlt.add(newFlt001);
            }
        }
        newFlt001s.removeAll(insertFlt); //去掉新增
        for (int i = 0; i < oldFlt001s.size(); i++) {
            DataCrkywCplrkFlt001 oldFlt001 = oldFlt001s.get(i);
            boolean flag  = false;
            for (int j = 0; j < newFlt001s.size(); j++) {
                DataCrkywCplrkFlt001 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("0".equals(isstaging)) { //暂存
            //删除之前保存的子表数据
            QueryWrapper<DataCrkywCplrkFlt001> wrapper = new QueryWrapper<>();
            wrapper.eq("MainDataID", param.getDataId());
            dataCrkywCplrkFlt001Service.remove(wrapper);
            //结算数据
            SettlementManagement settlementManagement = new SettlementManagement();
            settlementManagement.setReceiptDocNo(param.getRkbh());//入库编号
            settlementManagement.setOrderNo(param.getDdbh());//订单编号
            settlementManagement.setSupplierName(param.getGys());
            settlementManagement.setTradeName(param.getSjjlspmc());
            settlementManagement.setUnitid(unitId);
            settlementManagement.setBuilderDate(new Date());
            settlementManagement.setBuilder("系统自动生成");
            settlementManagement.setWarehousingTime(param.getYwsj());
            settlementManagement.setAuditStatus("0");
            settlementManagementService.save(settlementManagement);

            //新增保存入库子表数据
            String spmc = "";
            for (int i = 0; i < param.getFltList().size(); i++) {
                //保存从表数据，有错误抛异常
                DataCrkywCplrkFlt001 flt001 =  param.getFltList().get(i);
                flt001.setMainDataId(dataId);// 设置主表ID
                flt001.setUnitid(unitId);// 设置单位id
                SysParams byId = sysParamsService.getById("sy.url");
                String paramVal = byId.getParamVal();
                String syurl=paramVal+"/"+unitId+"/"+param.getCh()+"/"+param.getHwh()+"/"+flt001.getSjjlspmcbh()+"/"+param.getRkbh()+"/"+flt001.getScpc();
                flt001.setSyurl(syurl);
                //非暂存保存入库数据和评分数据
                    spmc += flt001.getSjjlspmc() + ",";
                    flt001.setIsstaging("1");
                    //有订单时，自动新增评分数据
                    if (StrUtil.isNotBlank(param.getDdbh())) {
                        DataCrkywCplpfDefault dataCrkywCplpfDefault = new DataCrkywCplpfDefault();
                        dataCrkywCplpfDefault.setScpc(flt001.getScpc());
                        dataCrkywCplpfDefault.setSjjlspmcbh(flt001.getSjjlspmcbh());
                        dataCrkywCplpfDefault.setTzdbm(param.getDdbh());
                        dataCrkywCplpfDefault.setUnitid(param.getUnitid());
                        dataCrkywCplpfDefault.setCjsj(param.getCjsj());
                        dataCrkywCplpfDefault.setRkbh(param.getRkbh());
                        dataCrkywCplpfDefault.setRksj(param.getYwsj());
                        dataCrkywCplpfDefaultService.save(dataCrkywCplpfDefault);
                        dataCrkywCplrkFlt001Service.saveFlt(flt001);
                    }
            }
            param.setSjjlspmc(spmc.substring(0,spmc.length()-1));
            if (!super.saveOrUpdate(param)) { //
                param.setIsstaging("1");
                throw new Exception("保存成品粮入库失败");
            }
            jsonObject.set("success", true);
            jsonObject.set("msg", "保存成功");
            return jsonObject;
        }else{//非暂存
            if (insertFlt.size() >0){ //新增内容
                for (int j = 0; j < insertFlt.size(); j++) {
                    //保存从表数据，有错误抛异常
                    DataCrkywCplrkFlt001 flt001 = insertFlt.get(j);
                    flt001.setMainDataId(param.getDataId());// 设置主表
                    flt001.setUnitid(param.getUnitid());//
                    flt001.setIsstaging("1");
                    dataCrkywCplrkFlt001Service.saveFlt(flt001);
                }
            }
            if (updateFlt.size() >0){ //修改内容
                for (int j = 0; j < updateFlt.size(); j++) {
                    //修改从表数据，有错误抛异常
                    DataCrkywCplrkFlt001 flt001 = updateFlt.get(j);
                    flt001.setMainDataId(param.getDataId());// 设置主表
                    flt001.setUnitid(param.getUnitid());
                    flt001.setIsstaging("1");
                    JSONObject flag = dataCrkywCplrkFlt001Service.updateFlt(flt001);

                }
            }
            if (deleteFlt.size() >0){ //删除内容
                for (int j = 0; j < deleteFlt.size(); j++) {
                    //删除从表数据，有错误抛异常
                    DataCrkywCplrkFlt001 byId = dataCrkywCplrkFlt001Service.getById(deleteFlt.get(j));
                    dataCrkywCplrkFlt001Service.deleteFlt(deleteFlt.get(j));
                    deleteDataRecordService.save(deleteFlt.get(j),"data_crkyw_cplrk_flt_001",byId.getUnitid(),new Date());
                }
            }
            param.setSjjlspmc(spmcz.substring(0,spmcz.length()-1));
            if (!super.saveOrUpdate(param)) { //
                param.setIsstaging("1");
                throw new Exception("保存成品粮入库失败");
            }
            jsonObject.set("success", true);
            jsonObject.set("msg", "保存成功");
            return jsonObject;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject deleteRk(String id) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        //得到对象
        DataCrkywCplrkDefault entity = super.getById(id);
        if (entity == null) {
            jsonObject.set("msg", "此数据已被删除");
            return jsonObject;
        }
        if (!super.removeById(id)) { //删除成品粮入库数据失败
            jsonObject.set("msg", "删除成品粮入库数据失败");
            return jsonObject;
        }
        String isstaging = entity.getIsstaging();//获取保存状态
        deleteDataRecordService.save(id,"data_crkyw_cplrk_default",entity.getUnitid(),new Date());

        //删除结算
        String ddbh = entity.getDdbh();
        String rkbh = entity.getRkbh();
        QueryWrapper<SettlementManagement> settlementManagement = new QueryWrapper<>();
        settlementManagement.eq("receipt_doc_no",rkbh);
        List<SettlementManagement> list = settlementManagementService.list(settlementManagement);
        if(list.size()>0){
            Iterator<SettlementManagement> iterator = list.iterator();
            while (iterator.hasNext()){
                SettlementManagement next = iterator.next();
                settlementManagementService.getById(next.getDataId());
                deleteDataRecordService.save(next.getDataId(),"settlement_management",next.getUnitid(),new Date());
            }
        }
        settlementManagementService.remove(settlementManagement);

        //得到从表数据
        QueryWrapper<DataCrkywCplrkFlt001> flt001QueryWrapper = new QueryWrapper<>();
        flt001QueryWrapper.eq("mainDataId",id);
        if("0".equals(isstaging)){
            dataCrkywCplrkFlt001Service.remove(flt001QueryWrapper);
            jsonObject.set("success", true);
            jsonObject.set("msg", "删除成功");
            return jsonObject;
        }
        List<DataCrkywCplrkFlt001> flt001s = dataCrkywCplrkFlt001Service.list(flt001QueryWrapper);
        if (flt001s != null || flt001s.size() > 0){
            for (int i = 0; i < flt001s.size(); i++) {
                //保存从表数据，有错误抛异常
                DataCrkywCplrkFlt001 flt001 = flt001s.get(i);
                dataCrkywCplrkFlt001Service.deleteFlt(flt001.getDataId());
                //删除评分
                QueryWrapper<DataCrkywCplpfDefault> dataCrkywCplpfDefault = new QueryWrapper<>();
                dataCrkywCplpfDefault.eq("cjsj",entity.getCjsj());
                dataCrkywCplpfDefault.eq("scpc",flt001.getScpc());
                List<DataCrkywCplpfDefault> list1 = dataCrkywCplpfDefaultService.list(dataCrkywCplpfDefault);
                if(list1.size()>0){
                    Iterator<DataCrkywCplpfDefault> iterator = list1.iterator();
                    while (iterator.hasNext()){
                        DataCrkywCplpfDefault next = iterator.next();
                        dataCrkywCplpfDefaultService.delete(next.getDataId());
                        deleteDataRecordService.save(next.getDataId(),"data_crkyw_cplpf_default",next.getUnitid(),new Date());
                    }
                }
            }
        }
        jsonObject.set("success", true);
        jsonObject.set("msg", "删除成功");
        return jsonObject;
    }

    @Override
    public DataCrkywCplrkDefault getOneData(String id) {
            DataCrkywCplrkDefault dataCrkywCplrkDefault = dataCrkywCplrkDefaultMapper.getOneById(id);
            QueryWrapper<DataCrkywCplrkFlt001> Wrapper = new QueryWrapper<>();
            Wrapper.eq("MainDataID", id);
            List<DataCrkywCplrkFlt001> list = dataCrkywCplrkFlt001Service.list(Wrapper);
            if(list!=null && list.size()>0){
                for (int i = 0; i < list.size(); i++) {
                    DataCrkywCplrkFlt001 flt001 = list.get(i);
                    BasicEnum jldw = basicEnumService.getById(flt001.getJldw());
                    flt001.setJldwmc(jldw.getEnumName() != null ?jldw.getEnumName():"");
                }
                dataCrkywCplrkDefault.setFltList(list);
            }
            return dataCrkywCplrkDefault;
    }

    @Override
    public List<DataCrkywCplrkDefault> getAppRkList(String ddbh) {
            List<DataCrkywCplrkDefault> dataCrkywCplrkDefaults = dataCrkywCplrkDefaultMapper.getAppRkList(ddbh);
            for (int i = 0; i < dataCrkywCplrkDefaults.size(); i++) {
                DataCrkywCplrkDefault dataCrkywCplrkDefault = dataCrkywCplrkDefaults.get(i);
                QueryWrapper<DataCrkywCplrkFlt001> Wrapper = new QueryWrapper<>();
                Wrapper.eq("MainDataID", dataCrkywCplrkDefault.getDataId());
                List<DataCrkywCplrkFlt001> list = dataCrkywCplrkFlt001Service.list(Wrapper);
                if(list!=null && list.size()>0){
                    for (int j = 0; j < list.size(); j++) {
                        DataCrkywCplrkFlt001 flt001 = list.get(j);

                        flt001.setJldwmc(basicEnumService.getById(flt001.getJldw()).getEnumName());
                        flt001.setGg(flt001.getGg()+flt001.getJldwmc());
                    }
                    dataCrkywCplrkDefault.setFltList(list);
                }
            }
            return dataCrkywCplrkDefaults;
    }

    @Override
    public List<DataCrkywCplrkDefault> getCphList(String unitId) {
        QueryWrapper<DataCrkywCplrkDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(" DISTINCT cph"," cyr,cyrdh,cyrdz,cyrsfz,cph,cjsj").lambda();
        if(StringUtils.isNotBlank(unitId)){
            queryWrapper.eq("unitId",unitId);
        }
        queryWrapper.isNotNull("cph");
        queryWrapper.isNotNull("cjsj");
        queryWrapper.isNotNull("cph");
        queryWrapper.orderByDesc("cjsj");
        queryWrapper.orderByAsc("cph");
        return super.list(queryWrapper);
    }

    @Override
    public List<HashMap> getScpcByddbh(String ddid, String spbh) {
        DataCrkywCpltzdxxDefault byId = dataCrkywCpltzdxxDefaultService.getById(ddid);
        String thdbm = byId.getThdbm();
        List<HashMap> scpc= dataCrkywCplrkDefaultMapper.getScpcByddbh(thdbm,spbh);
        return scpc;
    }

    /**
     * 按照条件查询成品粮入库信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataCrkywCplrkDefaultVo pageQuery){
        {
        //条形查询器
        QueryWrapper<DataCrkywCplrkDefault> queryWrapper = new QueryWrapper<>();
        //分页相关
            if(StringUtils.isNotBlank(pageQuery.getUnitId())){
                queryWrapper.eq("a.unitId",pageQuery.getUnitId());
            }
            if(StringUtils.isNotBlank(pageQuery.getSjjlpzbh())){
                queryWrapper.eq("a.sjjlpzbh",pageQuery.getSjjlpzbh());
            }
            if(StringUtils.isNotBlank(pageQuery.getSjjlspmc())){
                queryWrapper.like("a.sjjlspmc", ResultUtil.getQueryWrapperformat(pageQuery.getSjjlspmc()));
            }
            if(StringUtils.isNotBlank(pageQuery.getRkbh())){
                queryWrapper.like("a.rkbh",ResultUtil.getQueryWrapperformat(pageQuery.getRkbh()));
            }
            if(StringUtils.isNotBlank(pageQuery.getYwlx())){
                queryWrapper.eq("a.ywlx",pageQuery.getYwlx());
            }
            if(StringUtils.isNotBlank(pageQuery.getCazylx())){
                String cazylx = pageQuery.getCazylx();
                String[] split = cazylx.split(",");
                queryWrapper.in("a.cazylx",split);
            }
            if (StringUtils.isNotBlank(pageQuery.getJysjStart()) && StringUtils.isNotBlank(pageQuery.getJysjEnd())){
                queryWrapper.apply(" DATE_FORMAT(ifnull(a.ywsj,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getJysjStart()+"' AND DATE_FORMAT(ifnull(a.ywsj,NOW()),'%Y-%m-%d') <= '"+pageQuery.getJysjEnd()+" 23:59:59'");

            }
        Page<DataCrkywCplrkDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

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


    /**
     * 通过单据号号检查是否已经存在
     *
     * @param rkbh
     * @return
     */
    private boolean isExist(String rkbh) {
        QueryWrapper<DataCrkywCplrkDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rkbh", rkbh);
        queryWrapper.eq("isstaging","1");
        queryWrapper.last("limit 1");
        return super.getOne(queryWrapper) != null;
    }

}
