package com.ym.mec.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ym.mec.biz.dal.dao.TenantContractRecordDao;
import com.ym.mec.biz.dal.entity.TenantContractRecord;
import com.ym.mec.biz.dal.entity.TenantContractRecord.TenantContractRecordEnum;
import com.ym.mec.biz.service.TenantContractRecordService;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.page.PageUtil;
import com.ym.mec.common.page.WrapperUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * 机构协议记录表(TenantContractRecord)表服务实现类
 *
 * @author hgw
 * @since 2022-02-12 16:16:41
 */
@Service("tenantContractRecordService")
public class TenantContractRecordServiceImpl extends ServiceImpl<TenantContractRecordDao, TenantContractRecord> implements TenantContractRecordService {

    private final static Logger log = LoggerFactory.getLogger(TenantContractRecordServiceImpl.class);

    /**
     * 写入协议记录
     *
     * @param tenantId     机构id
     * @param contractPath 文件地址
     * @param en           文件类型
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertContractRecord(Integer tenantId, String contractPath, TenantContractRecordEnum en) {
        if(en.equals(TenantContractRecordEnum.OPEN)){
            //一个机构只能创建一个开通协议
            TenantContractRecord open = this.getOne(new QueryWrapper<>(new TenantContractRecord())
                    .eq("tenant_id_", tenantId)
                    .eq("type_", TenantContractRecordEnum.OPEN.getType()));
            if (Objects.nonNull(open)) {
                return 1;
            }
        }

        Date now = new Date();
        TenantContractRecord record = new TenantContractRecord();
        record.setContractName(en.getMsg());
        record.setType(en.getType());
        record.setTenantId(tenantId);
        record.setUrl(contractPath);
        record.setBizDate(now);
        record.setCreateTime(now);
        return baseMapper.insert(record);
    }

    /**
     * 分页查询
     *
     * @param param 条件
     */
    @Override
    public PageInfo<TenantContractRecord> queryPage(Map<String, Object> param) {
        Page<TenantContractRecord> pageInfo = PageUtil.getPageInfo(param);
        //分页查询
        IPage<TenantContractRecord> page = this.page(pageInfo,
                new WrapperUtil<TenantContractRecord>()
                        .hasEq("type_", param.get("type"))
                        .hasEq("tenant_id_", param.get("tenantId"))
                        .queryWrapper());
        return PageUtil.pageInfo(page);
    }

}

