package com.infoepoch.pms.agent.infractructure.basic.user;

import com.infoepoch.pms.agent.common.utils.LogHelper;
import com.infoepoch.pms.agent.common.utils.OracleUtils;
import com.infoepoch.pms.agent.domain.baisc.user.ISupplierEmployeeRepository;
import com.infoepoch.pms.agent.domain.baisc.user.SupplierEmployee;
import com.infoepoch.pms.agent.domain.baisc.user.SupplierEmployeeCriteria;
import com.infoepoch.pms.agent.platform.shared.exception.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

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

/**
 * @author jiangyz
 * @date 2026/4/10 10:07
 * 合作单位用户仓储实现
 */
@Repository
public class SupplierEmployeeRepository implements ISupplierEmployeeRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 新增
     */
    @Override
    public boolean insert(SupplierEmployee entity) {
        String sql = "INSERT INTO T_SUPPLIEREMPLOYEE(SE_ID, SE_NAME, SE_SUPPLIER, SE_PHONE, SE_USER_NAME, SE_PASS_WORD, SE_RECORD_TIME, SE_DISABLED) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        int result;
        try {
            result = jdbcTemplate.update(sql, entity.getId(), entity.getName(), entity.getSupplier(), entity.getPhone(), entity.getUserName(), entity.getPassWord(), entity.getRecordTime(), entity.getDisabled());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("新增 合作单位用户 数据 失败。");
        }
        return result > 0;
    }

    /**
     * 更新
     */
    @Override
    public boolean update(SupplierEmployee entity) {
        String sql = "UPDATE T_SUPPLIEREMPLOYEE SET SE_NAME = ?, SE_SUPPLIER = ?, SE_PHONE = ?, SE_USER_NAME = ?, SE_PASS_WORD = ?, SE_RECORD_TIME = ?, SE_DISABLED = ? WHERE SE_ID = ?";
        int result;
        try {
            result = jdbcTemplate.update(sql, entity.getName(), entity.getSupplier(), entity.getPhone(), entity.getUserName(), entity.getPassWord(), entity.getRecordTime(), entity.getDisabled(), entity.getId());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("更新 合作单位用户 数据 失败。");
        }
        return result >= 0;
    }

    /**
     * 批量新增
     */
    public int[] batchInsert(List<SupplierEmployee> list) {
        String sql = "INSERT INTO T_SUPPLIEREMPLOYEE(SE_ID, SE_NAME, SE_SUPPLIER, SE_PHONE, SE_USER_NAME, SE_PASS_WORD, SE_RECORD_TIME, SE_DISABLED) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                SupplierEmployee item = list.get(i);
                ps.setString(++j, item.getId());
                ps.setString(++j, item.getName());
                ps.setString(++j, item.getSupplier());
                ps.setString(++j, item.getPhone());
                ps.setString(++j, item.getUserName());
                ps.setString(++j, item.getPassWord());
                ps.setTimestamp(++j, item.getRecordTime() != null ? new Timestamp(item.getRecordTime().getTime()) : null);
                ps.setBoolean(++j, item.getDisabled());
            }

            @Override
            public int getBatchSize() {
                return list.size();
            }
        });
        return result;
    }

    /**
     * 批量更新
     */
    public int[] batchUpdate(List<SupplierEmployee> list) {
        String sql = "UPDATE T_SUPPLIEREMPLOYEE SET SE_NAME = ?, SE_SUPPLIER = ?, SE_PHONE = ?, SE_USER_NAME = ?, SE_PASS_WORD = ?, SE_RECORD_TIME = ?, SE_DISABLED = ? WHERE SE_ID = ? ";
        int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                int j = 0;
                SupplierEmployee item = list.get(i);
                ps.setString(++j, item.getName());
                ps.setString(++j, item.getSupplier());
                ps.setString(++j, item.getPhone());
                ps.setString(++j, item.getUserName());
                ps.setString(++j, item.getPassWord());
                ps.setTimestamp(++j, item.getRecordTime() != null ? new Timestamp(item.getRecordTime().getTime()) : null);
                ps.setBoolean(++j, item.getDisabled());
                ps.setString(++j, item.getId());
            }

            @Override
            public int getBatchSize() {
                return list.size();
            }
        });
        return result;
    }

    /**
     * 删除
     */
    @Override
    public boolean delete(String id) {
        String sql = "DELETE FROM T_SUPPLIEREMPLOYEE WHERE SE_ID = ?";
        int result;
        try {
            result = jdbcTemplate.update(sql, id);
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            throw new ValidationException("删除 合作单位用户 数据 失败。");
        }
        return result > 0;
    }

    /**
     * 根据Id查询
     */
    @Override
    public SupplierEmployee selectById(String id) {
        String sql = "SELECT * FROM T_SUPPLIEREMPLOYEE WHERE SE_ID = ? ";
        try {
            return jdbcTemplate.queryForObject(sql, new SupplierEmployeeRowMapper(), id);
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            return null;
        }
    }

    /**
     * 根据查询条件查询单个对象
     */
    @Override
    public SupplierEmployee selectOneByCriteria(SupplierEmployeeCriteria criteria) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM T_SUPPLIEREMPLOYEE ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria), 1, 1);
        try {
            return jdbcTemplate.queryForObject(buffer.toString(), list.toArray(), new SupplierEmployeeRowMapper());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            return null;
        }
    }

    /**
     * 根据查询条件查询对象集合
     */
    @Override
    public List<SupplierEmployee> selectByCriteria(SupplierEmployeeCriteria criteria) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM T_SUPPLIEREMPLOYEE ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria));
        try {
            return jdbcTemplate.query(buffer.toString(), list.toArray(), new SupplierEmployeeRowMapper());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            return null;
        }
    }

    /**
     * 根据查询条件分页查询对象结合
     */
    @Override
    public List<SupplierEmployee> selectCriteriaByPage(SupplierEmployeeCriteria criteria, int pageNum, int pageSize) {
        StringBuffer buffer = new StringBuffer("SELECT * FROM T_SUPPLIEREMPLOYEE ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria), pageNum, pageSize);
        try {
            return jdbcTemplate.query(buffer.toString(), list.toArray(), new SupplierEmployeeRowMapper());
        } catch (Exception e) {
            LogHelper.error(this,this.getClass().getName(),e);
            return null;
        }
    }

    /**
     * 根据条件查询对象总记录数
     */
    @Override
    public Integer selectCountByCriteria(SupplierEmployeeCriteria criteria) {
        StringBuffer buffer = new StringBuffer("SELECT COUNT(*) FROM T_SUPPLIEREMPLOYEE ");
        List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria));
        int count = jdbcTemplate.queryForObject(buffer.toString(), list.toArray(), int.class);
        return count;
    }

    /**
     * RowMapper
     */
    private class SupplierEmployeeRowMapper implements RowMapper<SupplierEmployee> {
        @Override
        public SupplierEmployee mapRow(ResultSet rs, int i) throws SQLException {
            return new SupplierEmployee(
                    rs.getString("SE_ID"),
                    rs.getString("SE_NAME"),
                    rs.getString("SE_SUPPLIER"),
                    rs.getString("SE_PHONE"),
                    rs.getString("SE_USER_NAME"),
                    rs.getString("SE_PASS_WORD"),
                    rs.getTimestamp("SE_RECORD_TIME"),
                    rs.getBoolean("SE_DISABLED")
            );
        }
    }

    /**
     * 创建查询条件
     */
    private Map<String, Object> createCriteriaSql(SupplierEmployeeCriteria criteria) {
        Map<String, Object> andMap = new LinkedHashMap<>();
        if (criteria == null)
            return andMap;
        //if (criteria.byId())
        //    andMap.put(criteria.getId() == null ? " T_Id IS NULL " : " T_Id = ? ", criteria.getId());

        //姓名
        if (criteria.byName())
            andMap.put(criteria.getName() == null ? " SE_NAME IS NULL " : " SE_NAME = ? ", criteria.getName());
        //姓名（LIKE）
        if (criteria.byNameContain())
            andMap.put(" SE_NAME LIKE ? ", "%" + criteria.getNameContain() + "%");
        //单位名称
        if (criteria.bySupplier())
            andMap.put(criteria.getSupplier() == null ? " SE_SUPPLIER IS NULL " : " SE_SUPPLIER = ? ", criteria.getSupplier());
        //单位名称（LIKE）
        if (criteria.bySupplierContain())
            andMap.put(" SE_SUPPLIER LIKE ? ", "%" + criteria.getSupplierContain() + "%");
        //手机号
        if (criteria.byPhone())
            andMap.put(criteria.getPhone() == null ? " SE_PHONE IS NULL " : " SE_PHONE = ? ", criteria.getPhone());
        //手机号（LIKE）
        if (criteria.byPhoneContain())
            andMap.put(" SE_PHONE LIKE ? ", "%" + criteria.getPhoneContain() + "%");
        //登录用户名
        if (criteria.byUserName())
            andMap.put(criteria.getUserName() == null ? " SE_USER_NAME IS NULL " : " SE_USER_NAME = ? ", criteria.getUserName());
        //登录用户名（LIKE）
        if (criteria.byUserNameContain())
            andMap.put(" SE_USER_NAME LIKE ? ", "%" + criteria.getUserNameContain() + "%");
        return andMap;
    }

}