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.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.DataCrkywCkrmdjDefault;
import com.unis.crk.business.qcck.entity.vo.DataCrkywCkrmdjDefaultVo;
import com.unis.crk.business.qcck.entity.vo.Qcck;
import com.unis.crk.business.qcck.mapper.DataCrkywCkrmdjDefaultMapper;
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.Map;

/**
 * <p>
 * 汽车出库-入门表 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2021-10-22
 */
@Service
public class DataCrkywCkrmdjDefaultServiceImpl extends ServiceImpl<DataCrkywCkrmdjDefaultMapper, DataCrkywCkrmdjDefault> implements IDataCrkywCkrmdjDefaultService {

    @Resource
    private DataCrkywCkrmdjDefaultMapper dataCrkywCkrmdjDefaultMapper;
    @Autowired
    IBizflowtrailService bizflowtrailService;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;
    /**
     * 通过单位号检查是否已经存在
     *
     * @param bizNo
     * @return
     */
    private boolean isExist(String bizNo) {
        QueryWrapper<DataCrkywCkrmdjDefault> 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);
        DataCrkywCkrmdjDefault dataCrkywRmdjDefault = qcck.getDataCrkywCkrmdjDefault();
        if (isExist(dataCrkywRmdjDefault.getBizNo())){
            jsonObject.set("msg","此单据号已存在");
            return jsonObject;
        }
        dataCrkywRmdjDefault.setSytelInfoID("4028814763a546b20163aab53ee8001a"); //样式id
        dataCrkywRmdjDefault.setPeriodID("11"); //期间id
        dataCrkywRmdjDefault.setDeptID(dataCrkywRmdjDefault.getUnitID());
        dataCrkywRmdjDefault.setRoundID(0); //舍们id
        dataCrkywRmdjDefault.setShoworder(0);
        dataCrkywRmdjDefault.setPreorder(0);
        dataCrkywRmdjDefault.setDjsj(dataCrkywRmdjDefault.getRmsj());
        if (StringUtils.isBlank(dataCrkywRmdjDefault.getBuilder())){
            dataCrkywRmdjDefault.setBuilder(dataCrkywRmdjDefault.getUnitID());
            dataCrkywRmdjDefault.setEditor(dataCrkywRmdjDefault.getUnitID());
        }
        if (!super.save(dataCrkywRmdjDefault)) { //保存汽车入门表成功
            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);
        //查询下一环节是否已处理
        DataCrkywCkrmdjDefault dataCrkywCkrmdjDefault = qcck.getDataCrkywCkrmdjDefault();
        String bizNo = dataCrkywCkrmdjDefault.getBizNo();
        String unitId = dataCrkywCkrmdjDefault.getUnitID();
        Integer curBizNodeID = 1; //当前节点
        //条件查询器
        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 (!super.updateById(dataCrkywCkrmdjDefault)) { //修改汽车出库入门成功
            jsonObject.set("msg","修改汽车出库入门失败");
            return  jsonObject;
        }
        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);

        //得到对象
        DataCrkywCkrmdjDefault dataCrkywRmdjDefault = super.getById(id);
        if (dataCrkywRmdjDefault == null){
            jsonObject.set("msg","此数据已被删除");
            return  jsonObject;
        }
        String bizNo = dataCrkywRmdjDefault.getBizNo();
        String unitId = dataCrkywRmdjDefault.getUnitID();
        Integer curBizNodeID = 1; //当前节点
        //条件查询器
        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)) { //删除汽车出库入门表成功
            jsonObject.set("msg","删除汽车入出库中门失败");
            return  jsonObject;
        }
        if (!bizflowtrailService.remove(deleteWrapper)) { //删除轨迹表
            jsonObject.set("msg","删除轨迹表失败");
            throw  new Exception("删除轨迹表失败");
//            return  jsonObject;
        }
        //保存删除数据记录
        deleteDataRecordService.save(id,"data_crkyw_ckrmdj_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(DataCrkywCkrmdjDefaultVo pageQuery){
        {
            //条形查询器
            QueryWrapper<DataCrkywCkrmdjDefault> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(pageQuery.getUnitId())) {
                queryWrapper.eq("a.UnitId", pageQuery.getUnitId());
            }
            if (StringUtils.isNotBlank(pageQuery.getBizNo())) {
                queryWrapper.like("a.bizNo", ResultUtil.getQueryWrapperformat(pageQuery.getBizNo()));
            }
            if (StringUtils.isNotBlank(pageQuery.getLspz())) {
                queryWrapper.like("a.lspz", ResultUtil.getQueryWrapperformat(pageQuery.getLspz()));
            }
            if (StringUtils.isNotBlank(pageQuery.getCyr())) {
                queryWrapper.like("a.cyr", ResultUtil.getQueryWrapperformat(pageQuery.getCyr()));
            }
            if (StringUtils.isNotBlank(pageQuery.getSlr())) {
                queryWrapper.like("a.slr", ResultUtil.getQueryWrapperformat(pageQuery.getSlr()));
            }
            if (StringUtils.isNotBlank(pageQuery.getCydw())){
                queryWrapper.like("a.cydw",ResultUtil.getQueryWrapperformat(pageQuery.getCydw()));
            }
            if (StringUtils.isNotBlank(pageQuery.getCph())) {
                queryWrapper.like("a.cph", ResultUtil.getQueryWrapperformat(pageQuery.getCph()));
            }
            if (StringUtils.isNotBlank(pageQuery.getDjsjStart()) && StringUtils.isNotBlank(pageQuery.getDjsjEnd())) {
                queryWrapper.apply(" DATE_FORMAT(ifnull(a.rmsj,NOW()),'%Y-%m-%d') >=  '" + pageQuery.getDjsjStart() + "' AND DATE_FORMAT(ifnull(a.rmsj,NOW()),'%Y-%m-%d') <= '" + pageQuery.getDjsjEnd() + " 23:59:59'");
            }
            //排序
            queryWrapper.orderByDesc("a.ModifyDate");

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

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

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


    private boolean saveBizflowtrailEnt(Qcck qcck){
        Bizflowtrail bizflowtrail = new Bizflowtrail();
        DataCrkywCkrmdjDefault dataCrkywCkrmdjDefault= qcck.getDataCrkywCkrmdjDefault();
        String flowId = qcck.getBizflowtrail().getFlowID(); //流程id
        String bizNo = dataCrkywCkrmdjDefault.getBizNo(); //单据号
        String unitId = dataCrkywCkrmdjDefault.getUnitID(); //单位ID
        Integer curBizNodeID = 1; //当前节点
        Integer nextBizNodeID = 2; //下一节点
        Integer bizNodeId = 9; //  report表节点id
        Integer trailOrder = 1;
        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);

        return bizflowtrailService.save(bizflowtrail);
    }
}
