package com.unis.crk.cplbusiness.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.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.crk.business.qcrk.entity.DataCrkywTzdxxDefault;
import com.unis.crk.business.qcrk.entity.DataCrkywTzdxxFlt001;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.cplbusiness.entity.*;
import com.unis.crk.cplbusiness.entity.vo.DataCrkywCplpfDefaultVo;
import com.unis.crk.cplbusiness.entity.vo.DataCrkywCpltzdxxDefaultVo;
import com.unis.crk.cplbusiness.mapper.DataCrkywCpltzdxxDefaultMapper;
import com.unis.crk.cplbusiness.service.IDataCrkywCplckDefaultService;
import com.unis.crk.cplbusiness.service.IDataCrkywCpltzdxxDefaultService;
import com.unis.crk.cplbusiness.service.IDataCrkywCpltzdxxFlt001Service;
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 sun.rmi.server.WeakClassHashMap;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 成品粮出入库-通知单主表 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2022-03-23
 */
@Service
public class DataCrkywCpltzdxxDefaultServiceImpl extends ServiceImpl<DataCrkywCpltzdxxDefaultMapper, DataCrkywCpltzdxxDefault> implements IDataCrkywCpltzdxxDefaultService {

    @Resource
    private DataCrkywCpltzdxxDefaultMapper dataCrkywCpltzdxxDefaultMapper;
    @Autowired
    private IDataCrkywCpltzdxxFlt001Service dataCrkywCpltzdxxFlt001Service;

    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;

    @Autowired
    private IDataCrkywCplckDefaultService dataCrkywCplckDefaultService;
    /**
     *修改成品粮出入库-通知单主表
     * @param entity 成品粮出入库-通知单主表业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(DataCrkywCpltzdxxDefault entity) throws Exception {
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("success", false);
            //剩余数量=数量-完成数量（0）
            entity.setSysl(entity.getSl()-entity.getWcsl());
            if (!super.updateById(entity)) { //修改成品粮订单主表失败
                jsonObject.set("msg", "修改成品粮订单主表失败");
                return jsonObject;
            }

            //保存从表信息
            List<DataCrkywCpltzdxxFlt001> fltList = entity.getFltList();
            if (!fltList.isEmpty()) {
                {
                    String id = entity.getDataID();
                    String unitId = entity.getUnitID();
                    for (int i = 0; i < fltList.size(); i++) {
                        DataCrkywCpltzdxxFlt001 dataCrkywCpltzdxxFlt001 = fltList.get(i);
                        dataCrkywCpltzdxxFlt001.setPeriodID("11");
                        dataCrkywCpltzdxxFlt001.setMainDataID(id);
                        dataCrkywCpltzdxxFlt001.setDeptID(unitId); //部门id
                        dataCrkywCpltzdxxFlt001.setUnitID(unitId); //
                        dataCrkywCpltzdxxFlt001.setRoundID(0); //舍位id
                        Double wcsl = dataCrkywCpltzdxxFlt001.getWcsl();
                        if (wcsl == null){
                            wcsl = 0.0;
                        }
                        //剩余数量=数量-完成数量（0）
                        dataCrkywCpltzdxxFlt001.setSysl(dataCrkywCpltzdxxFlt001.getSl()-wcsl);
                        if (StringUtils.isBlank(dataCrkywCpltzdxxFlt001.getBuilder())){
                            dataCrkywCpltzdxxFlt001.setBuilder(unitId);
                            dataCrkywCpltzdxxFlt001.setEditor(unitId);
                        }
                    }
                    if (!dataCrkywCpltzdxxFlt001Service.saveOrUpdateBatch(fltList)) { //修改成品粮订单主表失败
                        throw  new Exception("修改成品粮订单从表失败");

                    }
                }
            }
            jsonObject.set("success", true);
            jsonObject.set("msg", "修改成功");
            return jsonObject;
        }
    }
    /**
     *删除成品粮出入库-通知单主表数据
     * @param id 成品粮出入库-通知单主表主键尖
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject delete(String id) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        DataCrkywCpltzdxxDefault dataCrkywCpltzdxxDefault = dataCrkywCpltzdxxDefaultMapper.selectById(id);

        if (dataCrkywCpltzdxxDefault == null) {
            jsonObject.set("msg", "此数据已被删除");
            return jsonObject;
        }
        //檢查完成數理
        Double wcsl = dataCrkywCpltzdxxDefault.getWcsl();
//        System.out.println("完成數量:"+wcsl);
        if (wcsl != null && wcsl > 0.0 ){
            jsonObject.set("msg","此数据已被使用，不能删除");
            return  jsonObject;
        }
        if (!super.removeById(id)) { //删除成功
            jsonObject.set("msg", "删除成品粮订单数据失败");
            return jsonObject;
        }
        QueryWrapper<DataCrkywCpltzdxxFlt001> flt001QueryWrapper = new QueryWrapper<>();
        flt001QueryWrapper.eq("MainDataID",id);
        List<DataCrkywCpltzdxxFlt001> fltForMainDataId = dataCrkywCpltzdxxFlt001Service.list(flt001QueryWrapper);

        deleteDataRecordService.save(id,"data_crkyw_cpltzdxx_default",dataCrkywCpltzdxxDefault.getUnitID(),new Date());
        if(fltForMainDataId.size()>0){
            Iterator<DataCrkywCpltzdxxFlt001> iterator = fltForMainDataId.iterator();
            while (iterator.hasNext()){
                DataCrkywCpltzdxxFlt001 next = iterator.next();
                deleteDataRecordService.save(next.getDataID(),"data_crkyw_cpltzdxx_flt_001",next.getUnitID(),new Date());
            }

        }
        jsonObject.set("success", true);
        jsonObject.set("msg", "删除成功");
        return jsonObject;
    }
    /**
     * 按照条件查询成品粮出入库-通知单主表信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataCrkywCpltzdxxDefaultVo pageQuery){
        {
            //条形查询器
            QueryWrapper<DataCrkywCpltzdxxDefault> queryWrapper = new QueryWrapper<>();
            if (StrUtil.isNotBlank(pageQuery.getUnitId())){
                queryWrapper.eq("unitid",pageQuery.getUnitId());
            }
            if (StrUtil.isNotBlank(pageQuery.getTzdbm())){
                queryWrapper.like("tzdbm", ResultUtil.getQueryWrapperformat(pageQuery.getTzdbm()));
            }
            if (StrUtil.isNotBlank(pageQuery.getCazylx())){
                if (StringUtils.indexOf(pageQuery.getCazylx().toString(),",") > 0){ //表示查询入库,还是出库类型
                    queryWrapper.inSql("cazylx",pageQuery.getCazylx());
                }else{
                    queryWrapper.eq("cazylx",pageQuery.getCazylx());
                }

            }
            if (StrUtil.isNotBlank(pageQuery.getIsWc()) ){
                if ( StrUtil.equals(pageQuery.getIsWc(),"1")){
                    queryWrapper.le("a.sysl", 0);
                }else {
                    queryWrapper.gt("a.sysl",0);
                }
            }
            if (StringUtils.isNotBlank(pageQuery.getYwStart()) && StringUtils.isNotBlank(pageQuery.getYwEnd())){
                queryWrapper.apply(" DATE_FORMAT(ifnull(a.kdsj,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getYwStart()+"' AND DATE_FORMAT(ifnull(a.kdsj,NOW()),'%Y-%m-%d') <= '"+pageQuery.getYwEnd()+" 23:59:59'");
            }
            //排序
            queryWrapper.orderByDesc("a.BuildDate");
            //分页相关
            Page<DataCrkywCpltzdxxDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

            IPage<Map<String,Object>> page = dataCrkywCpltzdxxDefaultMapper.selectMyMapsPage(p,queryWrapper);
            if (StrUtil.isNotBlank(pageQuery.getIsWc())) {
            List<Map<String, Object>> records = page.getRecords();
            for (int i = 0; i < records.size(); i++) {
                Map<String, Object> map = records.get(i);
                QueryWrapper<DataCrkywCpltzdxxFlt001> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("maindataId", map.getOrDefault("dataid", ""));
                List<DataCrkywCpltzdxxFlt001> dataCrkywCplckFlt001s = dataCrkywCpltzdxxFlt001Service.list(queryWrapper1);
                Double wcjs = 0.0;
                Double syjs = 0.0;
                for (int j = 0; j < dataCrkywCplckFlt001s.size(); j++) {
                    DataCrkywCpltzdxxFlt001 dataCrkywCplckFlt001 = dataCrkywCplckFlt001s.get(j);
                    //t得到剩余件数
                    Double sysl = dataCrkywCplckFlt001.getSysl();
                    Double wcsl = dataCrkywCplckFlt001.getWcsl();
                    String gg = dataCrkywCplckFlt001.getGg();
                    syjs += sysl / Double.parseDouble(gg);
                    wcjs += wcsl / Double.parseDouble(gg);
                }
                map.put("syjs", syjs);
                map.put("wcjs", wcjs);
                records.set(i, map);
            }
                page.setRecords(records);
        }
            return page;
        }
    }
    @Override
    public List<Map<String,Object>> getCplTzdList(String unitId, String zylx){
        return  dataCrkywCpltzdxxDefaultMapper.getCplTzdList(unitId,zylx);
    }
    @Override
    public List<Map<String,Object>> getCplCrkTzdFltList(String dataId){
        return  dataCrkywCpltzdxxFlt001Service.getCplCrkTzdFltList(dataId);
    }

    @Override
    public IPage<Map<String,Object>> findPagepfDefaultVo(DataCrkywCplpfDefaultVo pageQuery) {
        QueryWrapper<DataCrkywCpltzdxxDefault> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(pageQuery.getUnitId())){
            queryWrapper.eq("unitid",pageQuery.getUnitId());
        }
        if (StrUtil.isNotBlank(pageQuery.getTzdbm())){
            queryWrapper.like("tzdbm",pageQuery.getTzdbm());
        }
        if (StrUtil.isNotBlank(pageQuery.getCazylx())){
            queryWrapper.eq("cazylx",pageQuery.getCazylx());
        }

        if (StringUtils.isNotBlank(pageQuery.getYwStart()) && StringUtils.isNotBlank(pageQuery.getYwEnd())){
            queryWrapper.apply(" DATE_FORMAT(ifnull(a.BuildDate,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getYwStart()+"' AND DATE_FORMAT(ifnull(a.BuildDate,NOW()),'%Y-%m-%d') <= '"+pageQuery.getYwEnd()+" 23:59:59'");
        }

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

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

    @Override
    public Map<String, Object> getCplCrkTzdFltListAndsp(String mainDataId) {
        List<Map<String, Object>> cplCrkTzdFltList = dataCrkywCpltzdxxFlt001Service.getCplCrkTzdFltList(mainDataId);
        DataCrkywCpltzdxxDefault byId = this.getById(mainDataId);
        String thdbm = byId.getThdbm();
        QueryWrapper<DataCrkywCplckDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ddbh",thdbm);
        List<DataCrkywCplckDefault> list = dataCrkywCplckDefaultService.list(queryWrapper);
        Iterator<DataCrkywCplckDefault> iterator = list.iterator();
        ArrayList<DataCrkywCplckFlt001> dataCrkywCplckFlt001s = new ArrayList<>();
        while (iterator.hasNext()){
            DataCrkywCplckDefault next = iterator.next();
            DataCrkywCplckDefault oneData = dataCrkywCplckDefaultService.getOneData(next.getDataId());
            List<DataCrkywCplckFlt001> fltList = oneData.getFltList();
            dataCrkywCplckFlt001s.addAll(fltList);
        }
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("cplCrkTzdFltList",cplCrkTzdFltList);
        stringObjectHashMap.put("dataCrkywCplckFlt001s",dataCrkywCplckFlt001s);
        return stringObjectHashMap;
    }


    @Override
    public List<Map<String,Object>> getCplCrkTzdList(String unitId, String zylx){
        if (StrUtil.isNotBlank(zylx)){
            if (StrUtil.equals("3",zylx)){ //入库+退货入库
                zylx = "'3','7','5','9','10'";
            }else if(StrUtil.equals("5",zylx)){//退货入库
                zylx = "'5','9','10'";

            }else if(StrUtil.equals("7",zylx)){//正常入库
                zylx = "'3','7'";

            }else { //出库+采购退货出库
                zylx = "'4', '6','8','11'";
            }
        }
        List<Map<String,Object>> list = dataCrkywCpltzdxxDefaultMapper.getCplCrkTzdList(unitId,zylx);
        if (list != null && list.size() > 0 ){
            QueryWrapper<DataCrkywCpltzdxxFlt001> queryWrapper = new QueryWrapper<>();
            for (int i = 0; i < list.size(); i++) {
                Map<String,Object>  map = list.get(i);
                String dataId = map.get("dataid").toString();
                queryWrapper.eq("mainDataId",dataId);
                List<Map<String,Object>> dataCrkywCplckFlt001s = dataCrkywCpltzdxxFlt001Service.getCplCrkTzdFltList(dataId);
                String mxpzValue = "";
                for (int j = 0; j < dataCrkywCplckFlt001s.size(); j++) {
                    Map<String,Object> dataCrkywCplckFlt001 = dataCrkywCplckFlt001s.get(j);
                    mxpzValue+= dataCrkywCplckFlt001.getOrDefault("sjjlspmc","")+",";
                }
                map.put("mxpzValue",StrUtil.sub(mxpzValue,0,mxpzValue.length()-1));
                list.set(i,map);
            }
        }
        return  list;
    }
    @Override
    public DataCrkywCpltzdxxDefault getOneData(String id) {
        DataCrkywCpltzdxxDefault dataCrkywCpltzdxxDefault = dataCrkywCpltzdxxDefaultMapper.selectById(id);
        List<DataCrkywCpltzdxxFlt001> list = dataCrkywCpltzdxxFlt001Service.getFltForMainDataId(id);
        if(list!=null && list.size()>0){
            dataCrkywCpltzdxxDefault.setFltList(list);
        }
        return dataCrkywCpltzdxxDefault;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveData(DataCrkywCpltzdxxDefault param) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        String tzdh = param.getTzdh();
        if (isExist(tzdh)){
            jsonObject.set("msg","此通知单已存在");
            return jsonObject;
        }
        String unitID = param.getUnitID();
        param.setSytelInfoID(unitID);
        param.setPeriodID("11");
        param.setDeptID(unitID); //部门id
        param.setUnitID(unitID); //
        param.setRoundID(0); //舍位id
        //样式id,流程id根据作业类型进行处理
        String zylx = param.getCazylx();
        if (StringUtils.indexOf("3,5,7,9,10",zylx) >=0 ){ //成品粮入库流程
            param.setFlowId("420801654D8F01A7D9FCE01B90A395E6"); //流程Id
        }
        if (StringUtils.indexOf("4,6,8,11",zylx) >=0){ //成品粮出库流程
            param.setFlowId("284344D15DCA72D90AA43C24BD4F9B47"); //流程Id
        }
        param.setWcsl(0.0); //完成数量
        //剩余数量=数量-完成数量（0）
        param.setSysl(param.getSl()-param.getWcsl());
        param.setFlowStatus(1); //流程状态
        if (!super.saveOrUpdate(param)) {
            jsonObject.set("msg","保存成品粮订单数据失败");
            return  jsonObject;

        }
        String dataID = param.getDataID();

        List<DataCrkywCpltzdxxFlt001> fltList = param.getFltList();
        if(!fltList.isEmpty() && fltList.size()>0){
            for (int i = 0; i < fltList.size(); i++) {
                DataCrkywCpltzdxxFlt001 dataCrkywCpltzdxxFlt001 = fltList.get(i);
                dataCrkywCpltzdxxFlt001.setMainDataID(dataID);
                dataCrkywCpltzdxxFlt001.setSytelInfoID(unitID);
                dataCrkywCpltzdxxFlt001.setPeriodID("11");
                dataCrkywCpltzdxxFlt001.setDeptID(unitID); //部门id
                dataCrkywCpltzdxxFlt001.setUnitID(unitID); //
                dataCrkywCpltzdxxFlt001.setRoundID(0); //舍位id
                dataCrkywCpltzdxxFlt001.setWcsl(0.0); //完成数量
                dataCrkywCpltzdxxFlt001.setSysl(dataCrkywCpltzdxxFlt001.getSl()); //剩余数量
                //剩余数量=数量-完成数量（0）
//                dataCrkywCpltzdxxFlt001.setSysl(dataCrkywCpltzdxxFlt001.getSl()-dataCrkywCpltzdxxFlt001.getWcsl());
                if (StringUtils.isBlank(dataCrkywCpltzdxxFlt001.getBuilder())){
                    dataCrkywCpltzdxxFlt001.setBuilder(unitID);
                    dataCrkywCpltzdxxFlt001.setEditor(unitID);
                }
            }
            if(!dataCrkywCpltzdxxFlt001Service.saveOrUpdateBatch(fltList)){
                throw  new Exception("保存成品粮订单从表数据失败");
            }

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

    /**
     * 通过单位号检查是否已经存在
     *
     * @param tzdh
     * @return
     */
    private boolean isExist(String tzdh) {
        QueryWrapper<DataCrkywCpltzdxxDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tzdh", tzdh);
        queryWrapper.last("limit 1");
        return super.getOne(queryWrapper) != null;
    }
}
