package com.zehong.system.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.zehong.common.core.domain.model.LoginUser;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.system.domain.*;
import com.zehong.system.domain.vo.GasUserAndSafetyDeviceVo;
import com.zehong.system.domain.vo.UserManageGasUserExportVo;
import com.zehong.system.domain.vo.UserManageSafetyDeviceExportVo;
import com.zehong.system.domain.vo.YeHuaqiUserManageSafetyDeviceExportVo;
import com.zehong.system.mapper.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zehong.system.service.ITYehuaqiUserService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * 燃气用户Service业务层处理
 * 
 * @author zehong
 * @date 2022-09-14
 */
@Service
public class TYehuaqiUserServiceImpl implements ITYehuaqiUserService 
{
    @Resource
    private TYehuaqiUserMapper tYehuaqiUserMapper;
    @Resource
    private TYehuaqiDeviceMapper tYehuaqiDeviceMapper;

    @Resource
    private TYehuaqiuserSafetyDeviceInfoMapper yehuaqiuserSafetyDeviceInfoMapper;

    @Resource
    private DataSource dataSource;

    @Resource
    private TEnterpriseInfoMapper tEnterpriseInfoMapper;

    @Resource
    private TUserManageVillageMapper villageMapper;

    /**
     * 查询燃气用户
     * 
     * @param userId 燃气用户ID
     * @return 燃气用户
     */
    @Override
    public TYehuaqiUser selectTYehuaqiUserById(Long userId)
    {
        return tYehuaqiUserMapper.selectTYehuaqiUserById(userId);
    }

    /**
     * 查询燃气用户列表
     * 
     * @param tYehuaqiUser 燃气用户
     * @return 燃气用户
     */
    @Override
    public List<TYehuaqiUser> selectTYehuaqiUserList(TYehuaqiUser tYehuaqiUser)
    {
        return tYehuaqiUserMapper.selectTYehuaqiUserList(tYehuaqiUser);
    }

    /**
     * 根据 userOwnId list 和 enterpriseId 查询数据
     * @param userOwnIds userOwnId list
     * @param enterpriseId enterpriseId
     * @return r
     */
    @Override
    public List<TYehuaqiUser> queryByUserOwnIdAndEnterpriseIdForThirdParty(List<String> userOwnIds, String enterpriseId) {
        return tYehuaqiUserMapper.queryByUserOwnIdAndEnterpriseIdForThirdParty(userOwnIds,enterpriseId);
    }

    @Override
    public List<TYehuaqiUser> selectAllUserList(TYehuaqiUser tYehuaqiUser)
    {
        List<TYehuaqiUser> list =  tYehuaqiUserMapper.selectTYehuaqiUserListTwo(tYehuaqiUser);
        for (TYehuaqiUser user : list){
            TYehuaqiDevice d = new TYehuaqiDevice();
            d.setUserId(user.getUserId());
            List<TYehuaqiDevice> devices = tYehuaqiDeviceMapper.selectTYehuaqiDeviceList(d);
            user.setDeviceNum(devices.size());
        }
        return list;
    }

    /**
     * 根据企业id统计错误数据
     * @return r
     */
    @Override
    public int countByBeyondEnterpriseId() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String deptId = loginUser.getUser().getDeptId();

        return tYehuaqiUserMapper.countByBeyondEnterpriseId(deptId);
    }

    /**
     * 新增燃气用户
     * 
     * @param tYehuaqiUser 燃气用户
     * @return 结果
     */
    @Override
    public int insertTYehuaqiUser(TYehuaqiUser tYehuaqiUser)
    {
        tYehuaqiUser.setCreateTime(DateUtils.getNowDate());
        return tYehuaqiUserMapper.insertTYehuaqiUser(tYehuaqiUser);
    }

    /**
     * 批量插入
     * @param tYehuaqiUsers t
     * @return r
     */
    @Override
    public int insertBatch(List<TYehuaqiUser> tYehuaqiUsers) {
        return tYehuaqiUserMapper.insertBatch(tYehuaqiUsers);
    }

    /**
     * 提供给第三方接口调用时的批量插入
     * @param tYehuaqiUsers r
     * @return r
     */
    public int insertBatchForThirdParty(List<TYehuaqiUser> tYehuaqiUsers){
        return tYehuaqiUserMapper.insertBatchForThirdParty(tYehuaqiUsers);
    }

    /**
     * 修改燃气用户
     * 
     * @param tYehuaqiUser 燃气用户
     * @return 结果
     */
    @Override
    public int updateTYehuaqiUser(TYehuaqiUser tYehuaqiUser)
    {
        tYehuaqiUser.setUpdateTime(DateUtils.getNowDate());
        return tYehuaqiUserMapper.updateTYehuaqiUser(tYehuaqiUser);
    }

    /**
     * 批量修改
     * @param tYehuaqiUsers t
     * @return r
     */
    @Override
    public int updateBatch(List<TYehuaqiUser> tYehuaqiUsers) {
        return tYehuaqiUserMapper.updateBatch(tYehuaqiUsers);
    }

    /**
     * 批量删除燃气用户
     * 
     * @param userIds 需要删除的燃气用户ID
     * @return 结果
     */
    @Override
    public int deleteTYehuaqiUserByIds(Long[] userIds)
    {
        return tYehuaqiUserMapper.deleteTYehuaqiUserByIds(userIds);
    }

    /**
     * 删除燃气用户信息
     * 
     * @param userId 燃气用户ID
     * @return 结果
     */
    @Override
    public int deleteTYehuaqiUserById(Long userId)
    {
        return tYehuaqiUserMapper.deleteTYehuaqiUserById(userId);
    }

    /**
     * 新增燃气用户 和 安全装置
     * @param gasUserAndSafetyDeviceVo gas
     * @return r
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addUserAndSafetyDevice(GasUserAndSafetyDeviceVo gasUserAndSafetyDeviceVo) {
        TYehuaqiUser yehuaqiUser = gasUserAndSafetyDeviceVo.getYehuaqiUser();
        tYehuaqiUserMapper.insertTYehuaqiUser(yehuaqiUser);
        List<TYehuaqiuserSafetyDeviceInfo> yehuaqiuserSafetyDeviceInfos = gasUserAndSafetyDeviceVo.getYehuaqiuserSafetyDeviceInfos();
        if (yehuaqiuserSafetyDeviceInfos != null && yehuaqiuserSafetyDeviceInfos.size() > 0) {
            for (TYehuaqiuserSafetyDeviceInfo yehuaqiuserSafetyDeviceInfo : yehuaqiuserSafetyDeviceInfos) {
                yehuaqiuserSafetyDeviceInfo.setfRelationUserId(yehuaqiUser.getUserId());;
            }
            yehuaqiuserSafetyDeviceInfoMapper.insertBatch(yehuaqiuserSafetyDeviceInfos);
        }
        return 1;
    }


    /**
     * 修改燃气用户 和 安全装置
     * @param gasUserAndSafetyDeviceVo gas
     * @return r
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserAndSafetyDevice(GasUserAndSafetyDeviceVo gasUserAndSafetyDeviceVo) {

        TYehuaqiUser yehuaqiUser = gasUserAndSafetyDeviceVo.getYehuaqiUser();
        tYehuaqiUserMapper.updateTYehuaqiUser(yehuaqiUser);
        List<TYehuaqiuserSafetyDeviceInfo> yehuaqiuserSafetyDeviceInfos = gasUserAndSafetyDeviceVo.getYehuaqiuserSafetyDeviceInfos();
        if (yehuaqiuserSafetyDeviceInfos != null && yehuaqiuserSafetyDeviceInfos.size() > 0) {
            for (TYehuaqiuserSafetyDeviceInfo yehuaqiuserSafetyDeviceInfo : yehuaqiuserSafetyDeviceInfos) {
                yehuaqiuserSafetyDeviceInfo.setfRelationUserId(yehuaqiUser.getUserId());
            }
        }

        yehuaqiuserSafetyDeviceInfoMapper.deleteYehuaqiuserSafetyDeviceInfoUserId(yehuaqiUser.getUserId());
        if (yehuaqiuserSafetyDeviceInfos != null && yehuaqiuserSafetyDeviceInfos.size() > 0) {
            yehuaqiuserSafetyDeviceInfoMapper.insertBatch(yehuaqiuserSafetyDeviceInfos);
        }
        return 1;
    }

    /**
     * 查询燃气用户列表 - 导出使用
     *
     * @param yehuaqiUser 液化气用户
     * @return 燃气用户集合
     */
    @Override
    public List<TYehuaqiUser> selectForExportTYehuaqiUserList(TYehuaqiUser yehuaqiUser) {
        return tYehuaqiUserMapper.selectForExportTYehuaqiUserList(yehuaqiUser);
    }

    /**
     * 根据userOwnIds 和  enterpriseId 查询数据
     * @param userOwnIds u
     * @param enterpriseId e
     * @return r
     */
    @Override
    public List<TYehuaqiUser> queryByUserOwnIdsAndEnterpriseId(List<String> userOwnIds, String enterpriseId) {
        return tYehuaqiUserMapper.queryByUserOwnIdsAndEnterpriseId(userOwnIds,enterpriseId);
    }

    /**
     * 批量插入 安全装置
     * @param yehuaqiuserSafetyDeviceInfos y
     * @return r
     */
    @Override
    public int insertBatchSafetyDevice(List<TYehuaqiuserSafetyDeviceInfo> yehuaqiuserSafetyDeviceInfos) {
        return yehuaqiuserSafetyDeviceInfoMapper.insertBatch(yehuaqiuserSafetyDeviceInfos);
    }

    /**
     * 根据 用户userId 集合删除数据
     * @param userIds u
     * @return r
     */
    @Override
    public int deleteBatchSafetyDeviceByUserIds(List<Long> userIds) {
        return 0;
    }

    /**
     * 处理解析好的 自定义模版的导入的数据 多sheet
     * @param gasUserExportVos d 燃气用户数据
     * @param safetyDeviceExportVos s 安全装置信息
     * @param reImportOfIncorrectDataFlag r 错误数据重新导入标志  true 表示错误数据重新导入
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleCustomMoreSheetImportData(List<UserManageGasUserExportVo> gasUserExportVos,
                                                List<YeHuaqiUserManageSafetyDeviceExportVo> safetyDeviceExportVos,
                                                boolean updateSupport,boolean reImportOfIncorrectDataFlag) {

        List<TYehuaqiUser> successDataList = new ArrayList<>();

        List<TYehuaqiUser> errorDataList = new ArrayList<>();

        // 安全装置 按照 用户自由id 分组
        Map<String, List<YeHuaqiUserManageSafetyDeviceExportVo>> safetyDeviceList = null;

        if (gasUserExportVos.size() > 0) {
            if (safetyDeviceExportVos != null && safetyDeviceExportVos.size() > 0) {
                safetyDeviceList = safetyDeviceExportVos.stream().collect(Collectors.groupingBy(YeHuaqiUserManageSafetyDeviceExportVo::getUserOwnId));
            }

            TYehuaqiUser tYehuaqiUser;
            StringBuilder stringBuilder = new StringBuilder();
            for (UserManageGasUserExportVo gasUserExportVo : gasUserExportVos) {
                String userOwnId = gasUserExportVo.getUserOwnId();
                String userType = gasUserExportVo.getUserType();
                String beyondEnterpriseName = gasUserExportVo.getBeyondEnterpriseName();
                String villageName = gasUserExportVo.getVillageName();

                if(!reImportOfIncorrectDataFlag) {

                    if (StringUtils.isBlank(userOwnId)) {
                        stringBuilder.append("用户自由id为空|");
                    }
                }

                if ((StringUtils.isNotBlank(userType))){
                    if (!"1".equals(userType) && !"2".equals(userType)&& !"3".equals(userType)&& !"4".equals(userType)) {
                        stringBuilder.append("用户类型数据没按提示录入|");
                    }
                }

                if (StringUtils.isBlank(beyondEnterpriseName)) {
                    stringBuilder.append("所属企业为空|");
                } else {
                    List<TEnterpriseInfo> tEnterpriseInfos = tEnterpriseInfoMapper.selectTEnterpriseInfoByName(beyondEnterpriseName);
                    if (tEnterpriseInfos != null && tEnterpriseInfos.size() > 0) {
                        gasUserExportVo.setBeyondEnterpriseId(tEnterpriseInfos.get(0).getEnterpriseId());
                    } else {
                        stringBuilder.append("所属企业不存在|");
                    }
                }

                if (StringUtils.isBlank(villageName)) {
                    stringBuilder.append("居住区(村、庄)为空|");
                } else {
                    TUserManageVillage tUserManageVillage = new TUserManageVillage();
                    tUserManageVillage.setfVillageName(villageName);
                    List<TUserManageVillage> tUserManageVillages = villageMapper.selectTUserManageVillageList(tUserManageVillage);
                    if(tUserManageVillages == null || tUserManageVillages.size() == 0) {
                        stringBuilder.append("居住区(村、庄)不存在|");
                    } else{
                        Long aLong = tUserManageVillages.get(0).getfVillageId();
                        gasUserExportVo.setVillageId(aLong);
                    }
                }

                //说明有错误数据
                if (StringUtils.isNotBlank(stringBuilder.toString())) {
                    tYehuaqiUser = new TYehuaqiUser();

                    BeanUtils.copyProperties(gasUserExportVo, tYehuaqiUser);

                    tYehuaqiUser.setErrorMsg(stringBuilder.toString());
                    stringBuilder = new StringBuilder();
                    errorDataList.add(tYehuaqiUser);
                    //正确数据
                } else {
                    TYehuaqiUser yehuaqiUser = new TYehuaqiUser();
                    BeanUtils.copyProperties(gasUserExportVo,yehuaqiUser);
                    successDataList.add(yehuaqiUser);
                }
            }
        }

        //错误数据批量插入错误表
        if (errorDataList.size() > 0) {
            tYehuaqiUserMapper.insertBatch(errorDataList);
            //安全装置的就直接插入
            initYehuaqiuserSafetyDeviceInfo(errorDataList, safetyDeviceList);
        }

        //正确数据插入后 生成id,再关联 安全装置
        if(successDataList.size() > 0) {

            //成功的数据里面如果有 userId，那说明是要修改的 要做区分
            List<TYehuaqiUser> addCollect = successDataList.stream().filter(item -> item.getUserId() == null).collect(Collectors.toList());
            if(addCollect.size() > 0) {
                tYehuaqiUserMapper.insertBatch(addCollect);
                if(safetyDeviceList != null && safetyDeviceList.size() > 0) {

                    //安全装置的就直接插入
                    initYehuaqiuserSafetyDeviceInfo(addCollect, safetyDeviceList);
                }
            }
            //是要修改的
            List<TYehuaqiUser> updateCollect = successDataList.stream().filter(item -> item.getUserId() != null).collect(Collectors.toList());
            if (updateCollect.size() > 0 && reImportOfIncorrectDataFlag) {
                String sql = "UPDATE t_yehuaqi_user \n" +
                        "SET nick_name = ?,\n" +
                        "user_type = ?,\n" +
                        "f_village_id = ?,\n" +
                        "beyond_enterprise_id = ?,\n" +
                        "address = ?,\n" +
                        "linkman = ?,\n" +
                        "phone = ?,\n" +
                        "remarks = ?,\n" +
                        "error_msg = ? \n" +
                        "WHERE\n" +
                        "\tuser_id = ?";
                try (Connection conn = dataSource.getConnection()) {
                    PreparedStatement pstmt = conn.prepareStatement(sql);
                    for (TYehuaqiUser yehuaqiUser : updateCollect) {
                        pstmt.setString(1,yehuaqiUser.getNickName());
                        pstmt.setString(2,yehuaqiUser.getUserType());
                        pstmt.setLong(3,yehuaqiUser.getVillageId());
                        pstmt.setString(4,yehuaqiUser.getBeyondEnterpriseId());
                        pstmt.setString(5,yehuaqiUser.getAddress());
                        pstmt.setString(6,yehuaqiUser.getLinkman());
                        pstmt.setString(7,yehuaqiUser.getPhone());
                        pstmt.setString(8,yehuaqiUser.getRemarks());
                        pstmt.setString(9,null);
                        pstmt.setLong(10,yehuaqiUser.getUserId());
                        pstmt.addBatch();
                    }
                    pstmt.executeBatch();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 导入 单独处理 安全装置
     * @param list
     */
    private void initYehuaqiuserSafetyDeviceInfo(List<TYehuaqiUser> list, Map<String, List<YeHuaqiUserManageSafetyDeviceExportVo>> listMap) {

        List<TYehuaqiuserSafetyDeviceInfo> gasuserSafetyDeviceInfoList = new ArrayList<>();

        //正确的 和 错误的 都是先出入 后 再统一处理 安全装置。

        for (TYehuaqiUser yehuaqiUser : list) {
            String userOwnId = yehuaqiUser.getUserOwnId();
            List<YeHuaqiUserManageSafetyDeviceExportVo> userManageSafetyDeviceExportVos = listMap.get(userOwnId);
            if (userManageSafetyDeviceExportVos != null && userManageSafetyDeviceExportVos.size() > 0) {
                TYehuaqiuserSafetyDeviceInfo yehuaqiuserSafetyDeviceInfo;
                for (YeHuaqiUserManageSafetyDeviceExportVo userManageSafetyDeviceExportVo : userManageSafetyDeviceExportVos) {
                    yehuaqiuserSafetyDeviceInfo = new TYehuaqiuserSafetyDeviceInfo();
                    BeanUtils.copyProperties(userManageSafetyDeviceExportVo, yehuaqiuserSafetyDeviceInfo);
                    yehuaqiuserSafetyDeviceInfo.setfRelationUserId(yehuaqiUser.getUserId());
                    gasuserSafetyDeviceInfoList.add(yehuaqiuserSafetyDeviceInfo);
                }
            }
        }

        if (gasuserSafetyDeviceInfoList.size() > 0) {
            yehuaqiuserSafetyDeviceInfoMapper.insertBatch(gasuserSafetyDeviceInfoList);
        }
    }

    /**
     * 查询导入的错误数据
     * @return r
     */
    @Override
    public List<TYehuaqiUser> queryErrorDetectorUserList() {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        String deptId = loginUser.getUser().getDeptId();

        return tYehuaqiUserMapper.queryErrorDetectorUserList(deptId);
    }
}
