package com.unis.crk.business.qcck.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.unis.crk.aop.SystemLog;
import com.unis.crk.business.qcck.entity.DataCrkywCkcpzDefault;
import com.unis.crk.business.qcck.entity.DataCrkywCkrmdjDefault;
import com.unis.crk.business.qcck.entity.vo.DataCrkywCkcpzDefaultVo;
import com.unis.crk.business.qcck.entity.vo.Qcck;
import com.unis.crk.business.qcck.mapper.DataCrkywCkcpzDefaultMapper;
import com.unis.crk.business.qcck.service.IDataCrkywCkcpzDefaultService;
import com.unis.crk.business.qcck.service.IDataCrkywCkrmdjDefaultService;
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.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 汽车出库-称皮重表 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2021-10-22
 */
@Service
public class DataCrkywCkcpzDefaultServiceImpl extends ServiceImpl<DataCrkywCkcpzDefaultMapper, DataCrkywCkcpzDefault> implements IDataCrkywCkcpzDefaultService {

    @Resource
    private DataCrkywCkcpzDefaultMapper dataCrkywCkcpzDefaultMapper;
    @Autowired
    private IBizflowtrailService bizflowtrailService;
    @Autowired
    private IDataCrkywCkrmdjDefaultService dataCrkywCkrmdjDefaultService;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;
    /**
     * 通过单位号检查是否已经存在
     *
     * @param bizNo
     * @return
     */
    private boolean isExist(String bizNo) {
        QueryWrapper<DataCrkywCkcpzDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BizNo", bizNo);
        queryWrapper.last("limit 0,1");
        return super.getOne(queryWrapper) != null;
    }
    /**
     *保存汽车出库-称皮重表
     * @param qcck 汽车出库-称皮重表业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SystemLog(module = "原粮出库皮重", methods = "新增",uploadName = "yuliang.ck")
    public JSONObject save(Qcck qcck)throws  Exception{
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        DataCrkywCkcpzDefault entity = qcck.getDataCrkywCkcpzDefault();
        if (isExist(entity.getBizNo())){
            jsonObject.set("msg","此单据号已存在");
            return jsonObject;
        }
        entity.setSytelInfoID("4028814763a546b20163aade294b001d"); //样式id
        entity.setPeriodID("11"); //期间id
        entity.setDeptID(entity.getUnitID());
        entity.setRoundID(0); //舍们id
        entity.setShoworder(0);
        entity.setPreorder(1);
        if (StringUtils.isBlank(entity.getBuilder())){
            entity.setBuilder(entity.getUnitID());
            entity.setEditor(entity.getUnitID());
        }
        if (!dataCrkywCkrmdjDefaultService.updateById(qcck.getDataCrkywCkrmdjDefault())) { //保存汽车出库入门表成功
            throw  new Exception("保存汽车出库入门失败");
        }
        if (!super.save(entity)) { //保存汽车称皮重表成功
            throw  new Exception("保存汽车出库称皮重失败");
        }


        if (!saveBizflowtrailEnt(qcck)) { //保存轨迹表
//            jsonObject.set("msg","保存轨迹表失败");
            throw  new Exception("保存轨迹表失败");
//            return  jsonObject;
        }
        jsonObject.set("success",true);
        jsonObject.set("msg","保存成功");
        return jsonObject;
    }
    /**
     *修改汽车出库-称皮重表
     * @param qcck 汽车出库-称皮重表业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SystemLog(module = "原粮出库皮重", methods = "修改",uploadName = "yuliang.ck")
    public JSONObject update(Qcck qcck) throws  Exception{
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        //查询下一环节是否已处理
        DataCrkywCkcpzDefault dataCrkywCkcpzDefault = qcck.getDataCrkywCkcpzDefault();
        String bizNo = dataCrkywCkcpzDefault.getBizNo();
        String unitId = dataCrkywCkcpzDefault.getUnitID();
        Integer curBizNodeID = 2; //当前节点
        //条件查询器
        QueryWrapper<Bizflowtrail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BillNo",bizNo);
        queryWrapper.eq("UnitID",unitId);
        queryWrapper.eq("CurBizNodeID",curBizNodeID); //当前节点
        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","当前车辆已完成[称毛重]，不能修改");
            return  jsonObject;
        }
        if (!dataCrkywCkrmdjDefaultService.updateById(qcck.getDataCrkywCkrmdjDefault())) { //保存汽车出库入门表成功
            throw  new Exception("保存汽车出库入门失败");
        }
        if (!super.updateById(dataCrkywCkcpzDefault)) { //修改汽车出库称皮重成功
            throw  new Exception("修改汽车出库称皮重失败");
        }

        jsonObject.set("success",true);
        jsonObject.set("msg","保存成功");
        return jsonObject;
    }
    /**
     *删除汽车出库-称皮重表数据
     * @param id 汽车出库-称皮重表主键尖
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SystemLog(module = "原粮出库皮重", methods = "删除",uploadName = "yuliang.ck")
    public JSONObject delete(String id) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);

        //得到对象
        DataCrkywCkcpzDefault dataCrkywCkcpzDefault = super.getById(id);
        if (dataCrkywCkcpzDefault == null){
            jsonObject.set("msg","此数据已被删除");
            return  jsonObject;
        }
        String bizNo = dataCrkywCkcpzDefault.getBizNo();
        String unitId = dataCrkywCkcpzDefault.getUnitID();
        Integer curBizNodeID = 2; //当前节点
        //条件查询器
        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){
            jsonObject.set("msg","轨迹表数据已被删除，请联系管理员");
            return  jsonObject;
        }
        if (bizflowtrail.getStatus() == 1 || bizflowtrail.getStatus() == 100){ //表示已经执行后面业务，不能删除
            jsonObject.set("msg","当前车辆已完成[称皮重]，不能删除");
            return  jsonObject;
        }
        if (!super.removeById(id)) { //删除汽车出库称皮重表成功
            throw  new Exception("删除汽车入出库中门失败-入门数据失败");
        }

        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;
        }
        //操作成功后，再处理入门业务数据
        if (dataCrkywCkcpzDefaultMapper.updateCkRmdj(bizNo)){

        }
        //保存删除数据记录
        deleteDataRecordService.save(id,"data_crkyw_ckcpz_default",unitId,new Date());
        deleteDataRecordService.save(bizflowtrail.getTrailID(),"bizflowtrail",unitId,new Date());

        jsonObject.set("success",true);
        jsonObject.set("msg","删除成功");
        return jsonObject;
    }

    /**
     * 按照条件查询汽车出库-称皮重表信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataCrkywCkcpzDefaultVo pageQuery){
        {
            //条形查询器
            QueryWrapper<DataCrkywCkcpzDefault> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(pageQuery.getUnitId())) {
                queryWrapper.eq("DATA_CRKYW_CKRMDJ_DEFAULT.UnitId", pageQuery.getUnitId());
            }
            if (StringUtils.isNotBlank(pageQuery.getBizNo())) {
                queryWrapper.like("DATA_CRKYW_CKRMDJ_DEFAULT.bizNo", ResultUtil.getQueryWrapperformat(pageQuery.getBizNo()));
            }
            if (StringUtils.isNotBlank(pageQuery.getLspz())) {
                queryWrapper.like("DATA_CRKYW_CKRMDJ_DEFAULT.lspz", ResultUtil.getQueryWrapperformat(pageQuery.getLspz()));
            }
            if (StringUtils.isNotBlank(pageQuery.getSlr())) {
                queryWrapper.like("DATA_CRKYW_CKRMDJ_DEFAULT.slr", ResultUtil.getQueryWrapperformat(pageQuery.getSlr()));
            }
            if (StringUtils.isNotBlank(pageQuery.getCyr())) {
                queryWrapper.like("DATA_CRKYW_CKRMDJ_DEFAULT.cyr", ResultUtil.getQueryWrapperformat(pageQuery.getCyr()));
            }
            if (StringUtils.isNotBlank(pageQuery.getCydw())){
                queryWrapper.like("DATA_CRKYW_CKRMDJ_DEFAULT.cydw",ResultUtil.getQueryWrapperformat(pageQuery.getCydw()));
            }
            if (StringUtils.isNotBlank(pageQuery.getCph())) {
                queryWrapper.like("DATA_CRKYW_CKRMDJ_DEFAULT.cph", ResultUtil.getQueryWrapperformat(pageQuery.getCph()));
            }
            if (StringUtils.isNotBlank(pageQuery.getCpzsjStart()) && StringUtils.isNotBlank(pageQuery.getCpzsjEnd())) {
                queryWrapper.apply(" DATE_FORMAT(ifnull(jpsj,NOW()),'%Y-%m-%d') >=  '" + pageQuery.getCpzsjStart() + "' AND DATE_FORMAT(ifnull(jpsj,NOW()),'%Y-%m-%d') <= '" + pageQuery.getCpzsjEnd() + " 23:59:59'");
            }
            //排序
            queryWrapper.orderByDesc("DATA_CRKYW_CKCPZ_DEFAULT.BuildDate");

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

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

    @Override
    public Map<String, Object> getOne(String bizNo, String id) {
        return dataCrkywCkcpzDefaultMapper.getOne(bizNo,id);
    }


    private boolean saveBizflowtrailEnt(Qcck qcck){
        Bizflowtrail bizflowtrail = new Bizflowtrail();
        DataCrkywCkcpzDefault dataCrkywCkrmdjDefault= qcck.getDataCrkywCkcpzDefault();
        String flowId = qcck.getBizflowtrail().getFlowID(); //流程id
        String bizNo = dataCrkywCkrmdjDefault.getBizNo(); //单据号
        String unitId = dataCrkywCkrmdjDefault.getUnitID(); //单位ID
        Integer curBizNodeID = 2; //当前节点
        Integer nextBizNodeID = 3; //下一节点
        Integer bizNodeId = 11; //  report表节点id
        Integer trailOrder = 2;
        String builder = dataCrkywCkrmdjDefault.getBuilder(); //创建人
        Integer showOrder = dataCrkywCkrmdjDefault.getShoworder(); //序号

        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", nextBizNodeID - 1);
        updateWrapper.eq("BizNodeId", 9);
        updateWrapper.eq("TrailOrder", trailOrder - 1);
        updateWrapper.set("status", 1); //修改状态
        updateWrapper.set("UPDATE_TIME", null); //上传时间设置为空
        if (!bizflowtrailService.update(updateWrapper)) { //更新轨迹表
            return false;
        }
        return true;
    }
        @Override
        public List<Map<String, Object>> getPerData(DataCrkywCkcpzDefaultVo pageQuery) {
            List<Map<String,Object>> list = dataCrkywCkcpzDefaultMapper.getPerData(pageQuery);
        return list;
        }
}
