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.unis.crk.aop.SystemCountryLog;
import com.unis.crk.aop.SystemLog;
import com.unis.crk.business.qcrk.entity.DataCrkywRkcmDefault;
import com.unis.crk.business.qcrk.entity.vo.DataCrkywCmzDefaultVo;
import com.unis.crk.business.qcrk.entity.vo.DataCrkywRkcmDefaultVo;
import com.unis.crk.business.qcrk.entity.vo.Qcrk;
import com.unis.crk.business.qcrk.mapper.DataCrkywRkcmDefaultMapper;
import com.unis.crk.business.qcrk.service.*;
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.boot.autoconfigure.AutoConfigureOrder;
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-11
 */
@Service
public class DataCrkywRkcmDefaultServiceImpl extends ServiceImpl<DataCrkywRkcmDefaultMapper, DataCrkywRkcmDefault> implements IDataCrkywRkcmDefaultService {

    @Resource
    private DataCrkywRkcmDefaultMapper dataCrkywRkcmDefaultMapper;
    @Autowired
    private IBizflowtrailService bizflowtrailService;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;

    @Autowired
    IDataCrkywRmdjDefaultService dataCrkywRmdjDefaultService;
    @Autowired
    IDataCrkywQyxxDefaultService dataCrkywQyxxDefaultService;
    @Autowired
    IDataCrkywJyxxDefaultService dataCrkywJyxxDefaultService;
    @Autowired
    IDataCrkywCmzDefaultService dataCrkywCmzDefaultService;
    @Autowired
    IDataCrkywCpzDefaultService dataCrkywCpzDefaultService;
    @Autowired
    IDataCrkywJsxxDefaultService dataCrkywJsxxDefaultService;
    /**
     * 通过单位号检查是否已经存在
     *
     * @param bizNo
     * @return
     */
    private boolean isExist(String bizNo) {
        QueryWrapper<DataCrkywRkcmDefault> 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")
    @SystemCountryLog(module = "原粮入库新增出门", methods = "新增",uploadName = "yuliang.rk")
    public JSONObject save(Qcrk qcrk) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        DataCrkywRkcmDefault entity = qcrk.getDataCrkywRkcmDefault();
        if (isExist(entity.getBizNo())){
            jsonObject.set("msg", "此单据号已存在");
            return jsonObject;
        }
        entity.setSytelInfoID("4028814763a546b20163aa7a7fda0012"); //样式id
        entity.setPeriodID("11"); //期间id
        entity.setDeptID(entity.getUnitID());
        entity.setRoundID(0); //舍位id
        entity.setShowOrder(0);
        entity.setBuildDate(new Date());
        entity.setModifyDate(new Date());
        entity.setPreOrder(6);
        if (StringUtils.isBlank(entity.getBuilder())){
            entity.setBuilder(entity.getUnitID());
            entity.setEditor(entity.getUnitID());
        }
        if (!super.save(entity)) { //保存汽车入库-出门表表成功
            jsonObject.set("msg", "保存汽车入库-出门表失败");
            return jsonObject;
        }

        if (!saveBizflowtrailEnt(qcrk)) { //保存轨迹表
            jsonObject.set("msg", "保存轨迹表失败");
            throw new Exception("保存轨迹表失败");
//        return  jsonObject;
        }
        jsonObject.set("success", true);
        //为上报国家局
        jsonObject.set("dataId", entity.getDataID());
        jsonObject.set("bizNo", entity.getBizNo());
        jsonObject.set("msg", "保存成功");
        return jsonObject;
    }
    /**
     * 保存汽车出库数据
     *
     * @param qcrk 汽车出库业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveQcrk(Qcrk qcrk) throws Exception {
        JSONObject jsonObject = new JSONObject();
        //保存入门数据
        jsonObject = dataCrkywRmdjDefaultService.save(qcrk);
        if (!jsonObject.getBool("success")){
            return jsonObject;
        }
        //保存扦样数据
        jsonObject = dataCrkywQyxxDefaultService.save(qcrk);
        if (!jsonObject.getBool("success")){
            return jsonObject;
        }
        //保存化验数据
        jsonObject = dataCrkywJyxxDefaultService.save(qcrk);
        if (!jsonObject.getBool("success")){
            return jsonObject;
        }
        //保存称毛重数据
        jsonObject = dataCrkywCmzDefaultService.save(qcrk);
        if (!jsonObject.getBool("success")){
            return jsonObject;
        }
        jsonObject = dataCrkywCpzDefaultService.save(qcrk);
        if (!jsonObject.getBool("success")){
            return jsonObject;
        }
        //保存结算数据
        jsonObject = dataCrkywJsxxDefaultService.save(qcrk);
        if (!jsonObject.getBool("success")){
            return jsonObject;
        }
        //保存出门数据
        jsonObject = this.save(qcrk);
        if (!jsonObject.getBool("success")){
            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")
    @SystemCountryLog(module = "原粮入库修改出门", methods = "修改",uploadName = "yuliang.rk")
    public JSONObject update(Qcrk qcrk) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        //查询下一环节是否已处理
        DataCrkywRkcmDefault entity = qcrk.getDataCrkywRkcmDefault();
        String bizNo = qcrk.getBizflowtrail().getBillNo();
        String unitId = entity.getUnitID();
        Integer NextBizNodeID = 7; //下一个节点
        //条件查询器
        QueryWrapper<Bizflowtrail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BillNo", bizNo);
        queryWrapper.eq("UnitID", unitId);
        queryWrapper.eq("NextBizNodeID", NextBizNodeID); //下一个节点
        queryWrapper.last("limit 1");
        Bizflowtrail bizflowtrail = bizflowtrailService.getOne(queryWrapper);
        if (bizflowtrail == null) {
            jsonObject.set("msg", "轨迹表数据已被删除，请联系管理员");
            return jsonObject;
        }
        entity.setModifyDate(new Date());
        if (!super.updateById(entity)) { //修改汽车入库-出门表表成功
            jsonObject.set("msg", "保存汽汽车入库-出门表失败");
            throw new Exception("保存汽汽车入库");
//        return  jsonObject;
        }
        jsonObject.set("success", true);
        jsonObject.set("dataId", entity.getDataID());
        jsonObject.set("bizNo", bizNo);
        jsonObject.set("msg", "保存成功");
        return jsonObject;
    }

    /**
     * 删除汽车入库-出门表数据
     *
     * @param id 汽车入库-出门表主键尖
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
//    @SystemLog(module = "原粮入库删除出门", methods = "删除",uploadName = "yuliang.rk")
    @SystemCountryLog(module = "原粮入库删除出门", methods = "删除",uploadName = "yuliang.rk")
    public JSONObject delete(String id) throws Exception {
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("success", false);
            //得到对象
            DataCrkywRkcmDefault entity = super.getById(id);
            if (entity == null) {
                jsonObject.set("msg", "此数据已被删除");
                return jsonObject;
            }
            String bizNo = entity.getBizNo();
            String unitId = entity.getUnitID();
            Integer NextBizNodeID = 7; //下一个节点
            //条件查询器
            QueryWrapper<Bizflowtrail> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("BillNo", bizNo);
            deleteWrapper.eq("UnitID", unitId);
            deleteWrapper.eq("NextBizNodeID", NextBizNodeID); //下一个节点
            deleteWrapper.last("limit 1");
            Bizflowtrail bizflowtrail = bizflowtrailService.getOne(deleteWrapper);
            if (bizflowtrail == null) {
                jsonObject.set("msg", "轨迹表数据已被删除，请联系管理员");
                return jsonObject;
            }
            if (!super.removeById(id)) {
                jsonObject.set("msg", "删除汽车入库-出门表数据失败");
                return jsonObject;
            }
            //修改当前节点状态为0
            UpdateWrapper<Bizflowtrail> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("BillNo", bizNo);
            updateWrapper.eq("UnitID", unitId);
            updateWrapper.eq("NextBizNodeID", NextBizNodeID );
            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_rkcm_default",unitId,new Date());
            jsonObject.set("success", true);
            jsonObject.set("dataId", entity.getDataID());
            jsonObject.set("bizNo", entity.getBizNo());
            jsonObject.set("msg", "删除成功");
            return jsonObject;
        }
    }

    /**
     * 按照条件查询汽车入库-出门表信息
     *
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String, Object>> findPageVo(DataCrkywRkcmDefaultVo pageQuery) {
        {
            //条形查询器
            QueryWrapper<DataCrkywRkcmDefault> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(pageQuery.getUnitId())) {
                queryWrapper.eq("DATA_CRKYW_RKCM_DEFAULT.UnitId", pageQuery.getUnitId());
            }
            if (StringUtils.isNotBlank(pageQuery.getBizNo())) {
                queryWrapper.like("DATA_CRKYW_RKCM_DEFAULT.bizNo", ResultUtil.getQueryWrapperformat(pageQuery.getBizNo()));
            }
            if (StringUtils.isNotBlank(pageQuery.getSlr())) {
                queryWrapper.like("DATA_CRKYW_RMDJ_DEFAULT.slr", ResultUtil.getQueryWrapperformat(pageQuery.getSlr()));
            }
            if (StringUtils.isNotBlank(pageQuery.getCyr())) {
                queryWrapper.like("DATA_CRKYW_RMDJ_DEFAULT.cyr", ResultUtil.getQueryWrapperformat(pageQuery.getCyr()));
            }
            if (StringUtils.isNotBlank(pageQuery.getCydw())){
                queryWrapper.like("DATA_CRKYW_RMDJ_DEFAULT.cydw",ResultUtil.getQueryWrapperformat(pageQuery.getCydw()));
            }
            if (StringUtils.isNotBlank(pageQuery.getCph())) {
                queryWrapper.like("DATA_CRKYW_RMDJ_DEFAULT.cph", ResultUtil.getQueryWrapperformat(pageQuery.getCph()));
            }
            if (StringUtils.isNotBlank(pageQuery.getCmsjStart()) && StringUtils.isNotBlank(pageQuery.getCmsjEnd())) {
                queryWrapper.apply(" DATE_FORMAT(ifnull(DATA_CRKYW_RKCM_DEFAULT.cmsj,NOW()),'%Y-%m-%d') >=  '" + pageQuery.getCmsjStart() + "' AND DATE_FORMAT(ifnull(DATA_CRKYW_RKCM_DEFAULT.cmsj,NOW()),'%Y-%m-%d') <= '" + pageQuery.getCmsjEnd() + " 23:59:59'");

            }
            //排序
            queryWrapper.orderByDesc("DATA_CRKYW_RKCM_DEFAULT.BuildDate");

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

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

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

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

    private Boolean saveBizflowtrailEnt(Qcrk qcrk) {
        DataCrkywRkcmDefault dataCrkywRkcmDefault = qcrk.getDataCrkywRkcmDefault();
        String bizNo = dataCrkywRkcmDefault.getBizNo(); //单据号
        String unitId = dataCrkywRkcmDefault.getUnitID(); //单位ID
        Integer curBizNodeID = 6; //当前节点
        Integer nextBizNodeID = 7; //下一节点
        Integer bizNodeId = 7; //  report表节点id
        Integer trailOrder = 6;
        //更新上一环节业务数据
        //查询是否是终止入库
        QueryWrapper<Bizflowtrail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("BillNo", bizNo);
        queryWrapper.eq("UnitID", unitId);
        queryWrapper.eq("CurBizNodeID", curBizNodeID);
        queryWrapper.eq("NextBizNodeID", nextBizNodeID);
        queryWrapper.eq("BizNodeId", bizNodeId);
        queryWrapper.eq("TrailOrder", trailOrder);
        List<Bizflowtrail> bizflowtrailList = bizflowtrailService.list(queryWrapper);
        if (bizflowtrailList.size() < 1){ //表示是终止业务
            curBizNodeID = 3;
            trailOrder = 3;
        }
        //更新查询器
        UpdateWrapper<Bizflowtrail> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("BillNo", bizNo);
        updateWrapper.eq("UnitID", unitId);
        updateWrapper.eq("CurBizNodeID", curBizNodeID);
        updateWrapper.eq("NextBizNodeID", nextBizNodeID);
        updateWrapper.eq("BizNodeId", bizNodeId);
        updateWrapper.eq("TrailOrder", trailOrder);
        updateWrapper.set("status", 100); //修改状态，完成
        if (!bizflowtrailService.update(updateWrapper)) { //更新轨迹表
            return false;
        }
        return true;
    }
}
