package com.ruoyi.business.state.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.business.state.domain.StateModel;
import com.ruoyi.business.state.domain.StateModelForm;
import com.ruoyi.business.state.domain.StateModelFormItem;
import com.ruoyi.business.state.mapper.StateModelFormItemMapper;
import com.ruoyi.business.state.mapper.StateModelFormMapper;
import com.ruoyi.business.state.mapper.StateModelMapper;
import com.ruoyi.business.state.service.IStateModelService;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 调查问卷模板Service业务层处理
 *
 * @author Duke_yzl
 * @date 2023-06-26
 */
@Service
public class StateModelServiceImpl extends MPJBaseServiceImpl<StateModelMapper, StateModel> implements IStateModelService {
    @Resource
    private StateModelFormMapper modelFormMapper;
    @Resource
    private StateModelFormItemMapper modelFormItemMapper;

    /**
     * 查询调查问卷模板
     *
     * @param modelId 调查问卷模板主键
     * @return 调查问卷模板
     */
    @Override
    public StateModel selectStateModelByModelId(Long modelId) {
        MPJLambdaWrapper<StateModel> getOne = new MPJLambdaWrapper<StateModel>("sm")
                .selectAll(StateModel.class)
                .selectCollection(StateModelForm.class, StateModel::getModelForms,b->b
                        .collection(StateModelFormItem.class,StateModelForm::getItems))
                .leftJoin(StateModelForm.class, "smf" , StateModelForm::getModelId, StateModel::getModelId)
                .leftJoin(StateModelFormItem.class, "smfi" , StateModelFormItem::getStateId, StateModelForm::getStateId)
                .eq(StateModel::getModelId, modelId)
                .orderByAsc(StateModel::getCreateTime)
                .orderByAsc(StateModelForm::getOrderNum)
                .orderByAsc(StateModelFormItem::getOrderNum);

        StateModel stateModel = selectJoinOne(StateModel.class, getOne);
        return stateModel;
    }

    /**
     * 查询调查问卷模板列表
     *
     * @param stateModel 调查问卷模板
     * @return 调查问卷模板
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<StateModel> selectStateModelList(StateModel stateModel) {

        MPJLambdaWrapper<StateModel> selectStateModelList = new MPJLambdaWrapper<StateModel>("sm")
                .selectAll(StateModel.class)
                .selectAs(SysDept::getDeptName,StateModel::getDeptName)
                //会产生笛卡尔，列表不携带子表数据
//                .selectCollection(StateModelForm.class,StateModel::getModelForms,b->b
//                        .collection(StateModelFormItem.class,StateModelForm::getItems))
//                .leftJoin(StateModelForm.class, "smf" , StateModelForm::getModelId, StateModel::getModelId)
//                .leftJoin(StateModelFormItem.class, "smfi" , StateModelFormItem::getStateId, StateModelForm::getStateId)
                .leftJoin(SysDept.class,"d",SysDept::getDeptId,StateModel::getDeptId)
                .like(StringUtils.isNotBlank(stateModel.getModelName()), StateModel::getModelName, stateModel.getModelName())
                .eq(StringUtils.isNotBlank(stateModel.getModelType()), StateModel::getModelType, stateModel.getModelType())
                .eq(StringUtils.isNotLongNull(stateModel.getDeptId()), StateModel::getDeptId, stateModel.getDeptId())
                //搜索问题
                .like(StringUtils.isNotBlank((CharSequence) stateModel.getParams().get("stateFormName")), StateModelForm::getStateName,stateModel.getParams().get("stateFormName"))
                //批量删除时使用
//                .in(StringUtils.isNotNull(stateModel.getParams().get("stateModelIds")), StateModelForm::getStateId,Arrays.asList(String.valueOf(stateModel.getParams().get("stateModelIds")).split(",")))
                .between(StringUtils.isNotBlank((CharSequence) stateModel.getParams().get("beginCreateTime")) && StringUtils.isNotBlank((CharSequence) stateModel.getParams().get("endCreateTime")),
                        StateModel::getCreateTime, stateModel.getParams().get("beginCreateTime"), stateModel.getParams().get("endnCreateTime"))
                .apply(StringUtils.isNotBlank((String)stateModel.getParams().get("dataScope")), (String) stateModel.getParams().get("dataScope"));
        return selectJoinList(StateModel.class, selectStateModelList);
    }

    /**
     * 新增调查问卷模板
     *
     * @param stateModel 调查问卷模板
     * @return 结果
     */
    @Override
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public boolean insertStateModel(StateModel stateModel) {
        boolean save = save(stateModel);
        saveModelForm(stateModel.getModelForms(),stateModel.getModelId());
        return save;
    }

    /**
     * 修改调查问卷模板
     *
     * @param stateModel 调查问卷模板
     * @return 结果
     */
    @Override
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public boolean updateStateModel(StateModel stateModel) {
        deleteModelForm(stateModel.getModelId());
        boolean b = updateById(stateModel);
        saveModelForm(stateModel.getModelForms(),stateModel.getModelId());
        return b;
    }

    /**
     * 写入题目
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public void saveModelForm(List<StateModelForm> modelForms,Long modelId){
        for (StateModelForm modelForm:modelForms) {
            modelForm.setModelId(modelId);
            modelFormMapper.insert(modelForm);
            List<StateModelFormItem> items = modelForm.getItems();
            if(null != items && items.size() > 0){
                for (StateModelFormItem modelFormItem:items){
                    modelFormItem.setStateId(modelForm.getStateId());
                    modelFormItemMapper.insert(modelFormItem);
                }
            }
        }
    }

    /**
     * 批量删除调查问卷模板
     *
     * @param modelIds 需要删除的调查问卷模板主键
     * @return 结果
     */
    @Override
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public boolean deleteStateModelByModelIds(Long[] modelIds) {

        List<StateModelForm> stateModelForms = modelFormMapper.selectList(new LambdaQueryWrapper<StateModelForm>().in(StateModelForm::getModelId, Arrays.asList(modelIds)));
        List<Long> collect = stateModelForms.stream().map(StateModelForm::getStateId).collect(Collectors.toList());

        modelFormMapper.delete(new LambdaQueryWrapper<StateModelForm>().in(StateModelForm::getModelId,Arrays.asList(modelIds)));
        modelFormItemMapper.delete(new LambdaQueryWrapper<StateModelFormItem>().in(StateModelFormItem::getStateId,collect));

        return removeBatchByIds(Arrays.asList(modelIds));
    }

    /**
     * 删除调查问卷模板信息
     *
     * @param modelId 调查问卷模板主键
     * @return 结果
     */
    @Override
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public boolean deleteStateModelByModelId(Long modelId) {

        deleteModelForm(modelId);

        return removeById(modelId);
    }

    /**
     * 删除题目元素
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public void deleteModelForm(Long modelId) {
        StateModel stateModel = selectStateModelByModelId(modelId);
        List<StateModelForm> modelForms = stateModel.getModelForms();

        List<Long> collectModelForm = modelForms.stream().map(StateModelForm::getStateId).collect(Collectors.toList());
        modelFormMapper.delete(new LambdaQueryWrapper<StateModelForm>().eq(StateModelForm::getModelId, stateModel.getModelId()));
        modelFormItemMapper.delete(new LambdaQueryWrapper<StateModelFormItem>().in(StateModelFormItem::getStateId,collectModelForm));
    }
}
