package com.liquidnet.service.adam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.liquidnet.service.adam.constant.AdamAdminisConstants;
import com.liquidnet.service.adam.entity.AdamAdminisProcessHis;
import com.liquidnet.service.adam.mapper.AdamAdminisProcessHisMapper;
import com.liquidnet.service.adam.service.IAdamAdminisProcessHisService;
import com.liquidnet.service.adam.vo.AdamAdminisProcessHisVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class AdamAdminisProcessHisServiceImpl implements IAdamAdminisProcessHisService {
    @Autowired
    private AdamAdminisProcessHisMapper adminisProcessHisMapper;

    @Override
    public int record(AdamAdminisConstants.ProcessHisEnum hisEnum, Object sourceSnap, String[] arr) {
        AdamAdminisProcessHis processHis = new AdamAdminisProcessHis();

        processHis.setComId(arr[0]);
        processHis.setUserId(arr[1]);
        processHis.setHisTag(hisEnum.tag);
        processHis.setHisVal(hisEnum.val);
        processHis.setHisSnap("");
        processHis.setOperator(arr[2]);
        processHis.setOperatTime(LocalDateTime.now());
        processHis.setOperatorName(arr[3]);

        return adminisProcessHisMapper.insert(processHis);
    }

    @Override
    public Page<AdamAdminisProcessHisVo> queryPageListForProcessHis(String hisTag, int pageNo, int pageSize) {
        return this.queryPageListForProcessHis(hisTag, null, pageNo, pageSize);
    }

    @Override
    public Page<AdamAdminisProcessHisVo> queryPageListForProcessHis(String hisTag, String operatorUserId, int pageNo, int pageSize) {
        Page<AdamAdminisProcessHisVo> targetPage = new Page<>();

        LambdaQueryWrapper<AdamAdminisProcessHis> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(AdamAdminisProcessHis::getHisTag, hisTag)
                .eq(!StringUtils.isEmpty(operatorUserId), AdamAdminisProcessHis::getOperator, operatorUserId)
                .orderByDesc(AdamAdminisProcessHis::getOperatTime);

        Page<AdamAdminisProcessHis> sourcePage = adminisProcessHisMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);
        List<AdamAdminisProcessHis> sourceRecords = sourcePage.getRecords();

        List<AdamAdminisProcessHisVo> targetRecords = Lists.newArrayList();

        sourceRecords.forEach(r -> {
            targetRecords.add(AdamAdminisProcessHisVo.getNew().copy(r));
        });

        sourcePage.setRecords(null);
        BeanUtils.copyProperties(sourcePage, targetPage);
        targetPage.setRecords(targetRecords);
        return targetPage;
    }
}
