package com.unis.crk.cplbusiness.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.unis.crk.aop.SystemLog;
import com.unis.crk.basic.entity.BasicEnum;
import com.unis.crk.basic.service.IBasicEnumService;
import com.unis.crk.business.kcgl.entity.DataKcglFcbgzDefault;
import com.unis.crk.business.qcck.entity.DataCrkywCkcmzDefault;
import com.unis.crk.business.qcck.entity.DataCrkywCkcpzDefault;
import com.unis.crk.common.entity.Bizflowtrail;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.cplbusiness.entity.*;
import com.unis.crk.cplbusiness.mapper.DataCrkywCplckDefaultMapper;
import com.unis.crk.cplbusiness.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.crk.enums.EditStatus;
import com.unis.crk.enums.StoreWorkType;
import com.unis.crk.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.json.JSONObject;
import javax.annotation.Resource;
import com.unis.crk.cplbusiness.entity.vo.DataCrkywCplckDefaultVo;

import static cn.hutool.core.text.CharSequenceUtil.hasBlank;

/**
 * <p>
 * 成品粮出库 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2022-03-21
 */
@Service
public class DataCrkywCplckDefaultServiceImpl extends ServiceImpl<DataCrkywCplckDefaultMapper, DataCrkywCplckDefault> implements IDataCrkywCplckDefaultService {

    @Resource
    private DataCrkywCplckDefaultMapper dataCrkywCplckDefaultMapper;

    @Autowired
    private IDataKcglCplxckcDefaultService dataKcglCplxckcDefaultService;
    @Autowired
    private IDataCrkywCpltzdxxFlt001Service dataCrkywCpltzdxxFlt001Service;
    @Autowired
    private IDataKcglCplfcbgzDefaultService  dataKcglCplfcbgzDefaultService;
    @Autowired
    private IDataCrkywCplckFlt001Service dataCrkywCplckFlt001Service;
    @Autowired
    private IBasicEnumService basicEnumService;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;
    @Autowired
    private IDispatchEhicleManagementService dispatchEhicleManagementService;
    @Autowired
    private IDispatcPersonnelManagementService dispatcPersonnelManagementService;



    /**
     * 按照条件查询成品粮出库信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataCrkywCplckDefaultVo pageQuery){
            //条形查询器
            QueryWrapper<DataCrkywCplckDefault> queryWrapper = new QueryWrapper<>();
            if(StringUtils.isNotBlank(pageQuery.getUnitId())){
                queryWrapper.eq("a.unitId",pageQuery.getUnitId());
            }
            if(StringUtils.isNotBlank(pageQuery.getSjjlpzbh())){
                queryWrapper.eq("a.sjjlpzbh",pageQuery.getSjjlpzbh());
            }
            if(StringUtils.isNotBlank(pageQuery.getSjjlspmc())){
                queryWrapper.like("a.sjjlspmc",ResultUtil.getQueryWrapperformat(pageQuery.getSjjlspmc()));
            }
            if(StringUtils.isNotBlank(pageQuery.getCkbh())){
                queryWrapper.like("a.ckbh",ResultUtil.getQueryWrapperformat(pageQuery.getCkbh()));
            }
            if(StringUtils.isNotBlank(pageQuery.getYwlx())){
                queryWrapper.eq("a.ywlx",pageQuery.getYwlx());
            }
            if (StringUtils.isNotBlank(pageQuery.getJysjStart()) && StringUtils.isNotBlank(pageQuery.getJysjEnd())){
                queryWrapper.apply(" DATE_FORMAT(ifnull(a.ywsj,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getJysjStart()+"' AND DATE_FORMAT(ifnull(a.ywsj,NOW()),'%Y-%m-%d') <= '"+pageQuery.getJysjEnd()+" 23:59:59'");

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

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveCk(DataCrkywCplckDefault param) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        if (isExist(param.getCkbh())){
            jsonObject.set("msg","此单据号已存在");
            return jsonObject;
        }
        param.setDeptId(param.getUnitid());//部门id
        if (StringUtils.isBlank(param.getBuilder())){
            param.setBuilder(param.getUnitid());
            param.setEditor(param.getUnitid());
        }
        //如果是内部车,设置车牌号和人员相关信息
        param = setRyCp(param);
//        param.setYwlx("1");//业务类型，1入库
        if (param.getFltList() == null || param.getFltList().size() <= 0) { //
            throw new Exception("成品粮出库无从表数据");
        }
        String dataId = param.getDataId();
        String s = IdUtil.simpleUUID();
        if(StringUtils.isBlank(dataId)){
            dataId=s;
            param.setDataId(s);
        }
        String unitId = param.getUnitid();
        //得到从表数据

        List<DataCrkywCplckFlt001> flt001s = param.getFltList();
        if (flt001s == null || flt001s.size() <= 0){
            throw new Exception("成品粮出库商品信息为空失败");
        }
        if (!super.saveOrUpdate(param)) {
            throw new Exception("保存成品粮出库失败");
        }
        String spmc = "";
                    if("0".equals(param.getIsstaging())){ //
                for (int i = 0; i < flt001s.size(); i++) {
                    //保存从表数据，有错误抛异常
                    DataCrkywCplckFlt001 flt001 = flt001s.get(i);
                    flt001.setMainDataId(dataId);// 设置主表ID
                    flt001.setUnitid(unitId);// 设置单位id
                    flt001.setIsstaging("0");//设置暂存
                    dataCrkywCplckFlt001Service.save(flt001);
                    spmc +=flt001.getSjjlspmc()+",";
                }
                if (StrUtil.isNotBlank(spmc)){
                    param.setSjjlspmc(spmc.substring(0,spmc.length()-1));
                    if (!super.saveOrUpdate(param)) { //
                        throw new Exception("保存成品粮出库失败");
                    }
                }
        }else{  //保存
                for (int i = 0; i < flt001s.size(); i++) {
                    //保存从表数据，有错误抛异常
                    DataCrkywCplckFlt001 flt001 = flt001s.get(i);
                    flt001.setMainDataId(dataId);// 设置主表ID
                    flt001.setUnitid(unitId);// 设置单位id
                    flt001.setIsstaging("1");//设置保存
                    dataCrkywCplckFlt001Service.saveFlt(flt001);

                    spmc +=flt001.getSjjlspmc()+",";
                }
                if (StrUtil.isNotBlank(spmc)){
                    param.setSjjlspmc(spmc.substring(0,spmc.length()-1));
                    if (!super.saveOrUpdate(param)) { //
                        throw new Exception("保存成品粮出库失败");
                    }
                }
        }

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

    private DataCrkywCplckDefault setRyCp(DataCrkywCplckDefault param) {
        if (StrUtil.equals("1",param.getNwc())){
            //车辆
            if (StrUtil.isNotBlank(param.getCphId())){
                DispatchEhicleManagement dispatchEhicleManagement = dispatchEhicleManagementService.getById(param.getCphId());
                if (dispatchEhicleManagement != null){
                    param.setCph(dispatchEhicleManagement.getLicensePlateNumber());
                }
            }
            //人员
            if (StrUtil.isNotBlank(param.getRyid())){
                DispatcPersonnelManagement dispatcPersonnelManagement = dispatcPersonnelManagementService.getById(param.getRyid());
                if (dispatcPersonnelManagement != null){
                    param.setCyr(dispatcPersonnelManagement.getPersonName()); //承运人
                    param.setCyrsfz(dispatcPersonnelManagement.getIdNumber()); //身份证号
                    param.setCyrdh(dispatcPersonnelManagement.getContactNumber()); //电话
                    param.setCyrdz(dispatcPersonnelManagement.getContactAddress()); //地址
                }
            }

        }
        return param;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject deleteCk(String id) throws  Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        //得到对象
        DataCrkywCplckDefault entity = super.getById(id);
        if (entity == null) {
            jsonObject.set("msg", "此数据已被删除");
            return jsonObject;
        }
        if (!super.removeById(id)) { //删除成品粮入库数据失败
            jsonObject.set("msg", "删除成品粮入库数据失败");
            return jsonObject;
        }
        String isstaging = entity.getIsstaging();

        deleteDataRecordService.save(id,"data_crkyw_cplck_default",entity.getUnitid(),new Date());
        //得到从表数据
        QueryWrapper<DataCrkywCplckFlt001> flt001QueryWrapper = new QueryWrapper<>();
        flt001QueryWrapper.eq("mainDataId",id);
        if("0".equals(isstaging)){
            dataCrkywCplckFlt001Service.remove(flt001QueryWrapper);
            jsonObject.set("success", true);
            jsonObject.set("msg", "删除成功");
            return jsonObject;
        }

        List<DataCrkywCplckFlt001> flt001s = dataCrkywCplckFlt001Service.list(flt001QueryWrapper);
        if (flt001s != null || flt001s.size() > 0){
            for (int i = 0; i < flt001s.size(); i++) {
                //保存从表数据，有错误抛异常
                DataCrkywCplckFlt001 flt001 = flt001s.get(i);
                if("0".equals(flt001.getIsstaging())){ //暂存直接删除子表数据
                    dataCrkywCplckFlt001Service.removeById(flt001.getDataId());

                }else{
                    dataCrkywCplckFlt001Service.deleteFlt(flt001.getDataId());

                }
                deleteDataRecordService.save(flt001.getDataId(),"data_crkyw_cplck_flt_001",flt001.getUnitid(),new Date());
            }
        }
        jsonObject.set("success", true);
        jsonObject.set("msg", "删除成功");
        return jsonObject;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject updateCk(DataCrkywCplckDefault param) throws Exception {
        //保存库存相关数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        String dataId = param.getDataId();
        String unitId = param.getUnitid();
        //得到对象
        DataCrkywCplckDefault entity = super.getById(param.getDataId());
        if (entity == null) {
            jsonObject.set("msg", "此数据已被删除");
            return jsonObject;
        }
        if (param.getFltList() == null || param.getFltList().size() <= 0) { //
            throw new Exception("成品粮出库无从表数据");
        }
        List<DataCrkywCplckFlt001> insertFlt = new ArrayList<>(); //新增
        List<DataCrkywCplckFlt001> updateFlt = new ArrayList<>(); //修改
        List<String> deleteFlt = new ArrayList<>(); //删除
        //得到从表数据
        //得到从表数据
        String  spmcz="";
        QueryWrapper<DataCrkywCplckFlt001> Wrapper = new QueryWrapper<>();
        Wrapper.eq("MainDataID", param.getDataId());
        List<DataCrkywCplckFlt001> oldFlt001s = dataCrkywCplckFlt001Service.list(Wrapper);

        List<DataCrkywCplckFlt001> newFlt001s = param.getFltList();
        for (int j = 0; j < newFlt001s.size(); j++) {
            DataCrkywCplckFlt001 newFlt001 = newFlt001s.get(j);
            spmcz +=newFlt001.getSjjlspmc()+",";
            if (StrUtil.isBlank(newFlt001.getDataId())){ //新增
                insertFlt.add(newFlt001);
            }
        }
        newFlt001s.removeAll(insertFlt); //去掉新增

        for (int i = 0; i < oldFlt001s.size(); i++) {
            DataCrkywCplckFlt001 oldFlt001 = oldFlt001s.get(i);
            boolean flag  = false;
            for (int j = 0; j < newFlt001s.size(); j++) {
                DataCrkywCplckFlt001 newFlt001 = newFlt001s.get(j);
                if ( StrUtil.equals(newFlt001.getDataId(),oldFlt001.getDataId())){ //修改
                    updateFlt.add(newFlt001);
                    flag = true;
                    continue;
                }
            }
            if (!flag){
                deleteFlt.add(oldFlt001.getDataId()); //删除内容
            }
        }
        //如果是内部车,设置车牌号和人员相关信息
        param = setRyCp(param);
        if (!super.updateById(param)) { //修改成品粮入库
            throw new Exception("修改成品粮入库");
        }
        if("0".equals(param.getIsstaging())){ //暂存
            String spmc = "";
            QueryWrapper<DataCrkywCplckFlt001> wrapper = new QueryWrapper<>();
            wrapper.eq("MainDataID", param.getDataId());
            dataCrkywCplckFlt001Service.remove(wrapper);
            for (int i = 0; i < param.getFltList().size(); i++) {
                //保存从表数据，有错误抛异常
                DataCrkywCplckFlt001 flt001 = param.getFltList().get(i);
                flt001.setMainDataId(dataId);// 设置主表ID
                flt001.setUnitid(unitId);// 设置单位id
                flt001.setIsstaging("1");//设置保存
                spmc +=flt001.getSjjlspmc()+",";
                dataCrkywCplckFlt001Service.saveFlt(flt001);

                spmc +=flt001.getSjjlspmc()+",";
            }
            if (StrUtil.isNotBlank(spmc)){
                param.setSjjlspmc(spmc.substring(0,spmc.length()-1));
                if (!super.saveOrUpdate(param)) { //
                    throw new Exception("保存成品粮出库失败");
                }
            }
            jsonObject.set("success", true);
            jsonObject.set("msg", "修改成功");
            return jsonObject;

            }else {//保存
                if (insertFlt.size() >0){ //新增内容
                    for (int j = 0; j < insertFlt.size(); j++) {
                        //保存从表数据，有错误抛异常
                        DataCrkywCplckFlt001 flt001 = insertFlt.get(j);
                        flt001.setMainDataId(param.getDataId());// 设置主表
                        flt001.setUnitid(param.getUnitid());//
                        dataCrkywCplckFlt001Service.saveFlt(flt001);
                    }
                }
                if (updateFlt.size() >0){ //修改内容
                    for (int j = 0; j < updateFlt.size(); j++) {
                        //修改从表数据，有错误抛异常
                        DataCrkywCplckFlt001 flt001 = updateFlt.get(j);
                        flt001.setMainDataId(param.getDataId());// 设置主表
                        flt001.setUnitid(param.getUnitid());//
                        dataCrkywCplckFlt001Service.updateFlt(flt001);
                    }
                }
                if (deleteFlt.size() >0){ //删除内容
                    for (int j = 0; j < deleteFlt.size(); j++) {
                        //删除从表数据，有错误抛异常
                        DataCrkywCplckFlt001 byId = dataCrkywCplckFlt001Service.getById(deleteFlt.get(j));
                        dataCrkywCplckFlt001Service.deleteFlt(deleteFlt.get(j));
                        deleteDataRecordService.save(deleteFlt.get(j),"data_crkyw_cplck_flt_001",byId.getUnitid(),new Date());

                    }
                }

            if (StrUtil.isNotBlank(spmcz)){
                param.setSjjlspmc(spmcz.substring(0,spmcz.length()-1));
                if (!super.saveOrUpdate(param)) { //
                    throw new Exception("保存成品粮出库失败");
                }
            }
            jsonObject.set("success", true);
            jsonObject.set("msg", "修改成功");
            return jsonObject;
        }


    }

    /**
     * 通过出库单号检测是否已经存在
     *
     * @param ckbh
     * @return
     */
    private boolean isExist(String ckbh) {
        QueryWrapper<DataCrkywCplckDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ckbh", ckbh);
        queryWrapper.eq("isstaging", "1");
        queryWrapper.last("limit 0,1");
        return super.getOne(queryWrapper) != null;
    }

    @Override
    public DataCrkywCplckDefault getOneData(String id) {
        DataCrkywCplckDefault dataCrkywCplckDefault = dataCrkywCplckDefaultMapper.getOneById(id);
        QueryWrapper<DataCrkywCplckFlt001> Wrapper = new QueryWrapper<>();
        Wrapper.eq("MainDataID", id);
        List<DataCrkywCplckFlt001> list = dataCrkywCplckFlt001Service.list(Wrapper);
        if(list!=null && list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                DataCrkywCplckFlt001 flt001 = list.get(i);
                BasicEnum jldw = basicEnumService.getById(flt001.getJldw());
                flt001.setJldwmc(jldw.getEnumName() != null ?jldw.getEnumName():"");
            }
            dataCrkywCplckDefault.setFltList(list);
        }
        return dataCrkywCplckDefault;
    }

    @Override
    public List<DataCrkywCplckDefault> getAppCkList(String ddbh) {
        {
            List<DataCrkywCplckDefault> dataCrkywCplckDefaults = dataCrkywCplckDefaultMapper.getAppCkList(ddbh);
            for (int i = 0; i < dataCrkywCplckDefaults.size(); i++) {
                DataCrkywCplckDefault dataCrkywCplckDefault = dataCrkywCplckDefaults.get(i);
                QueryWrapper<DataCrkywCplckFlt001> Wrapper = new QueryWrapper<>();
                Wrapper.eq("MainDataID", dataCrkywCplckDefault.getDataId());
                List<DataCrkywCplckFlt001> list = dataCrkywCplckFlt001Service.list(Wrapper);
                if(list!=null && list.size()>0){
                    for (int j = 0; j < list.size(); j++) {
                        DataCrkywCplckFlt001 flt001 = list.get(j);
                        flt001.setJldwmc(basicEnumService.getById(flt001.getJldw()).getEnumName());
                        flt001.setGg(flt001.getGg()+flt001.getJldwmc());
                    }
                    dataCrkywCplckDefault.setFltList(list);
                }
            }
            return dataCrkywCplckDefaults;
        }
    }

    @Override
    public List<DataCrkywCplckDefault> getCphList(String unitId) {
        QueryWrapper<DataCrkywCplckDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(" DISTINCT cph"," cyr,cyrdh,cyrdz,cyrsfz,cph,cjsj ").lambda();
        //分页相关
        if(StringUtils.isNotBlank(unitId)){
            queryWrapper.eq("unitId",unitId);
        }
        queryWrapper.isNotNull("cph");
        queryWrapper.orderByDesc("cjsj");
        queryWrapper.orderByAsc("cph");
        return super.list(queryWrapper);
    }

    /**
     * 检验是否超出库存数量
     * @param dataId
     * @param isUpdate
     * @return
     */
    public JSONObject beforEditOrDelete(String dataId, Boolean isUpdate) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", "true");
        jsonObject.set("editZl", 0.0);
        DataKcglCplfcbgzDefault dataKcglCplfcbgzDefault = dataKcglCplfcbgzDefaultService.getById(dataId);
        if (dataKcglCplfcbgzDefault != null) { //表示是修改、删除
            Double srsl = dataKcglCplfcbgzDefault.getSrsl();
            Double zcsl = dataKcglCplfcbgzDefault.getZcsl();
            Double oldZl = Math.abs(srsl - zcsl); //绝对值

            String sjjlpzbh = dataKcglCplfcbgzDefault.getSjjlpzbh();//品种编号
            String sjjlppbh = dataKcglCplfcbgzDefault.getSjjlppbh();//品牌编号
            String sjjlspmcbh = dataKcglCplfcbgzDefault.getSjjlspmcbh();//商品名称编号
            String scpc = dataKcglCplfcbgzDefault.getScpc();//生产批次
            String xz = dataKcglCplfcbgzDefault.getXz();//性质
            String ch = dataKcglCplfcbgzDefault.getCh();//仓房
            String hw = dataKcglCplfcbgzDefault.getHwh();//货位
            String gg = dataKcglCplfcbgzDefault.getGg();//规格

            String date =  DateUtil.format(dataKcglCplfcbgzDefault.getRcrq(),"yyyy-MM-dd HH:mm:ss");
//            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dataKcglFcbgzDefault.getRq());
            Double editZl;
            //得到新重量

            Double zl = super.getById(dataId).getSjjlsl();
            editZl = isUpdate ? (Double.valueOf(zl) - oldZl) : (0.0 - Double.valueOf(oldZl)); //修改/删除

            jsonObject.set("editZl", editZl);
            QueryWrapper<DataKcglCplfcbgzDefault> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("unitid", dataKcglCplfcbgzDefault.getUnitid());
            queryWrapper.eq("ch", ch);
            queryWrapper.eq("hwh", hw);
            queryWrapper.eq("sjjlpzbh", sjjlpzbh);
            queryWrapper.eq("hwxz", xz);
            queryWrapper.ge("rcrq", date);
            queryWrapper.ge("sjjlppbh", sjjlppbh);
            queryWrapper.ge("sjjlspmcbh", sjjlspmcbh);
            queryWrapper.ge("scpc", scpc);
            queryWrapper.ge("gg", gg);
            queryWrapper.lt("kcsl+" + editZl, 0); //修改后的库存数量小于0
            queryWrapper.ne("dataId", dataId);
            queryWrapper.orderByDesc("rq");
            if (dataKcglCplfcbgzDefaultService.list(queryWrapper).size() > 0) {
                jsonObject.set("success", "false");
                jsonObject.set("msg", "不可操作，库存数量变为负数");
                return jsonObject;
            }
        } else { //表示新增
            /*Double editZl;
            //得到新重量
            Double zl = super.getById(dataId).getSjjlsl();
            editZl = zl;

            jsonObject.set("editZl", editZl);*/
        }
        return jsonObject;
    }
}
