package com.unis.crk.business.qcrk.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.sun.corba.se.spi.ior.ObjectKey;
import com.unis.crk.aop.SystemLog;
import com.unis.crk.business.qcrk.entity.DataCrkywJyxxDefault;
import com.unis.crk.business.qcrk.entity.DataCrkywJyxxFlt001;
import com.unis.crk.business.qcrk.entity.vo.DataCrkywJyxxDefaultVo;
import com.unis.crk.business.qcrk.entity.vo.DataCrkywQyxxDefaultVo;
import com.unis.crk.business.qcrk.entity.vo.Qcrk;
import com.unis.crk.business.qcrk.mapper.DataCrkywJyxxDefaultMapper;
import com.unis.crk.business.qcrk.service.IDataCrkywJyxxDefaultService;
import com.unis.crk.business.qcrk.service.IDataCrkywJyxxFlt001Service;
import com.unis.crk.common.entity.Bizflowtrail;
import com.unis.crk.common.service.IBizflowtrailService;
import com.unis.crk.common.service.IDeleteDataRecordService;
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.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 汽车入库-检验主表 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2021-10-11
 */
@Service
public class DataCrkywJyxxDefaultServiceImpl extends ServiceImpl<DataCrkywJyxxDefaultMapper, DataCrkywJyxxDefault> implements IDataCrkywJyxxDefaultService {

    @Resource
    private DataCrkywJyxxDefaultMapper dataCrkywJyxxDefaultMapper;
    @Autowired
    private IBizflowtrailService bizflowtrailService;
    @Autowired
    private IDataCrkywJyxxFlt001Service dataCrkywJyxxFlt001Service;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;
    /**
     * 通过单位号检查是否已经存在
     *
     * @param bizNo
     * @return
     */
    private boolean isExist(String bizNo) {
        QueryWrapper<DataCrkywJyxxDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BizNo", bizNo);
        queryWrapper.last("limit 1");
        return super.getOne(queryWrapper) != null;
    }
    /**
     *保存汽车入库-检验主表
     * @param qcrk 汽车入库-检验主表业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SystemLog(module = "原粮入库新增检验", methods = "新增",uploadName = "yuliang.rk")
    public JSONObject save(Qcrk qcrk)throws  Exception{
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("success",false);
            DataCrkywJyxxDefault entity = qcrk.getDataCrkywJyxxDefault();
            if (isExist(entity.getBizno())){
                jsonObject.set("msg","此单据号已存在");
                return jsonObject;
            }
            String unitId = entity.getUnitID();
            entity.setSytelInfoID("402881476395411d0163964a2b57000b"); //样式id
            entity.setPeriodID("11"); //期间id
            entity.setDeptID(unitId); //部门id
            entity.setRoundID(0); //舍位id
            entity.setShoworder(0);
            entity.setPreorder(2);
            if (StringUtils.isBlank(entity.getBuilder())){
                entity.setBuilder(entity.getUnitID());
                entity.setEditor(entity.getUnitID());
            }
            boolean b = super.saveOrUpdate(entity);
            if (!b) { //保存汽车化验主表成功
                jsonObject.set("msg","保存汽车化验主表数据失败");
                return  jsonObject;

            }

            //保存从表信息
            List<DataCrkywJyxxFlt001> fltList = qcrk.getDataCrkywJyxxDefault().getFltList();
            if (!fltList.isEmpty()){
                String id = entity.getDataID();

                for (int i = 0; i < fltList.size(); i++) {
                    DataCrkywJyxxFlt001 dataCrkywJyxxFlt001 = fltList.get(i);
                    dataCrkywJyxxFlt001.setSytelInfoID("402881476395411d0163964a2b57000b");
                    dataCrkywJyxxFlt001.setPeriodID("11");
                    dataCrkywJyxxFlt001.setMainDataID(id);
                    dataCrkywJyxxFlt001.setDeptID(unitId); //部门id
                    dataCrkywJyxxFlt001.setUnitID(unitId); //
                    dataCrkywJyxxFlt001.setRoundID(0); //舍位id
                    if (StringUtils.isBlank(dataCrkywJyxxFlt001.getBuilder())){
                        dataCrkywJyxxFlt001.setBuilder(unitId);
                        dataCrkywJyxxFlt001.setEditor(unitId);
                    }
                }
                if (!dataCrkywJyxxFlt001Service.saveOrUpdateBatch(fltList)) { //保存汽车化验从表成功
                    jsonObject.set("msg","保存汽车化验从表数据失败");
                    throw new  Exception("保存汽车化验从表数据失败");
//                    return  jsonObject;
                }
            }
            if (!saveBizflowtrailEnt(qcrk)) { //保存轨迹表
            jsonObject.set("msg","保存轨迹表失败");
             throw new Exception("保存轨迹表失败");
//            return  jsonObject;
        }
            jsonObject.set("success",true);
            jsonObject.set("msg","保存成功");
            return jsonObject;
        }
    }
    /**
     *修改汽车入库-检验主表
     * @param qcrk 汽车入库-检验主表业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SystemLog(module = "原粮入库修改检验", methods = "修改",uploadName = "yuliang.rk")
    public JSONObject update(Qcrk qcrk) throws  Exception{
        {
            {
                JSONObject jsonObject = new JSONObject();
                jsonObject.set("success",false);
                DataCrkywJyxxDefault dataCrkywJyxxDefault = qcrk.getDataCrkywJyxxDefault();
                dataCrkywJyxxDefault.setUpdateTime(null);
                //条件查询器
                QueryWrapper<Bizflowtrail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("BillNo",dataCrkywJyxxDefault.getBizno());
                queryWrapper.eq("UnitID",dataCrkywJyxxDefault.getUnitID());
                queryWrapper.eq("CurBizNodeID",3); //当前节点
                queryWrapper.last("limit 1");
                Bizflowtrail bizflowtrail = bizflowtrailService.getOne(queryWrapper);
                if (bizflowtrail == null){
                    jsonObject.set("msg","轨迹表数据已被删除，请联系管理员");
                    return  jsonObject;
                }
                if (bizflowtrail.getStatus() == 1 || bizflowtrail.getStatus() == 100){ //表示已经执行后面业务，不能删除
                    jsonObject.set("msg","当前车辆已完成[称毛重]，不能修改");
                    if (bizflowtrail.getNextBizNodeID() == 7){ //表示是终止流程，直接出门
                        jsonObject.set("msg","当前车辆已完成[入库出门]，不能修改");
                    }
                    return  jsonObject;
                }
                if (!super.updateById(dataCrkywJyxxDefault)) { //保存汽车化验主表成功
                    jsonObject.set("msg","保存汽车化验主表数据失败");
                    return  jsonObject;
                }
                //删除从表相关信息
                //条件查询器
                QueryWrapper<DataCrkywJyxxFlt001> deleteWrapper = new QueryWrapper<>();
                deleteWrapper.eq("MainDataId",dataCrkywJyxxDefault.getDataID());
                if (dataCrkywJyxxFlt001Service.list(deleteWrapper).size() > 0){ //表示有从表数据
                    if (!dataCrkywJyxxFlt001Service.remove(deleteWrapper)) { //删除轨迹表
                        throw  new Exception("删除化验从表旧数据失败");
//                    return  jsonObject;
                    }
                }

                //保存从表信息
                String unitId = dataCrkywJyxxDefault.getDataID();
                List<DataCrkywJyxxFlt001> fltList = dataCrkywJyxxDefault.getFltList();
                if (!fltList.isEmpty()){
                    String id_ = dataCrkywJyxxDefault.getDataID();
                    for (int i = 0; i < fltList.size(); i++) {
                        DataCrkywJyxxFlt001 dataCrkywJyxxFlt001 = fltList.get(i);
                        dataCrkywJyxxFlt001.setMainDataID(id_);
                        dataCrkywJyxxFlt001.setSytelInfoID("402881476395411d0163964a2b57000b");
                        dataCrkywJyxxFlt001.setPeriodID("11");
                        dataCrkywJyxxFlt001.setDeptID(unitId); //部门id
                        dataCrkywJyxxFlt001.setUnitID(unitId); //
                        dataCrkywJyxxFlt001.setRoundID(0); //舍位id
                        if (StringUtils.isBlank(dataCrkywJyxxFlt001.getBuilder())){
                            dataCrkywJyxxFlt001.setBuilder(unitId);
                            dataCrkywJyxxFlt001.setEditor(unitId);
                        }
                    }
                    if (!dataCrkywJyxxFlt001Service.saveOrUpdateBatch(fltList)) { //保存汽车化验从表成功
                        jsonObject.set("msg","保存汽车化验从表数据失败");
                        throw  new Exception("保存汽车化验从表数据失败");
//                        return  jsonObject;
                    }
                }
                jsonObject.set("success",true);
                jsonObject.set("msg","保存成功");
                return jsonObject;
            }
        }
    }
    /**
     *删除汽车入库-检验主表数据
     * @param id 汽车入库-检验主表主键尖
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SystemLog(module = "原粮入库删除检验", methods = "删除",uploadName = "yuliang.rk")
    public JSONObject delete(String id) throws  Exception{
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("success",false);
            //得到对象
            DataCrkywJyxxDefault dataCrkywJyxxDefault = super.getById(id);
            if (dataCrkywJyxxDefault == null){
                jsonObject.set("msg","此数据已被删除");
                return  jsonObject;
            }
            String bizNo = dataCrkywJyxxDefault.getBizno();
            String unitId = dataCrkywJyxxDefault.getUnitID();
            Integer curBizNodeID = 3; //当前节点
            //条件查询器
            QueryWrapper<Bizflowtrail> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("BillNo",bizNo);
            deleteWrapper.eq("UnitID",unitId);
            deleteWrapper.eq("CurBizNodeID",curBizNodeID);
            deleteWrapper.last("limit 1");
            Bizflowtrail bizflowtrail = bizflowtrailService.getOne(deleteWrapper);
            if (bizflowtrail != null){
                if (bizflowtrail.getStatus() == 1 || bizflowtrail.getStatus() == 100){ //表示已经执行后面业务，不能删除
                    jsonObject.set("msg","当前车辆已完成[称毛重]，不能删除");
                    if (bizflowtrail.getNextBizNodeID() == 7){ //表示是终止流程，直接出门
                        jsonObject.set("msg","当前车辆已完成[入库出门]，不能删除");
                    }
                    return  jsonObject;
                }
            }
         //得到从表数据
        QueryWrapper<DataCrkywJyxxFlt001> deleteFltWrapper = new QueryWrapper<>();
        deleteFltWrapper.eq("MainDataID",id);
        deleteFltWrapper.eq("UnitID",unitId);
        List<DataCrkywJyxxFlt001> jyxxFlt001s = dataCrkywJyxxFlt001Service.list(deleteFltWrapper);
            if (!super.removeById(id)) { //删除成功
                jsonObject.set("msg","删除汽车检验主表数据失败");
                return  jsonObject;
            }

            if (!bizflowtrailService.remove(deleteWrapper)) { //删除轨迹表,当前节点数据
                jsonObject.set("msg","删除轨迹表数据失败");
                throw new Exception("删除轨迹表数据失败");
//                return  jsonObject;
            }
            //修改上一个节点状态为0
            UpdateWrapper<Bizflowtrail> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("BillNo",bizNo);
            updateWrapper.eq("UnitID",unitId);
            updateWrapper.eq("CurBizNodeID",curBizNodeID-1);
            updateWrapper.set("status",0);
            updateWrapper.set("UPDATE_TIME", null);
            if (!bizflowtrailService.update(updateWrapper)) {
                jsonObject.set("msg","修改上一节点轨迹数据表失败");
                throw  new Exception("修改上一节点轨迹数据表失败");
//                return  jsonObject;
            }
        //保存删除数据记录
        deleteDataRecordService.save(id,"data_crkyw_jyxx_default",unitId,new Date());
        //保存从表删除信息
        for (int i = 0; i < jyxxFlt001s.size(); i++) {
            DataCrkywJyxxFlt001 jyxxFlt001 = jyxxFlt001s.get(i);
            deleteDataRecordService.save(jyxxFlt001.getDataID(),"data_crkyw_jyxx_flt_001",unitId,new Date());
        }
        deleteDataRecordService.save(bizflowtrail.getTrailID(),"bizflowtrail",unitId,new Date());
            jsonObject.set("success",true);
            jsonObject.set("msg","删除成功");
            return jsonObject;
        }

    @Override
    public DataCrkywJyxxDefault getAllById(Serializable id) {
        DataCrkywJyxxDefault dataCrkywJyxxDefault = super.getById(id);
        if (dataCrkywJyxxDefault == null) return  null;
        //得到从表数据
        QueryWrapper<DataCrkywJyxxFlt001> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MainDataId",dataCrkywJyxxDefault.getDataID());
        dataCrkywJyxxDefault.setFltList(dataCrkywJyxxFlt001Service.list(queryWrapper));
        return dataCrkywJyxxDefault;
    }

    /**
     * 按照条件查询汽车入库-检验主表信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataCrkywJyxxDefaultVo pageQuery){
        {
        //条形查询器
        QueryWrapper<DataCrkywJyxxDefault> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(pageQuery.getUnitId())){
                queryWrapper.eq("DATA_CRKYW_JYXX_DEFAULT.UnitId",pageQuery.getUnitId());
            }
            if (StringUtils.isNotBlank(pageQuery.getBizNo())){
                queryWrapper.like("DATA_CRKYW_RMDJ_DEFAULT.bizNo", ResultUtil.getQueryWrapperformat(pageQuery.getBizNo()));
            }
            if (StringUtils.isNotBlank(pageQuery.getLspz())){
                queryWrapper.eq("DATA_CRKYW_RMDJ_DEFAULT.lspz",pageQuery.getLspz());
            }
            if (StringUtils.isNotBlank(pageQuery.getCph())){
                queryWrapper.like("DATA_CRKYW_RMDJ_DEFAULT.cph",pageQuery.getCph());
            }
            if (StringUtils.isNotBlank(pageQuery.getJysjStart()) && StringUtils.isNotBlank(pageQuery.getJysjEnd())){
                queryWrapper.apply(" DATE_FORMAT(ifnull(DATA_CRKYW_JYXX_DEFAULT.jysj,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getJysjStart()+"' AND DATE_FORMAT(ifnull(DATA_CRKYW_JYXX_DEFAULT.jysj,NOW()),'%Y-%m-%d') <= '"+pageQuery.getJysjEnd()+" 23:59:59'");
            }
            //排序
            queryWrapper.orderByDesc("DATA_CRKYW_JYXX_DEFAULT.BuildDate");

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

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

    @Override
    public List<Map<String, Object>> getPerData(DataCrkywQyxxDefaultVo pageQuery) {
        List<Map<String,Object>> list = dataCrkywJyxxDefaultMapper.getPerData(pageQuery);
        return list;
    }

    @Override
    public Map<String, Object> getOne(String bizNo,String id) {
        Map<String, Object> map = dataCrkywJyxxDefaultMapper.getOne(bizNo,id);
        if (StringUtils.isNotBlank(id)){ //修改，查看
            List<Map<String,Object>> fltList = dataCrkywJyxxFlt001Service.getLitByBizNoOrMainDatId(bizNo,id);
            map.put("fltList",fltList);
        }else{ //新增，需要从枚举中进行查询，新方式，在下拉选择品种时，动态带出

        }
        return map;
    }
    @Override
    public Map<String, Object> getYjSumByBizNo(String bizNo) {
        Map<String, Object> map = dataCrkywJyxxDefaultMapper.getYjSumByBizNo(bizNo).get(0);
        return map;
    }

    private Boolean saveBizflowtrailEnt(Qcrk qcrk){
        Bizflowtrail bizflowtrail = new Bizflowtrail();
        DataCrkywJyxxDefault dataCrkywJyxxDefault= qcrk.getDataCrkywJyxxDefault();
        String flowId = qcrk.getBizflowtrail().getFlowID(); //流程id
        String bizNo = dataCrkywJyxxDefault.getBizno(); //单据号
        String unitId = dataCrkywJyxxDefault.getUnitID(); //单位ID
        Integer curBizNodeID = 3; //当前节点
        Integer nextBizNodeID = 4; //下一节点
        Integer bizNodeId = 4; //  report表节点id
        Integer trailOrder = 3;
        String builder = dataCrkywJyxxDefault.getBuilder(); //创建人
        Integer showOrder = dataCrkywJyxxDefault.getShoworder(); //序号
        String zzyy = dataCrkywJyxxDefault.getZzyy();
        if (StringUtils.isNotBlank(zzyy)){ //是否是终止业务
            nextBizNodeID = 7;
            bizNodeId = 7;
            bizflowtrail.setNote(zzyy);
        }
        bizflowtrail.setBillNo(bizNo);
        bizflowtrail.setUnitID(unitId);
        bizflowtrail.setTrailOrder(trailOrder);
        bizflowtrail.setCurBizNodeID(curBizNodeID);
        bizflowtrail.setNextBizNodeID(nextBizNodeID);
        bizflowtrail.setBizNodeId(bizNodeId);
        bizflowtrail.setBuilder(builder);
        bizflowtrail.setBuildDate(new Date());
        bizflowtrail.setShowOrder(showOrder);
        bizflowtrail.setFlowID(flowId);
        bizflowtrail.setStatus(0);
        if (!bizflowtrailService.save(bizflowtrail)){
            return  false;
        }
        //更新上一环节业务数据
        //更新查询器
        UpdateWrapper<Bizflowtrail> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("BillNo",bizNo);
        updateWrapper.eq("UnitID",unitId);
        updateWrapper.eq("CurBizNodeID",curBizNodeID-1);
        updateWrapper.eq("NextBizNodeID",4-1);
        updateWrapper.eq("BizNodeId",2);
        updateWrapper.eq("TrailOrder",trailOrder-1);
        updateWrapper.set("status",1); //修改状态
        updateWrapper.set("UPDATE_TIME",null); //上传时间设置为空
        if (!bizflowtrailService.update(updateWrapper)) { //更新轨迹表
            return  false;
        }
        return true;
    }
}
