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

import cn.hutool.core.util.StrUtil;
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.basic.service.IBasicEnumService;
import com.unis.crk.business.qcrk.entity.*;
import com.unis.crk.business.qcrk.entity.vo.DataCrkywTzdxxDefaultVo;
import com.unis.crk.business.qcrk.entity.vo.Qcrk;
import com.unis.crk.business.qcrk.mapper.DataCrkywTzdxxDefaultMapper;
import com.unis.crk.business.qcrk.service.IDataCrkywTzdxxDefaultService;
import com.unis.crk.business.qcrk.service.IDataCrkywTzdxxFlt001Service;
import com.unis.crk.business.qcrk.service.IFlBillRelationService;
import com.unis.crk.common.mapper.BillnonewgjjMapper;
import com.unis.crk.common.service.IBillnonewgjjService;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.enums.StoreWorkType;
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 javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 汽车出入库-通知单主表 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2021-10-13
 */
@Service
public class DataCrkywTzdxxDefaultServiceImpl extends ServiceImpl<DataCrkywTzdxxDefaultMapper, DataCrkywTzdxxDefault> implements IDataCrkywTzdxxDefaultService {

    @Resource
    private DataCrkywTzdxxDefaultMapper dataCrkywTzdxxDefaultMapper;
    @Autowired
    private IDataCrkywTzdxxFlt001Service dataCrkywTzdxxFlt001Service;
    @Autowired
    private IFlBillRelationService flBillRelationService;
    @Autowired
    private IBasicEnumService basicEnumService;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;

    @Resource
    private BillnonewgjjMapper billnonewgjjMapper;
    /**
     * 保存汽车出入库-通知单主表
     *
     * @param qcrk 汽车出入库-通知单主表业务数据
     * @return
     */
    @Override
    @SystemLog(module = "原粮通知单", methods = "新增",uploadName = "yuliang.tzd")
    public JSONObject save(Qcrk qcrk) throws  Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);

        DataCrkywTzdxxDefault entity = qcrk.getDataCrkywTzdxxDefault();
        String unitId = entity.getUnitID();
        //样式id,流程id根据作业类型进行处理
        Integer zylx = entity.getZylx();
        entity.setSytelInfoID("2c9180856f7a0b21016f7e7c54e21cc1"); //样式id
        if (zylx == 1 || "1".equals(entity.getCczyfl())){ //粮油入库
            entity.setFlowId("A7B1FDB54DE7B32D6F8067FEFE2BF52F"); //流程Id
            entity.setCczyfl("2816");
            entity.setZylx(1);
        }
        if (zylx == 2 || "2".equals(entity.getCczyfl())){ //粮油出库
            entity.setFlowId("6FD0418CD28A2B3F3E7E9EC0D7429461"); //流程Id
            entity.setCczyfl("2818");
            entity.setZylx(2);
        }
        //设置作业类型
//        entity.setCczyfl(zylx.toString());
        Double sysl = entity.getSysl() != null?entity.getSysl():0.0;
        entity.setWcsl(entity.getSl()-sysl);

        entity.setFlowStatus(1); //流程状态
        entity.setPeriodID("11"); //期间id
        entity.setDeptID(unitId); //部门id
        entity.setRoundID(0); //舍位id
        if (StringUtils.isBlank(entity.getBuilder())){
            entity.setBuilder(entity.getUnitID());
            entity.setEditor(entity.getUnitID());
        }
        if (!super.save(entity)) { //保存汽车出入库-通知单主表表成功
            jsonObject.set("msg", "保存汽车出入库-通知单主表失败");
            return jsonObject;
        }

        //保存从表信息
        List<DataCrkywTzdxxFlt001> fltList = qcrk.getDataCrkywTzdxxDefault().getFltList();
        if (!fltList.isEmpty()) {
            {
                String id = entity.getDataID();
                String styelInfoId = entity.getSytelInfoID();
                for (int i = 0; i < fltList.size(); i++) {
                    DataCrkywTzdxxFlt001 dataCrkywTzdxxFlt001 = fltList.get(i);
                    dataCrkywTzdxxFlt001.setSytelInfoID(styelInfoId);
                    dataCrkywTzdxxFlt001.setPeriodID("11");
                    dataCrkywTzdxxFlt001.setMainDataID(id);
                    dataCrkywTzdxxFlt001.setDeptID(unitId); //部门id
                    dataCrkywTzdxxFlt001.setUnitID(unitId); //
                    dataCrkywTzdxxFlt001.setRoundID(0); //舍位id
                    dataCrkywTzdxxFlt001.setSysl(dataCrkywTzdxxFlt001.getCount()); //剩余数量与数量一致
                    if (StringUtils.isBlank(dataCrkywTzdxxFlt001.getBuilder())){
                        dataCrkywTzdxxFlt001.setBuilder(unitId);
                        dataCrkywTzdxxFlt001.setEditor(unitId);
                    }
                }
                if (!dataCrkywTzdxxFlt001Service.saveBatch(fltList)) { //保存汽车出入库-通知单从表成功
//                    jsonObject.set("msg", "保存汽车出入库-通知单从表数据失败");
                    throw  new Exception("保存汽车出入库-通知单从表数据失败");
//                    return jsonObject;

                }
            }

        }
        jsonObject.set("success", true);
        jsonObject.set("msg", "保存成功");
        return jsonObject;
    }

    /**
     * 修改汽车出入库-通知单主表
     *
     * @param qcrk 汽车出入库-通知单主表业务数据
     * @return
     */
    @Override
    @SystemLog(module = "原粮通知单", methods = "修改",uploadName = "yuliang.tzd")
    public JSONObject update(Qcrk qcrk) throws  Exception{
        {
            {
                JSONObject jsonObject = new JSONObject();
                jsonObject.set("success", false);
                //查询下一环节是否已处理
                DataCrkywTzdxxDefault entity = qcrk.getDataCrkywTzdxxDefault();
                Double wcsl = entity.getWcsl() != null?entity.getWcsl():0.0;
                entity.setSysl(entity.getSl()-wcsl);
                if (!super.updateById(entity)) { //修改汽车出入库-通知单主表表成功
                    jsonObject.set("msg", "修改汽汽车出入库-通知单主表失败");
                    return jsonObject;
                }

                //保存从表信息
                List<DataCrkywTzdxxFlt001> fltList = qcrk.getDataCrkywTzdxxDefault().getFltList();
                if (!fltList.isEmpty()) {
                    {
                        String id = entity.getDataID();
                        String unitId = entity.getUnitID();
                        for (int i = 0; i < fltList.size(); i++) {
                            DataCrkywTzdxxFlt001 dataCrkywTzdxxFlt001 = fltList.get(i);
                            dataCrkywTzdxxFlt001.setSytelInfoID("2c9180856f7a0b21016f7e7c54e21cc1");
                            dataCrkywTzdxxFlt001.setPeriodID("11");
                            dataCrkywTzdxxFlt001.setMainDataID(id);
                            dataCrkywTzdxxFlt001.setDeptID(unitId); //部门id
                            dataCrkywTzdxxFlt001.setUnitID(unitId); //
                            dataCrkywTzdxxFlt001.setRoundID(0); //舍位id
                            if (StringUtils.isBlank(dataCrkywTzdxxFlt001.getBuilder())){
                                dataCrkywTzdxxFlt001.setBuilder(unitId);
                                dataCrkywTzdxxFlt001.setEditor(unitId);
                            }
                            Double wcsl1 = dataCrkywTzdxxFlt001.getWcsl() != null?dataCrkywTzdxxFlt001.getWcsl():0.0;
                            dataCrkywTzdxxFlt001.setSysl(dataCrkywTzdxxFlt001.getCount()-wcsl1);
                        }
                        if (!dataCrkywTzdxxFlt001Service.saveOrUpdateBatch(fltList)) { //保存汽车出入库-通知单从表成功
//                    jsonObject.set("msg", "保存汽车出入库-通知单从表数据失败");
                            throw  new Exception("修改汽车出入库-通知单从表数据失败");
//                    return jsonObject;

                        }
                    }

                }
                jsonObject.set("success", true);
                jsonObject.set("msg", "修改成功");
                return jsonObject;
            }
        }
    }

    /**
     * 删除汽车出入库-通知单主表数据
     *
     * @param id 汽车出入库-通知单主表主键尖
     * @return
     */
    @Override
    @SystemLog(module = "原粮通知单", methods = "删除",uploadName = "yuliang.tzd")
    public JSONObject delete(String id)throws  Exception {
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("success", false);
            //得到对象
            DataCrkywTzdxxDefault dataCrkywJyxxDefault = super.getById(id);
            String unitID = dataCrkywJyxxDefault.getUnitID();
            if (dataCrkywJyxxDefault == null){
                jsonObject.set("msg","此数据已被删除");
                return  jsonObject;
            }
            //检测完成数量
            if (dataCrkywJyxxDefault.getWcsl() != null && dataCrkywJyxxDefault.getWcsl() > 0.0){
                jsonObject.set("msg","此数据已被使用，不能删除");
                return  jsonObject;
            }
            //得到从表数据
            QueryWrapper<DataCrkywTzdxxFlt001> deleteFltWrapper = new QueryWrapper<>();
            deleteFltWrapper.eq("MainDataID",id);
            List<DataCrkywTzdxxFlt001> tzdFlt001s = dataCrkywTzdxxFlt001Service.list(deleteFltWrapper);

            if (!super.removeById(id)) { //删除汽车出入库-通知单数据成功
                jsonObject.set("msg", "删除汽车出入库-通知单数据失败");
                return jsonObject;
            }
            //保存删除数据记录
            deleteDataRecordService.save(id,"data_crkyw_tzdxx_default",unitID,new Date());
            //保存从表删除信息
            for (int i = 0; i < tzdFlt001s.size(); i++) {
                DataCrkywTzdxxFlt001 jyxxFlt001 = tzdFlt001s.get(i);
                deleteDataRecordService.save(jyxxFlt001.getDataID(),"data_crkyw_tzdxx_flt_001",unitID,new Date());
            }

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

    /**id
     * 按照条件查询汽车出入库-通知单主表信息
     *
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String, Object>> findPageVo(DataCrkywTzdxxDefaultVo pageQuery) {
        {
            //条形查询器
            QueryWrapper<DataCrkywTzdxxDefault> queryWrapper = new QueryWrapper<>();
            String sytelInfoId = "2c9180856f7a0b21016f7e7c54e21cc1"; //默认粮油入库
            Integer zylx = pageQuery.getZylx();

//            if (zylx == 2){ //粮油出库
//                sytelInfoId = "2c90808b66fc54ea0166fcd5498a1728";
//            }

            queryWrapper.eq("data_crkyw_tzdxx_default.SytelInfoID",sytelInfoId);

            if (StringUtils.isNotBlank(pageQuery.getUnitId())){
                queryWrapper.eq("data_crkyw_tzdxx_default.UnitId",pageQuery.getUnitId());
            }
            if (StringUtils.isNotBlank(pageQuery.getTzdbh())){
                queryWrapper.like("data_crkyw_tzdxx_default.tzdbh", ResultUtil.getQueryWrapperformat(pageQuery.getTzdbh()));
            }
            if (StringUtils.isNotBlank(pageQuery.getLspz())){
                queryWrapper.eq("data_crkyw_tzdxx_default.lspz",pageQuery.getLspz());
            }
            if (StringUtils.isNotBlank(pageQuery.getLsxz())){
                queryWrapper.eq("data_crkyw_tzdxx_default.lsxz",pageQuery.getLsxz());
            }
            if (StringUtils.isNotBlank(pageQuery.getZdsjStart()) && StringUtils.isNotBlank(pageQuery.getZdsjEnd())){
                queryWrapper.apply(" DATE_FORMAT(ifnull(data_crkyw_tzdxx_default.kdsj,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getZdsjStart()+"' AND DATE_FORMAT(ifnull(data_crkyw_tzdxx_default.kdsj,NOW()),'%Y-%m-%d') <= '"+pageQuery.getZdsjEnd()+" 23:59:59'");
            }
            //排序
            queryWrapper.orderByDesc("data_crkyw_tzdxx_default.BuildDate");

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

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

    @Override
    public DataCrkywTzdxxDefault getOne(String id) {
       DataCrkywTzdxxDefault dataCrkywTzdxxDefault = super.getById(id);
       if (StringUtils.isNotBlank(dataCrkywTzdxxDefault.getCd())){
           String cdValue = basicEnumService.getById(dataCrkywTzdxxDefault.getCd()).getEnumName();
           dataCrkywTzdxxDefault.setCdValue(cdValue);

       }
        if (StringUtils.isNotBlank(id)){ //修改，查看
            QueryWrapper<DataCrkywTzdxxFlt001> querWrapper = new QueryWrapper<>();
            querWrapper.eq("MainDataId", id);
            List<DataCrkywTzdxxFlt001> fltList = dataCrkywTzdxxFlt001Service.list(querWrapper);
            dataCrkywTzdxxDefault.setFltList(fltList);
        }
        return dataCrkywTzdxxDefault;
    }
    @Override
    public List<Map<String,Object>> getTzdList(String unitId, Integer zylx){
        String flowId = "A7B1FDB54DE7B32D6F8067FEFE2BF52F";
        if (zylx == 2){ //粮油出库
            flowId = "6FD0418CD28A2B3F3E7E9EC0D7429461";
        }
        return  dataCrkywTzdxxDefaultMapper.getTzdList(unitId,flowId);
    }
    //第二次称重 新增，修改 时将 修改通知单表 剩余数量，如果 称重数据大于 剩余数量 则关闭通知单
    @Override
    @SystemLog(module = "原粮通知单", methods = "修改",uploadName = "yuliang.tzd")
    public JSONObject updateTzdDataQcRk(Double editZl, String matherId,boolean... isCk) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        //得到
        String sql = "";
//        if (workType == StoreWorkType.In) { //汽车入库
//            //TODO UpdateSqlForGBase finish ReportDataInDIYServiceImpl_updateTzdDataSql1 1
//            sql = " SELECT "+ fn_ifnull() +"(b.tzdcbid, '') AS \"tzdcbid\"," + fn_ifnull() + "(xzklhjz,0.0) as \"zl\"," + fn_ifnull() + "(c.sl,0) as \"sl\"," + fn_ifnull() + "(c.sysl,0.0) as \"sysl\"," + fn_ifnull() + "(c.wcsl,0.0) as \"wcsl\"," + fn_ifnull() + "(c.DataID,'') as " + fn_FormatFld("DataID") + "," + fn_ifnull() + "(c.tzdbh,'') as \"tzdh\" FROM data_crkyw_cpz_default a LEFT JOIN data_crkyw_rmdj_default b on a.BizNo = b.BizNo LEFT JOIN data_crkyw_tzdxx_default c on b.tzdbh = c.tzdbh where a.dataid = '" + matherId + "'";
//        }
        List<Map<String, Object>> list = dataCrkywTzdxxDefaultMapper.queryQcInTzdInf(matherId);
        if (isCk.length > 0  && isCk[0]){

            list = dataCrkywTzdxxDefaultMapper.queryQCOutTzdInf(matherId);
        }

        if (list.isEmpty()) { //没有查到相关信息
            jsonObject.set("success", true);
            return jsonObject;
        }
        //通过能通知单编码
        Double zl = new Double(list.get(0).get("zl") + ""); //扣量后净重
        Double sl = new Double(list.get(0).get("sl") + ""); //通知单数量
        Double sysl = new Double(list.get(0).get("sysl") + ""); //通知单剩余数量
        Double wcsl = new Double(list.get(0).get("wcsl") + ""); //通知单完成数量
        String dataId = list.get(0).getOrDefault("dataId","").toString(); //通知单数据Id
        String tzdcbid = list.get(0).getOrDefault("tzdcbid","").toString(); //从表通知单数据Id
        if (StrUtil.isBlank(dataId)){ //表示通知单已经不存在
            jsonObject.set("msg", "通知单["+list.get(0).getOrDefault("tzdh","").toString()+"]不存在");
            return jsonObject;
        }
//        String tzdcbid = list.get(0).get("tzdcbid").toString(); //通知单使用的从表id
        Double dir_wc = wcsl +editZl; //完成数量+变化数量（包插新增或修改、删除）
        Double dir_sy = sl - dir_wc > 0.0 ? sl - dir_wc : 0.0;

        if(sysl-editZl<0){
            jsonObject.set("msg", "卸载重量大于通知单剩余数量");
            return jsonObject;
        }
        //更新主从表完成数量与剩余数理
//        sql = " UPDATE data_crkyw_tzdxx_default SET UPDATE_TIME=null,sysl ='" + dir_sy + "',wcsl ='" + dir_wc + "' where tzdbh = '" + tzdh + "'; ";
//        //有从表Id，并且是汽车出入库
//        if (workType == StoreWorkType.In || workType == StoreWorkType.Out) {
//            String tzdcbid = list.get(0).get("tzdcbid").toString(); //通知单从表数据Id
//            if (StringUtils.isNotBlank(tzdcbid)) {
//                sql += "UPDATE data_crkyw_tzdxx_flt_001 SET wcsl = wcsl-"+editZl+"+"+zl+", sysl = count-wcsl where DataID  ='"+tzdcbid+"'";
//            }
//        }
        UpdateWrapper<DataCrkywTzdxxDefault> dataCrkywTzdxxDefaultUpdateWrapper = new UpdateWrapper<>();
        dataCrkywTzdxxDefaultUpdateWrapper.eq("dataId",dataId);
        dataCrkywTzdxxDefaultUpdateWrapper.set("UPDATE_TIME",null);
        dataCrkywTzdxxDefaultUpdateWrapper.set("sysl",dir_sy);
        dataCrkywTzdxxDefaultUpdateWrapper.set("wcsl",dir_wc);
        if (dir_sy <= 0.0) { //表示完成
            dataCrkywTzdxxDefaultUpdateWrapper.set("FLOW_STATUS",2);
        }
        if (!super.update(dataCrkywTzdxxDefaultUpdateWrapper)) {
            jsonObject.set("msg", "更新通知单主表剩余数量失败");
            return jsonObject;

        }
        //修改从表通知单数量
        if(StringUtils.isNotBlank(tzdcbid)){
            UpdateWrapper<DataCrkywTzdxxFlt001> flt001UpdateWrapper = new UpdateWrapper<>();
            flt001UpdateWrapper.eq("dataId",tzdcbid);
            flt001UpdateWrapper.set("UPDATE_TIME",null);
            flt001UpdateWrapper.set("sysl",dir_sy);
            flt001UpdateWrapper.set("wcsl",dir_wc);
            flt001UpdateWrapper.setSql("UPDATE_TIME=null,wcsl = wcsl-"+editZl+"+"+zl+", sysl = count-wcsl"); //
            if (!dataCrkywTzdxxFlt001Service.update(flt001UpdateWrapper)) {
                jsonObject.set("msg", "更新通知单从表剩余数量失败");
                return jsonObject;
            }
        }

        jsonObject.set("success", true);
        return jsonObject;
    }

    /**
     * 更新库级通知单完成数量、剩余数量 和状态,
     *
     * @param editZl
     * @param matherId
     * @param isCk
     * @return
     */
    @Override
    public JSONObject updateTzdDataQcRkByDepot(Double editZl, String matherId, boolean... isCk) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("success", false);
            //得到
            String sql = "";
            List<Map<String, Object>> list = dataCrkywTzdxxDefaultMapper.queryQcInTzdInfByDepot(matherId);
            if (isCk.length > 0  && isCk[0]){

                list = dataCrkywTzdxxDefaultMapper.queryQCOutTzdInfByDepot(matherId);
            }

            if (list.isEmpty()) { //没有查到相关信息
                jsonObject.set("success", true);
                return jsonObject;
            }
            //通过能通知单编码
            Double zl = new Double(list.get(0).get("zl") + ""); //扣量后净重
            Double sl = new Double(list.get(0).get("sl") + ""); //通知单数量
            Double sysl = new Double(list.get(0).get("sysl") + ""); //通知单剩余数量
            Double wcsl = new Double(list.get(0).get("wcsl") + ""); //通知单完成数量
            String dataId = list.get(0).getOrDefault("dataId","").toString(); //通知单数据Id
            String tzdcbid = list.get(0).getOrDefault("tzdcbid","").toString(); //从表通知单数据Id
            if (StrUtil.isBlank(dataId)){ //表示通知单已经不存在
                jsonObject.set("msg", "通知单["+list.get(0).getOrDefault("tzdh","").toString()+"]不存在");
                return jsonObject;
            }
//        String tzdcbid = list.get(0).get("tzdcbid").toString(); //通知单使用的从表id
            Double dir_wc = wcsl +editZl; //完成数量+变化数量（包插新增或修改、删除）
            Double dir_sy = sl - dir_wc > 0.0 ? sl - dir_wc : 0.0;

            if(sysl-editZl<0){
                jsonObject.set("msg", "卸载重量大于通知单剩余数量");
                return jsonObject;
            }
            //更新库级主从表完成数量与剩余数理
        sql = " UPDATE BUSINESS_DELIVERY_STORAGE_NOTICE SET remain_quantity ='" + dir_sy + "',complete_quantity ='" + dir_wc + "' where id = '" + dataId + "'; ";
        //有从表Id，并且是汽车出入库
        if (StringUtils.isNotBlank(tzdcbid)) {
            sql += "UPDATE BUSINESS_STORE_WARE_DETAIL SET complete_quantity = wcsl+"+editZl+"+"+zl+", remain_quantity = if(in_count >0,in_count,out_count)-complete_quantity where id  ='"+tzdcbid+"'";
        }
        billnonewgjjMapper.executeUpdate(sql);

        jsonObject.set("success", true);
        return jsonObject;
    }
}
