package com.patzn.lims.online.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.patzn.cloud.commons.api.RestAssert;
import com.patzn.lims.common.Tf;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.web.Account;
import com.patzn.lims.online.dto.TableDataDTO;
import com.patzn.lims.online.entity.PtOnlFormField;
import com.patzn.lims.online.entity.PtOnlFormHead;
import com.patzn.lims.online.mapper.PtOnlFormHeadMapper;
import com.patzn.lims.online.service.IPtOnlFormFieldService;
import com.patzn.lims.online.service.IPtOnlFormHeadService;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 表单表 服务实现类
 * </p>
 *
 * @author wwd
 * @since 2020-05-07
 */
@Service
public class PtOnlFormHeadServiceImpl extends BaseServiceImpl<PtOnlFormHeadMapper, PtOnlFormHead> implements IPtOnlFormHeadService {

    @Autowired
    private IPtOnlFormFieldService ptOnlFormFieldService;

    @Override
    public Page<PtOnlFormHead> page(Page<PtOnlFormHead> page, PtOnlFormHead ptOnlFormHead) {
        QueryWrapper<PtOnlFormHead> wrapper = Wrappers.<PtOnlFormHead>query(ptOnlFormHead);
        return this.page(page, wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addOnlineTable(TableDataDTO dto, Account account) {
        PtAssert.fail(null == dto,"数据不能为空");
        PtOnlFormHead head = dto.getHead();
        PtAssert.fail(null == head,"表信息不能为空");
        List<PtOnlFormField> formFields = dto.getFields();
        if (CollectionUtils.isEmpty(formFields)){
            PtAssert.fail("表字段不能为空");
        }
        if (save(head)){
            for (PtOnlFormField field:formFields) {
                field.setFormHeadId(head.getId());
            }
        }
        return ptOnlFormFieldService.saveBatch(formFields);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean synchTable(Long id, Account account) {
        if (null == id) {
            return  false;
        }
        PtOnlFormHead head=  getById(id);
        if ("是".equals(head.getIsDbSynch())){
            return  false;
        }
        List<PtOnlFormField> fields = ptOnlFormFieldService.listByHeadId(id);
        if (CollectionUtils.isEmpty(fields)){
            return  false;
        }
        baseMapper.executeDDL(Tf.getCtf(head,fields));
        PtOnlFormHead uHead = new PtOnlFormHead();
        uHead.setId(id);
        uHead.setIsDbSynch("是");
        return updateById(uHead);
    }
}
