package com.qmth.sop.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.sop.business.bean.result.SysDeviceResult;
import com.qmth.sop.business.entity.SysDevice;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.mapper.SysDeviceMapper;
import com.qmth.sop.business.service.SysDeviceService;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.DeviceStatusEnum;
import com.qmth.sop.common.enums.ExceptionResultEnum;
import com.qmth.sop.common.enums.FieldUniqueEnum;
import com.qmth.sop.common.enums.InOutTypeEnum;
import com.qmth.sop.common.util.ResultUtil;
import com.qmth.sop.common.util.ServletUtil;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 设备配置表 服务实现.
 *
 * @author: shudonghui
 * @date: 2023-08-24 17:32:07
 * @version: 1.0
 * @email: shudonghui@qmth.com.cn
 * @Company: www.qmth.com.cn
 */
@Service
public class SysDeviceServiceImpl extends ServiceImpl<SysDeviceMapper, SysDevice> implements SysDeviceService {


    /**
     * 查询列表
     *
     * @param iPage
     * @return
     */
    @Override
    public IPage<SysDeviceResult> query(IPage<Map> iPage, Long supplierId, String brand, String model, String deviceCode,String serialNo, DeviceStatusEnum status, InOutTypeEnum bound, Boolean enable) {
        if (deviceCode != null && deviceCode.length() > 0){
            deviceCode = SystemConstant.translateSpecificSign(deviceCode);
        }
        if (serialNo != null && serialNo.length() > 0){
            serialNo = SystemConstant.translateSpecificSign(serialNo);
        }
        return this.baseMapper.query(iPage, supplierId,brand,model,deviceCode,serialNo,Objects.nonNull(status)?status.name():null,Objects.nonNull(bound)?bound.name():null,enable);
    }

    /**
     * 新增修改设备配置表
     *
     * @param sysDevice
     */
    @Override
    @Transactional
    public Boolean saveSysDevice(SysDevice sysDevice) {
        try {
            SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
            if (Objects.isNull(sysDevice.getId())) {// 新增
                sysDevice.setBound(InOutTypeEnum.IN);
                sysDevice.insertInfo(sysUser.getId());
            } else { // 修改
                sysDevice.updateInfo(sysUser.getId());
            }
            return saveOrUpdate(sysDevice);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                String errorColumn = e.getCause().toString();
                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
                throw ExceptionResultEnum.SQL_ERROR.exception("[" + FieldUniqueEnum.convertToTitle(columnStr) + "]数据不允许重复插入");
            } else if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        }
        return null;

    }


    @Override
    @Transactional
    public boolean disable(long[] ids) {
        List<Long> idList = Arrays.stream(ids).boxed().collect(Collectors.toList());
        return this.update(new UpdateWrapper<SysDevice>().lambda().in(SysDevice::getId, idList).set(SysDevice::getEnable, false));
    }

    @Override
    @Transactional
    public boolean enable(long[] ids) {
        List<Long> idList = Arrays.stream(ids).boxed().collect(Collectors.toList());
        return this.update(new LambdaUpdateWrapper<SysDevice>().in(SysDevice::getId, idList).set(SysDevice::getEnable, true));
    }

    @Override
    @Transactional
    public boolean delete(long[] ids) {
        List<Long> idList = Arrays.stream(ids).boxed().collect(Collectors.toList());
        return this.removeByIds(idList);
    }

    @Override
    @Transactional
    public void saveSysDevice(List<SysDevice> sysDevices) {
        this.saveBatch(sysDevices);
    }

}