package cn.stylefeng.team.form.modular.manage.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.entity.BaseEntity;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.team.form.api.entity.FormDefinition;
import cn.stylefeng.team.form.api.entity.FormModel;
import cn.stylefeng.team.form.modular.manage.entity.FormTemplate;
import cn.stylefeng.team.form.modular.manage.enums.FormDefinitionExceptionEnum;
import cn.stylefeng.team.form.modular.manage.enums.FormModelExceptionEnum;
import cn.stylefeng.team.form.modular.manage.enums.FormTemplateExceptionEnum;
import cn.stylefeng.team.form.modular.manage.mapper.FormTemplateMapper;
import cn.stylefeng.team.form.modular.manage.pojo.request.FormTemplateRequest;
import cn.stylefeng.team.form.modular.manage.service.FormDefinitionService;
import cn.stylefeng.team.form.modular.manage.service.FormModelService;
import cn.stylefeng.team.form.modular.manage.service.FormTemplateService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class FormTemplateServiceImpl extends ServiceImpl<FormTemplateMapper, FormTemplate> implements FormTemplateService {

    @Resource
    private FormModelService formModelService;

    @Resource
    private FormDefinitionService formDefinitionService;

    @Override
    public void add(FormTemplateRequest formTemplateRequest) {

        Long formModelId = formTemplateRequest.getFromModelId();

        FormModel formModel = formModelService.getById(formModelId);
        if (ObjectUtil.isEmpty(formModel)) {
            throw new ServiceException(FormModelExceptionEnum.FORM_MODEL_NOT_EXISTED);
        }

        FormDefinition formDefinition = formDefinitionService.getById(formModel.getCurrentDefinitionId());
        if (formDefinition == null) {
            throw new ServiceException(FormDefinitionExceptionEnum.FORM_DEFINITION_NOT_EXISTED);
        }

        this.validateRepeatTemplate(formModel.getFormModelCode(), false, null);

        FormTemplate formTemplate = new FormTemplate();
        formTemplate.setTemplateName(formModel.getFormModelName());
        formTemplate.setTemplateCode(formModel.getFormModelCode());
        formTemplate.setTemplateSort(formModel.getFldSort());
        formTemplate.setFormConfig(formDefinition.getFormConfig());
        formTemplate.setMobileFormConfig(formDefinition.getMobileFormConfig());
        this.save(formTemplate);
    }

    @Override
    public void del(FormTemplateRequest formTemplateRequest) {
        FormTemplate formTemplate = this.queryFormTemplate(formTemplateRequest);
        this.removeById(formTemplate.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(FormTemplateRequest formTemplateRequest) {
        this.removeByIds(formTemplateRequest.getBatchDeleteIdList());
    }

    @Override
    public void edit(FormTemplateRequest formTemplateRequest) {

        this.validateRepeatTemplate(formTemplateRequest.getTemplateCode(), true, formTemplateRequest.getId());

        FormTemplate formTemplate = this.queryFormTemplate(formTemplateRequest);

        formTemplate.setTemplateName(formTemplateRequest.getTemplateName());
        formTemplate.setTemplateCode(formTemplateRequest.getTemplateCode());
        formTemplate.setTemplateSort(formTemplateRequest.getTemplateSort());

        this.updateById(formTemplate);
    }

    @Override
    public FormTemplate detail(FormTemplateRequest formTemplateRequest) {
        return this.queryFormTemplate(formTemplateRequest);
    }

    @Override
    public PageResult<FormTemplate> findPage(FormTemplateRequest formTemplateRequest) {
        LambdaQueryWrapper<FormTemplate> wrapper = createWrapper(formTemplateRequest);

        wrapper.select(FormTemplate::getTemplateName, FormTemplate::getTemplateCode, FormTemplate::getTemplateSort, BaseEntity::getCreateTime, FormTemplate::getId);

        Page<FormTemplate> pageList = this.page(PageFactory.defaultPage(), wrapper);
        return PageResultFactory.createPageResult(pageList);
    }

    @Override
    public List<FormTemplate> findList(FormTemplateRequest formTemplateRequest) {
        LambdaQueryWrapper<FormTemplate> wrapper = this.createWrapper(formTemplateRequest);
        return this.list(wrapper);
    }

    private FormTemplate queryFormTemplate(FormTemplateRequest formTemplateRequest) {
        FormTemplate formTemplate = this.getById(formTemplateRequest.getId());
        if (ObjectUtil.isEmpty(formTemplate)) {
            throw new ServiceException(FormTemplateExceptionEnum.FORM_TEMPLATE_NOT_EXISTED);
        }
        return formTemplate;
    }

    private LambdaQueryWrapper<FormTemplate> createWrapper(FormTemplateRequest formTemplateRequest) {
        LambdaQueryWrapper<FormTemplate> queryWrapper = new LambdaQueryWrapper<>();

        String searchText = formTemplateRequest.getSearchText();
        if (StrUtil.isNotBlank(searchText)) {
            queryWrapper.like(FormTemplate::getTemplateName, searchText);
            queryWrapper.or().like(FormTemplate::getTemplateCode, searchText);
        }

        queryWrapper.orderByAsc(FormTemplate::getTemplateSort);

        return queryWrapper;
    }

    private void validateRepeatTemplate(String formModelCode, boolean editFlag, Long templateId) {
        LambdaQueryWrapper<FormTemplate> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FormTemplate::getTemplateCode, formModelCode);
        if (editFlag) {
            lambdaQueryWrapper.ne(FormTemplate::getId, templateId);
        }
        long count = this.count(lambdaQueryWrapper);
        if (count > 0) {
            throw new ServiceException(FormTemplateExceptionEnum.REPEAT_TEMPLATE_CODE);
        }
    }

}
