package com.zhongshu.card.server.core.dao.devices.impl;

import com.github.microservice.components.data.mongo.mongo.helper.DBHelper;
import com.zhongshu.card.client.model.devices.DeviceUseRecordSearch;
import com.zhongshu.card.server.core.dao.BaseImpl;
import com.zhongshu.card.server.core.dao.devices.extend.DeviceUseRecordDaoExtend;
import com.zhongshu.card.server.core.domain.devices.DeviceUseRecords;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @Author TRX
 * @CreateDate: 2023/4/12
 * @Version: 1.0
 */
@Slf4j
public class DeviceUseRecordDaoImpl extends BaseImpl implements DeviceUseRecordDaoExtend {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private DBHelper dbHelper;

    @Override
    public Page<DeviceUseRecords> page(Pageable pageable, DeviceUseRecordSearch param) {
        Criteria criteria = buildCriteriaNotOid(param);

        // 所属项目
        if (StringUtils.isNotEmpty(param.getProjectOid())) {
            criteria.and("projectOid").is(param.getProjectOid());
        }

        // 设备类型
        if (param.getDeviceType() != null) {
            criteria.and("deviceType").is(param.getDeviceType());
        }

        if (param.getOperateType() != null) {
            criteria.and("operateType").is(param.getOperateType());
        }

        if (param.getOperateState() != null) {
            criteria.and("operateState").is(param.getOperateState());
        }

        if (StringUtils.isNotEmpty(param.getGateWayId())) {
            criteria.and("gateWayId").is(param.getGateWayId());
        }

        if (StringUtils.isNotEmpty(param.getBeLongOid())) {
            criteria.and("beLongOid").is(param.getBeLongOid());
        }

        if (StringUtils.isNotEmpty(param.getCardNo())) {
            criteria.and("cardNo").is(param.getCardNo());
        }

        if (StringUtils.isNotEmpty(param.getUserId())) {
            criteria.and("userId").is(param.getUserId());
        }

        // 模糊搜索
        List<Criteria> criterias = new ArrayList<>();
        if (StringUtils.isNotEmpty(param.getDeviceId())) {
            Pattern pattern = Pattern.compile("^.*" + param.getDeviceId() + ".*$");
            criterias.add(Criteria.where("deviceId").is(pattern));
        }
        if (!CollectionUtils.isEmpty(criterias)) {
            criteria.andOperator(criterias.toArray(new Criteria[]{}));
        }
        Sort sort = buildSort(param);
        Query query = Query.query(criteria);
        query.with(sort);
        return dbHelper.pages(query, pageable, DeviceUseRecords.class);
    }

    public DeviceUseRecords init(String mqttDataId, String token) {
        DeviceUseRecords doc = null;
        try {
            Query query = Query.query(Criteria.where("mqttDataId").is(mqttDataId).and("token").isNull());
            Update update = new Update()
                    .set("token", token)
                    .set("createTime", System.currentTimeMillis());
            FindAndModifyOptions options = new FindAndModifyOptions().upsert(true)
                    .returnNew(true);
            doc = mongoTemplate.findAndModify(query, update, options,
                    DeviceUseRecords.class);
        } catch (Exception e) {
            log.error("init {}", e.getMessage());
        }
        return doc;
    }

}
