package com.ics.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ics.admin.domain.Customer;
import com.ics.admin.domain.Room;
import com.ics.admin.domain.meeting.DetailEquipment;
import com.ics.admin.domain.meeting.RoomEquipment;
import com.ics.admin.domain.meeting.StaffCustomer;
import com.ics.admin.domain.meeting.UserEquipment;
import com.ics.admin.mapper.IcsCustomerStaffMapper;
import com.ics.admin.service.ICustomerService;
import com.ics.admin.service.IIcsCustomerStaffService;
import com.ics.admin.service.IRoomService;
import com.ics.admin.service.meeting.IDetailEquipmentService;
import com.ics.admin.service.meeting.IRoomEquipmentService;
import com.ics.admin.service.meeting.IStaffCustomerService;
import com.ics.admin.service.meeting.IUserEquipmentService;
import com.ics.common.core.domain.IcsCustomerStaff;
import com.ics.common.utils.StringUtils;
import com.ics.system.domain.User;
import com.ics.system.mapper.UserMapper;
import com.ics.system.service.ICurrentUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 企业员工Service业务层处理
 *
 * @author ics
 * @date 2024-02-19
 */
@Service
public class IcsCustomerStaffServiceImpl extends ServiceImpl<IcsCustomerStaffMapper, IcsCustomerStaff> implements IIcsCustomerStaffService {
    @Autowired
    private IcsCustomerStaffMapper icsCustomerStaffMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IStaffCustomerService staffCustomerService;

    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IRoomService roomService;

    @Autowired
    private ICurrentUserService currentUserService;

    @Autowired
    private IRoomEquipmentService roomEquipmentService;

    @Autowired
    private IDetailEquipmentService detailEquipmentService;
    @Autowired
    private IUserEquipmentService userEquipmentService;


    /**
     * 查询企业员工
     *
     * @param id 企业员工ID
     * @return 企业员工
     */
    @Override
    public IcsCustomerStaff selectIcsCustomerStaffById(Long id) {
        return icsCustomerStaffMapper.selectById(id);
    }

    /**
     * 查询企业员工列表
     *
     * @param icsCustomerStaff 企业员工
     * @return 企业员工
     */
    @Override
    public List<IcsCustomerStaff> selectIcsCustomerStaffList(IcsCustomerStaff icsCustomerStaff) {
        return icsCustomerStaffMapper.selectIcsCustomerStaffList(icsCustomerStaff);
    }

    /**
     * 新增企业员工
     *
     * @param icsCustomerStaff 企业员工
     * @return 结果
     */

    @Override
    public int insertIcsCustomerStaff(IcsCustomerStaff icsCustomerStaff) {
        return icsCustomerStaffMapper.insert(icsCustomerStaff);
    }

    /**
     * 修改企业员工
     *
     * @param icsCustomerStaff 企业员工
     * @return 结果
     */
    @Override
    public int updateIcsCustomerStaff(IcsCustomerStaff icsCustomerStaff) {
        return icsCustomerStaffMapper.updateById(icsCustomerStaff);
    }

    /**
     * 删除企业员工对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteIcsCustomerStaffByIds(String ids) {
        String[] idsArray = StringUtils.split(ids, ",");
        return icsCustomerStaffMapper.deleteBatchIds(CollUtil.toList(idsArray));
    }

    /**
     * 删除企业员工信息
     *
     * @param id 企业员工ID
     * @return 结果
     */
    @Override
    public int deleteIcsCustomerStaffById(Long id) {
        return icsCustomerStaffMapper.deleteIcsCustomerStaffById(id);
    }

    public String checkMobileUnique(String mobile) {
        return icsCustomerStaffMapper.checkMobileUnique(mobile);
    }

    @Override
    public IcsCustomerStaff selectUserByOpenid(String openid) {

        return icsCustomerStaffMapper.selectUserByOpenid(openid);
    }

    @Override
    public List<IcsCustomerStaff> selectUserByCustomer(Long id) {

        IcsCustomerStaff icsCustomerStaff = new IcsCustomerStaff();
        icsCustomerStaff.setIcsCustomerId(id);
        return icsCustomerStaffMapper.selectIcsCustomerStaffList(icsCustomerStaff);
    }

    @Override
    public List<IcsCustomerStaff> selectListByUserIds(List<Long> userIds) {

        QueryWrapper<IcsCustomerStaff> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.in(CollUtil.isNotEmpty(userIds), "id", userIds);
        return icsCustomerStaffMapper.selectList(objectQueryWrapper);
    }

    @Override
    public List<IcsCustomerStaff> getStaffListNotId(IcsCustomerStaff icsCustomerStaff) {

        QueryWrapper<IcsCustomerStaff> wrapper = new QueryWrapper<>();
//        wrapper.ne(icsCustomerStaff.getIcsCustomerId() != null,"ics_customer_Id",icsCustomerStaff.getIcsCustomerId());
        wrapper.isNull("ics_customer_Id");
        return icsCustomerStaffMapper.selectList(wrapper);
    }

    @Override
    public List<IcsCustomerStaff> getStaffListByUser(IcsCustomerStaff icsCustomerStaff) {
        List<Long> list = userMapper.getStaffListByUser();
        System.out.println(list);

        QueryWrapper<IcsCustomerStaff> wrapper = new QueryWrapper<>();

        wrapper.notIn(CollUtil.isNotEmpty(list), "id", list);

        return icsCustomerStaffMapper.selectList(wrapper);
    }



    @Override
    public int updateByCustomer(IcsCustomerStaff customerStaff) {

        return icsCustomerStaffMapper.updateByCustomer(customerStaff);
    }

    @Override
    public List<IcsCustomerStaff> selectCustomerStaffList(IcsCustomerStaff icsCustomerStaff) {

        return icsCustomerStaffMapper.selectIcsCustomerStaffList(icsCustomerStaff);
    }

    @Override
    public String importCustomerStaff(List<IcsCustomerStaff> userList,Long customerId) {

        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (IcsCustomerStaff user : userList) {
            try {
                // 验证是否存在这个用户
                IcsCustomerStaff u = icsCustomerStaffMapper.selectUserByMobile(user.getMobile());
                if (StringUtils.isNull(u)) {
                    user.setCardNo("0");
                    user.setDataType("1");
                    user.setGender(user.getGender().equals("男") ? "0" : "1");
                    int insert = icsCustomerStaffMapper.insert(user);
                    if (insert > 0) {
                        StaffCustomer staffCustomer =new StaffCustomer();
                        staffCustomer.setStaffId(user.getId());
                        staffCustomer.setIcsCustomerId(customerId);
                        StaffCustomer staffCustomer1 = staffCustomerService.selectStaffIdAndCustomerId(customerId, user.getId());
                        if (staffCustomer1 == null) {
                            Customer customer = customerService.selectCustomerById(customerId);
                            if (customer != null){
                                staffCustomer.setParkId(customer.getParkId());
                                staffCustomer.setTenantId(customer.getTenantId());
                            }

                            staffCustomerService.insertStaffCustomer(staffCustomer);
                        }
                        //根据用户添加对应企业设备
                        queryDeviceByCustomerId(customerId,user.getId());
                    }
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getName() + " 导入成功");
                } else {
                    u.setCardNo("0");
                    u.setDataType("1");
                    u.setGender(user.getGender().equals("男") ? "0" : "1");
                    u.setUsername(user.getUsername());
                    u.setName(user.getName());
                    u.setAddress(user.getAddress());
                    u.setEmail(user.getEmail());
                    u.setDegree(user.getDegree());
                    u.setUrgent(user.getUrgent());
                    int insert = updateByCustomer(u);
                    StaffCustomer staffCustomer =new StaffCustomer();
                    staffCustomer.setStaffId(u.getId());
                    staffCustomer.setIcsCustomerId(customerId);

                    StaffCustomer staffCustomer1 = staffCustomerService.selectStaffIdAndCustomerId(customerId, u.getId());
                    if (staffCustomer1 == null) {
                        staffCustomerService.insertStaffCustomer(staffCustomer);
                        //根据用户添加对应企业设备
                        queryDeviceByCustomerId(customerId,u.getId());
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、账号 " + user.getName() + " 已更新");
                    }else {
                        failureNum++;
                        failureMsg.append("<br/>" + successNum + "、账号 " + user.getName() + "已经存在");
                    }

                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");

            throw new RuntimeException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<IcsCustomerStaff> getUserList(IcsCustomerStaff customerStaff) {

        return icsCustomerStaffMapper.getUserList(customerStaff);
    }

    @Override
    public IcsCustomerStaff selectByPhoneAndOpenId(String phoneNumber, String openid) {

        QueryWrapper<IcsCustomerStaff> wrapper = new QueryWrapper<>();

        wrapper.eq("mobile", phoneNumber);
        wrapper.in("openid", openid);

        return icsCustomerStaffMapper.selectOne(wrapper);
    }

    @Override
    public IcsCustomerStaff selectUserByMobile(String phone) {
        return  icsCustomerStaffMapper.selectUserByMobile(phone);
    }

    @Override
    public List<IcsCustomerStaff> selectList() {

        QueryWrapper<IcsCustomerStaff> wrapper = new QueryWrapper<>();
        wrapper.groupBy("id");

        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<IcsCustomerStaff> selectListByCustomerId() {

        return icsCustomerStaffMapper.selectListByCustomerId();


    }

    @Override
    public List<IcsCustomerStaff> selectCustomerStaff(IcsCustomerStaff icsCustomerStaff) {
        return icsCustomerStaffMapper.selectCustomerStaff(icsCustomerStaff);
    }


    //根据企业查询对应的设备
    public void  queryDeviceByCustomerId(Long customerId,Long userId){
        ArrayList<Long> ids = new ArrayList<>();

        Customer customer = customerService.selectCustomerById(customerId);
        //根据企业 查询对应的 房间，和对应的楼层
        String roomId = customer.getRoomId();
        List<String> roomIds = StrUtil.split(roomId, ',');
        List<Long> collect = roomIds.stream().map(Long::valueOf).collect(Collectors.toList());
        for (Long roomid : collect) {
            Room room = roomService.selectRoomById(roomid);
            if (null != room) {
                Long id = room.getId();
                List<RoomEquipment> roomEquipment = roomEquipmentService.selectByRoomId(id);
                if (CollUtil.isNotEmpty(roomEquipment)) {
                    for (RoomEquipment equipment : roomEquipment) {
                        ids.add(equipment.getEquipmentId());
                    }
                }
                List<DetailEquipment> detailEquipments = detailEquipmentService.selectByRoomId(room.getBuildingDetailId());
                if (CollUtil.isNotEmpty(detailEquipments)) {
                    for (DetailEquipment detailEquipment : detailEquipments) {
                        ids.add(detailEquipment.getEquipmentId());
                    }
                }
            }
        }

        //根据设备id
        for (Long id : ids) {
            UserEquipment userEquipment = new UserEquipment();
            userEquipment.setEquipmentId(id);
            userEquipment.setUserId(userId);
            userEquipment.setStartTime(customer.getStartDate());
            userEquipment.setEndDate(customer.getEndDate());
            List<UserEquipment> equipments = userEquipmentService.selectUserEquipmentList(userEquipment);
            if (CollUtil.isEmpty(equipments)) {
                userEquipmentService.insertUserEquipment(userEquipment);
            }
        }
    }

}
