/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2022/6/15
 */
package org.ts.ddcs.CheckController.Service.Impl;

import org.ts.ddcs.CheckController.Service.CheckService;
import org.ts.ddcs.CheckController.Service.Entity.RtuCheckInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/***
 * Date:2022/6/15
 * Title:文件所属模块（必须填写）
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@Service("CheckService")
public class CheckServiceImpl implements CheckService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<RtuCheckInfo> list(String orgId) {
        String sql = "SELECT ci.id,ci.check_title,ci.warning_id,w.warning_info,cpi.process_status_id,ci.rtu_code,rtu.rtu_name,d.name process_status_name ,cpi.process_suggest,cpi.service_person_id,sp.person_name,u.user_name,cpi.update_time,ci.create_time ";
        sql += " FROM check_info ci ";
        sql += " LEFT JOIN check_process_info cpi on cpi.process_main_id = ci.id ";
        sql += " LEFT JOIN t_dict d ON d.id = cpi.process_status_id ";
        sql += " LEFT JOIN basic_project_service_person sp ON sp.id = cpi.service_person_id ";
        sql += " LEFT JOIN t_au_user u ON u.id = ci.update_user ";
        sql += " LEFT JOIN t_b_rtu_warning w  ON w.id = ci.warning_id ";
        sql += " LEFT JOIN t_base_rtu_info rtu  ON rtu.rtu_cd = ci.rtu_code ";
        sql += " LEFT JOIN t_base_project p  ON p.id = rtu.project_id ";
        sql += " WHERE 1=1 ";
        if (null != orgId) {
            sql += " AND p.org_id='" + orgId + "' ";
        }
        sql += " AND ci.last_process_id = cpi.id";
        sql += " ORDER BY ci.create_time DESC";
        List<RtuCheckInfo> list = jdbcTemplate.query(sql, new RowMapper<RtuCheckInfo>() {

            @Override
            public RtuCheckInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                RtuCheckInfo info = new RtuCheckInfo();
                info.setId(resultSet.getString("id"));
                info.setRtuCode(resultSet.getString("rtu_code"));
                info.setRtuName(resultSet.getString("rtu_name"));
                info.setCheckTitle(resultSet.getString("check_title"));
                info.setCreateTime(resultSet.getTimestamp("create_time"));
                info.setUpdateTime(resultSet.getTimestamp("update_time"));
                info.setUpdateUser(resultSet.getString("user_name"));
                info.setProcessStatusId(resultSet.getString("process_status_id"));
                info.setProcessStatusName(resultSet.getString("process_status_name"));
                info.setProcessSuggest(resultSet.getString("process_suggest"));
                info.setServicePersonId(resultSet.getString("service_person_id"));
                info.setServicePersonName(resultSet.getString("person_name"));
                info.setWarningDesc(resultSet.getString("warning_info"));
                info.setWarningId(resultSet.getString("warning_id"));
                return info;
            }
        });
        return list;
    }

    @Override
    public RtuCheckInfo checkInfo(String checkId) {
        String sql = "SELECT ci.id,ci.check_title,ci.warning_id,w.warning_info,cpi.process_status_id,ci.rtu_code,rtu.rtu_name,d.name process_status_name ,cpi.process_suggest,cpi.service_person_id,sp.person_name,u.user_name,cpi.update_time,ci.create_time ";
        sql += " FROM check_info ci ";
        sql += " LEFT JOIN check_process_info cpi on cpi.process_main_id = ci.id ";
        sql += " LEFT JOIN t_dict d ON d.id = cpi.process_status_id ";
        sql += " LEFT JOIN basic_project_service_person sp ON sp.id = cpi.service_person_id ";
        sql += " LEFT JOIN t_au_user u ON u.id = ci.create_user ";
        sql += " LEFT JOIN t_b_rtu_warning w  ON w.id = ci.warning_id ";
        sql += " LEFT JOIN t_base_rtu_info rtu  ON rtu.rtu_cd = ci.rtu_code ";
        sql += " LEFT JOIN t_base_project p  ON p.id = rtu.project_id ";
        sql += " WHERE 1=1 ";
        sql += " AND ci.id = '" + checkId + "'";
        sql += " AND ci.last_process_id = cpi.id";
        List<RtuCheckInfo> list = jdbcTemplate.query(sql, new RowMapper<RtuCheckInfo>() {

            @Override
            public RtuCheckInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                RtuCheckInfo info = new RtuCheckInfo();
                info.setId(resultSet.getString("id"));
                info.setRtuCode(resultSet.getString("rtu_code"));
                info.setRtuName(resultSet.getString("rtu_name"));
                info.setCheckTitle(resultSet.getString("check_title"));
                info.setCreateTime(resultSet.getTimestamp("create_time"));
                info.setUpdateTime(resultSet.getTimestamp("update_time"));
                info.setCreateUser(resultSet.getString("user_name"));
                info.setProcessStatusId(resultSet.getString("process_status_id"));
                info.setProcessStatusName(resultSet.getString("process_status_name"));
                info.setProcessSuggest(resultSet.getString("process_suggest"));
                info.setServicePersonId(resultSet.getString("service_person_id"));
                info.setServicePersonName(resultSet.getString("person_name"));
                info.setWarningDesc(resultSet.getString("warning_info"));
                info.setWarningId(resultSet.getString("warning_id"));
                return info;
            }
        });
        if (null != list && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<RtuCheckInfo> processList(String checkId) {
        String sql = "SELECT cpi.ID,cpi.PROCESS_STATUS_ID,d.NAME PROCESS_STATUS_NAME ,cpi.PROCESS_SUGGEST,cpi.SERVICE_PERSON_ID,p.person_name,cpi.create_user,cpi.create_time,cpi.update_time,u.user_name ";
        sql += " FROM check_process_info cpi  ";
        sql += " LEFT JOIN t_dict d ON d.ID = cpi.PROCESS_STATUS_ID ";
        sql += " LEFT JOIN basic_project_service_person p ON p.sys_user_id = cpi.service_person_id ";
        sql += " LEFT JOIN t_au_user u ON u.id = cpi.create_user ";
        sql += " WHERE cpi.PROCESS_MAIN_ID ='" + checkId + "'  ORDER BY cpi.UPDATE_TIME DESC";
        List<RtuCheckInfo> list = jdbcTemplate.query(sql, new RowMapper<RtuCheckInfo>() {

            @Override
            public RtuCheckInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                RtuCheckInfo info = new RtuCheckInfo();
                info.setIndexNumber(i);
                info.setId(resultSet.getString("ID"));
                info.setCreateUser(resultSet.getString("user_name"));
                info.setCreateTime(resultSet.getTimestamp("create_time"));
                info.setUpdateTime(resultSet.getTimestamp("update_time"));
                info.setProcessStatusId(resultSet.getString("PROCESS_STATUS_ID"));
                info.setProcessStatusName(resultSet.getString("PROCESS_STATUS_NAME"));
                info.setProcessSuggest(resultSet.getString("PROCESS_SUGGEST"));
                info.setServicePersonId(resultSet.getString("SERVICE_PERSON_ID"));
                info.setServicePersonName(resultSet.getString("person_name"));
                return info;
            }
        });
        return list;
    }

    @Override
    public RtuCheckInfo processInfo(String processId) {
        String sql = "SELECT cpi.id,cpi.process_status_id,d.name process_status_name ,cpi.process_suggest,cpi.service_person_id,sp.person_name,u.user_name,cpi.update_time,cpi.create_time  FROM check_process_info cpi";
        sql += " LEFT JOIN t_dict d ON d.id = cpi.process_status_id";
        sql += " LEFT JOIN basic_project_service_person sp ON sp.id = cpi.service_person_id";
        sql += " LEFT JOIN t_au_user u ON u.id = cpi.create_user";
        sql += " WHERE 1=1 AND cpi.id ='" + processId + "'";

        List<RtuCheckInfo> list = jdbcTemplate.query(sql, new RowMapper<RtuCheckInfo>() {

            @Override
            public RtuCheckInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                RtuCheckInfo info = new RtuCheckInfo();
                info.setId(resultSet.getString("id"));
                info.setProcessStatusId(resultSet.getString("process_status_id"));
                info.setCreateTime(resultSet.getTimestamp("create_time"));
                info.setUpdateTime(resultSet.getTimestamp("update_time"));
                info.setCreateUser(resultSet.getString("user_name"));
                info.setProcessStatusName(resultSet.getString("process_status_name"));
                info.setProcessSuggest(resultSet.getString("process_suggest"));
                info.setServicePersonId(resultSet.getString("service_person_id"));
                info.setServicePersonName(resultSet.getString("person_name"));
                return info;
            }
        });
        if (null != list && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<String> processPhotos(String processId) {
        String sql = "SELECT pif.id,f.SAVED_PATH path FROM check_process_info_file pif";
        sql += " LEFT JOIN t_file f ON f.ID=pif.file_id";
        sql += " WHERE pif.is_del=0 AND pif.process_id= '" + processId + "'";
        List<String> list = jdbcTemplate.query(sql, new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getString("path");
            }
        });
        return list;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void saveProcess(String checkId, RtuCheckInfo rtuCheckInfo) {
        String sql = "UPDATE  check_info  SET LAST_PROCESS_ID=?,UPDATE_TIME=?  WHERE ID =?";
        String processId = UUID.randomUUID().toString().replace("-", "").toLowerCase();

        jdbcTemplate.update(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                int index = 0;
                preparedStatement.setString(++index, processId);
                preparedStatement.setTimestamp(++index, new Timestamp(System.currentTimeMillis()));
                preparedStatement.setString(++index, checkId);
            }
        });

        sql = "INSERT INTO check_process_info (id,process_main_id,service_person_id,process_status_id,process_suggest,create_user) VALUES(?,?,?,?,?,?)";

        jdbcTemplate.update(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                int index = 0;
                preparedStatement.setString(++index, processId);
                preparedStatement.setString(++index, checkId);
                preparedStatement.setString(++index, rtuCheckInfo.getServicePersonId());
                preparedStatement.setString(++index, rtuCheckInfo.getProcessStatusId());
                preparedStatement.setString(++index, rtuCheckInfo.getProcessSuggest());
                preparedStatement.setString(++index, rtuCheckInfo.getCreateUser());
            }
        });

        if (rtuCheckInfo.getPhotos() != null && rtuCheckInfo.getPhotos().size() > 0) {
            sql = "INSERT INTO check_process_info_file( `process_id`, `file_id`) VALUES ( ?, ?)";
            jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                    String fileId = rtuCheckInfo.getPhotos().get(i);
                    int index = 0;
                    preparedStatement.setString(++index, processId);
                    preparedStatement.setString(++index, fileId);
                }

                @Override
                public int getBatchSize() {
                    return rtuCheckInfo.getPhotos().size();
                }
            });
        }
    }
}
