/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.youchain.businessdata.service.impl;

import com.alibaba.fastjson.JSON;
import com.youchain.basicdata.domain.Stock;
import com.youchain.businessdata.domain.PickOut;
import com.youchain.businessdata.domain.Task;
import com.youchain.businessdata.domain.TaskLog;
import com.youchain.businessdata.inputJson.IPTask;
import com.youchain.businessdata.returnJson.RPTaskList;
import com.youchain.businessdata.service.dto.TaskDto;
import com.youchain.businessdata.service.mapstruct.TaskMapper;
import com.youchain.utils.FileUtil;
import com.youchain.utils.PageUtil;
import com.youchain.utils.QueryHelp;
import com.youchain.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import com.youchain.businessdata.repository.TaskLogRepository;
import com.youchain.businessdata.service.TaskLogService;
import com.youchain.businessdata.service.dto.TaskLogDto;
import com.youchain.businessdata.service.dto.TaskLogQueryCriteria;
import com.youchain.businessdata.service.mapstruct.TaskLogMapper;
import org.hibernate.SQLQuery;
import org.hibernate.transform.AliasToEntityMapResultTransformer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * @author huojin
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-08-25
 **/
@Service
@RequiredArgsConstructor
public class TaskLogServiceImpl implements TaskLogService {

    private final TaskLogRepository taskLogRepository;
    private final TaskLogMapper taskLogMapper;
    private final TaskMapper taskMapper;
    private final EntityManager entityManager;

    @Override
    public Map<String, Object> queryAll(TaskLogQueryCriteria criteria, Pageable pageable) {
        Page<TaskLog> page = taskLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(taskLogMapper::toDto));
    }

    @Override
    public List<TaskLogDto> queryAll(TaskLogQueryCriteria criteria) {
        return taskLogMapper.toDto(taskLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public TaskLogDto findById(Long id) {
        TaskLog taskLog = taskLogRepository.findById(id).orElseGet(TaskLog::new);
        ValidationUtil.isNull(taskLog.getId(), "TaskLog", "id", id);
        return taskLogMapper.toDto(taskLog);
    }

    @Override
    @Transactional
    public TaskLog findEntityId(Long id) {
        TaskLog taskLog = taskLogRepository.findById(id).orElseGet(TaskLog::new);
        return taskLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TaskLogDto create(TaskLog resources) {
        return taskLogMapper.toDto(taskLogRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TaskLog resources) {
        TaskLog taskLog = taskLogRepository.findById(resources.getId()).orElseGet(TaskLog::new);
        ValidationUtil.isNull(taskLog.getId(), "TaskLog", "id", resources.getId());
        taskLog.copy(resources);
        taskLogRepository.save(taskLog);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            taskLogRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<TaskLogDto> all, HttpServletResponse response) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TaskLogDto taskLog : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("物料序号", taskLog.getItem());
            map.put("物料属性序号", taskLog.getItemKey());
            map.put("任务序号", taskLog.getTask());
            map.put("源容器", taskLog.getSrcStock());
            map.put("目标容器", taskLog.getDstStock());
            map.put("源点位", taskLog.getSrcPoint());
            map.put("目标点位", taskLog.getDstPoint());
            map.put("源容器编码", taskLog.getSrcStockCode());
            map.put("目标容器编码", taskLog.getDstStockCode());
            map.put("源点位编码", taskLog.getSrcLocCode());
            map.put("目标点位编码", taskLog.getDstLocCode());
            map.put("属性6", taskLog.getInvStatus());
            map.put("退回", taskLog.getBeBack());
            map.put("拣货数量", taskLog.getMoveQty());
            map.put("发运数量", taskLog.getShipQty());
            map.put("上架号", taskLog.getPutCode());
            map.put("库存ID", taskLog.getInvId());
            map.put("仓库ID", taskLog.getDept());
            map.put("创建人", taskLog.getCreateBy());
            map.put("修改人", taskLog.getUpdateBy());
            map.put("发运人", taskLog.getShipBy());
            map.put("发运时间", taskLog.getShipTime());
            map.put("创建时间", taskLog.getCreateTime());
            map.put("修改时间", taskLog.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public TaskLog getTaskLog(long taskId) {
        return taskLogRepository.getTaskLogbyTaskId(taskId);
    }

    @Override
    public void createTaskLogData(TaskDto tasks, double planQty) {
        Task task = taskMapper.toEntity(tasks);
        TaskLog taskLog = new TaskLog();
        taskLog.setItem(task.getItem());
        taskLog.setItemKey(task.getItemKey());
        taskLog.setTask(task);
        taskLog.setSrcStock(task.getSrcStock());
        taskLog.setDstStock(task.getDstStock());
        taskLog.setSrcPoint(task.getSrcPoint());
        taskLog.setDstPoint(task.getDstPoint());
        taskLog.setSrcStockCode(task.getSrcStockCode());
        taskLog.setDstStockCode(task.getDstStockCode());
        taskLog.setSrcLocCode(task.getSrcPointCode());
        taskLog.setDstLocCode(task.getDstPointCode());
        taskLog.setInvStatus(task.getInvStatus());
        taskLog.setMoveQty(planQty);
        taskLog.setShipQty(taskLog.getShipQty()==null?0d:taskLog.getShipQty());
//        taskLog.setShipQty(planQty);
        taskLog.setPutCode(task.getPutCode());
        taskLog.setInvId(task.getInvId());
        taskLog.setDept(task.getDept());
        this.create(taskLog);
    }

    @Override
    public TaskLog createTaskLog(Task task, double planQty, String stockCode,String xpp,String bhr) {
        TaskLog taskLog = new TaskLog();
        taskLog.setItem(task.getItem());
        taskLog.setItemKey(task.getItemKey());
        taskLog.setTask(task);
        taskLog.setSrcStock(task.getSrcStock());
        taskLog.setSrcPoint(task.getSrcPoint());
        taskLog.setDstPoint(task.getDstPoint());
        taskLog.setSrcStockCode(xpp);
        taskLog.setDstStockCode(stockCode);
        taskLog.setPutCode(bhr);
        taskLog.setSrcLocCode(task.getSrcPointCode());
        taskLog.setDstLocCode(task.getDstPointCode());
        taskLog.setInvStatus(task.getInvStatus());
        taskLog.setMoveQty(planQty);
        taskLog.setShipQty(0d);
        taskLog.setPutCode(task.getPutCode());
        taskLog.setInvId(task.getInvId());
        taskLog.setDept(task.getDept());
        if(task.getPickDetail()!=null) {
            taskLog.setShArea(task.getPickDetail().getShArea());
        }
        this.create(taskLog);
        return taskLog;
    }

    public  List<RPTaskList> queryTaskLogApp(IPTask t){
        String sql="SELECT it.code itemCode,it.`name` itemName,log.move_qty plan_qty,ik.prop_d1 pch,log.ship_qty bhs,log.dst_stock_code stockCode\n" +
                "from data_task_log log\n" +
                "left join data_item_key ik on ik.id=log.item_key_id\n" +
                "left join base_item it on it.id=ik.item_id\n" +
                " where 1=1 ";
        if(t.getPickTicketId()!=null&&!t.getPickTicketId().equals(0l)){
            sql+=" and log.pick_out_id="+t.getPickTicketId();
        }
        sql+= " ORDER BY it.code";
        List ts= entityManager.createNativeQuery(sql)
                .unwrap(SQLQuery.class)
                .setResultTransformer(
                        AliasToEntityMapResultTransformer.INSTANCE
                )
                .list();
        List<RPTaskList> l = JSON.parseArray(JSON.toJSONString(ts),RPTaskList.class);
        return  l;
    }



    public List<TaskLog> findByTph(String tph,Long outId) {
        String hql=" from TaskLog t where t.dstStockCode='"+tph+"' and t.pickOut.id is null and t.shipQty=0";
        if(outId!=null){
            hql=" from TaskLog t where t.pickOut.id="+outId+" and t.shipQty=0";
        }
        Query query=entityManager.createQuery(hql);
        List<TaskLog> logs=query.getResultList();
        return logs;
    }

    public List<TaskLog> findByLog(String xpp,String billCode) {
        String hql=" from TaskLog t where t.srcStockCode='"+xpp+"' and t.task.billCode='"+billCode+"' and t.shipQty=0";
        Query query=entityManager.createQuery(hql);
        List<TaskLog> logs=query.getResultList();
        return logs;
    }
}