package jp.agentec.abook.abv.bl.data.dao;

import java.util.List;

import jp.agentec.abook.abv.bl.common.db.Cursor;
import jp.agentec.abook.abv.bl.dto.TaskReportItemsDto;

/**
 * Created by leej on 2018/09/10.
 */

public class TaskReportItemsDao extends AbstractDao {

    /*package*/ TaskReportItemsDao() {
    }

    @Override
    protected TaskReportItemsDto convert(Cursor cursor) {
        TaskReportItemsDto dto = new TaskReportItemsDto();

        int column = cursor.getColumnIndex("task_key");
        if (column != -1) {
            dto.taskKey = cursor.getString(column);
        }

        column = cursor.getColumnIndex("task_report_level");
        if (column != -1) {
            dto.taskReportLevel = cursor.getInt(column);
        }

        column = cursor.getColumnIndex("item_key");
        if (column != -1) {
            dto.itemKey = cursor.getString(column);
        }
        column = cursor.getColumnIndex("input_value");
        if (column != -1) {
            dto.inputValue = cursor.getString(column);
        }

        return dto;
    }

    public void insertTaskReportItems(TaskReportItemsDto dto) {
        insert("insert into t_task_report_items (task_key, task_report_level, item_key, input_value) values (?,?,?,?)", dto.getInsertValues());
    }

    public List<TaskReportItemsDto> getTaskReportItemByTaskKey(String taskKey, int taskReportLevel) {
        return rawQueryGetDtoList("select * from t_task_report_items where task_key=? and task_report_level=?", new String[]{"" + taskKey, "" + taskReportLevel}, TaskReportItemsDto.class);
    }

    /**
     * 報告キー、報告担当レベル、itemKeyでデータ取得
     * @param taskKey
     * @param taskReportLevel
     * @param itemKey
     * @return
     */
    public TaskReportItemsDto getTaskReportItem(String taskKey, int taskReportLevel, String itemKey) {
        return rawQueryGetDto("SELECT * FROM t_task_report_items WHERE task_key=? AND task_report_level=? AND item_key=?", new String[]{"" + taskKey, "" + taskReportLevel, "" + itemKey}, TaskReportItemsDto.class);
    }

    public List<TaskReportItemsDto> getTaskReportItemByOperationId(Long operationId) {
        StringBuilder sb = new StringBuilder();
        sb.append(" select distinct ttri.* ");
        sb.append(" from t_task_report_items ttri ");
        sb.append(" inner join ");
        sb.append("     t_task tt ");
        sb.append("         ON tt.task_key == ttri.task_key ");
        sb.append("         WHERE tt.del_flg = 0");
        sb.append("         AND tt.operation_id = ?");
        return rawQueryGetDtoList(sb.toString(), new String[]{"" + operationId}, TaskReportItemsDto.class);
    }

    public boolean updateTaskReportItems(TaskReportItemsDto dto) {
        long count = update("update t_task_report_items set input_value=? where task_report_level=? and item_key=? and task_key=? ", dto.getUpdateValues());
        return (count > 0);
    }
}