package cn.ey.biz.module.system.service.field;

import cn.ey.biz.common.pojo.PageResult;
import cn.ey.biz.framework.security.core.util.SecurityFrameworkUtils;
import cn.ey.biz.module.system.controller.admin.field.vo.*;
import cn.ey.biz.module.system.convert.field.FieldItemConvert;
import cn.ey.biz.module.system.dal.dataobject.field.FieldConfigDO;
import cn.ey.biz.module.system.dal.dataobject.field.FieldItemDO;
import cn.ey.biz.module.system.dal.dataobject.user.AdminUserDO;
import cn.ey.biz.module.system.dal.mapper.field.FieldConfigMapper;
import cn.ey.biz.module.system.dal.mapper.field.FieldItemBatchInsertMapper;
import cn.ey.biz.module.system.dal.mapper.field.FieldItemMapper;
import cn.ey.biz.module.system.enums.field.StatusEnum;
import cn.ey.biz.module.system.service.user.AdminUserService;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static cn.ey.biz.common.exception.util.ServiceExceptionUtil.exception;
import static cn.ey.biz.module.system.enums.ErrorCodeConstants.FIELD_CONFIGCODE_NOT_NULL;
import static cn.ey.biz.module.system.enums.ErrorCodeConstants.FIELD_ITEM_NOT_EXISTS;

/**
 * 字段条目 Service 实现类
 */
@Service
@Validated
public class FieldItemServiceImpl implements FieldItemService {

    @Resource
    private FieldItemMapper fieldItemMapper;

    @Resource
    private FieldConfigMapper fieldConfigMapper;

    @Resource
    private AdminUserService adminUserService;

    @Resource
    private FieldItemBatchInsertMapper fieldItemBatchInsertMapper;

    @Override
    @Transactional
    public Long createFieldItem(FieldItemCreateReqVO createReqVO) {
        FieldItemDO fieldItem = FieldItemConvert.INSTANCE.convert(createReqVO);

        LambdaUpdateWrapper<FieldConfigDO> updateWrapper = Wrappers.<FieldConfigDO>update()
                .lambda()
                .eq(FieldConfigDO::getEnable, StatusEnum.ENABLE.getStatus());
        FieldConfigDO fieldConfigDO = new FieldConfigDO().setEnable(StatusEnum.DISABLE.getStatus());
        // 全部 禁用
        fieldConfigMapper.update(fieldConfigDO, updateWrapper);

        // 添加版本
        Long ConfigId = createFieldConfig(createReqVO);

        // 添加条目
        createFieldItem(createReqVO, ConfigId);

        // 返回
        return fieldItem.getId();
    }

    @Override
    public void updateFieldItem(FieldItemUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateFieldItemExists(updateReqVO.getId());
        // 更新
        FieldItemDO updateObj = FieldItemConvert.INSTANCE.convert(updateReqVO);
        fieldItemMapper.updateById(updateObj);
    }

    @Override
    public void deleteFieldItem(Long id) {
        // 校验存在
        this.validateFieldItemExists(id);
        // 删除
        fieldItemMapper.deleteById(id);
    }

    private void validateFieldItemExists(Long id) {
        if (fieldItemMapper.selectById(id) == null) {
            throw exception(FIELD_ITEM_NOT_EXISTS);
        }
    }

    @Override
    public FieldItemDO getFieldItem(Long id) {
        return fieldItemMapper.selectById(id);
    }

    @Override
    public List<FieldItemDO> getFieldItemList(Collection<Long> ids) {
        return fieldItemMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<FieldItemDO> getFieldItemPage(FieldItemPageReqVO pageReqVO) {
        return fieldItemMapper.selectPage(pageReqVO);
    }

    @Override
    public List<FieldItemDO> getFieldItemList(FieldItemExportReqVO exportReqVO) {
        return fieldItemMapper.selectList(exportReqVO);
    }

    @Override
    @Transactional
    public void updateFieldItemBelongto(FieldItemUpdateReqVO updateReqVO) {
        List<FieldItemDO> list = new ArrayList<>();
        LambdaUpdateWrapper<FieldItemDO> updateWrapper = Wrappers.<FieldItemDO>update()
                .lambda()
                .eq(FieldItemDO::getConfigId, updateReqVO.getId());
        fieldItemMapper.delete(updateWrapper);
        // 获取当前用户name
        AdminUserDO user = adminUserService.getUser(SecurityFrameworkUtils.getLoginUser().getId());
        LambdaUpdateWrapper<FieldConfigDO> update = Wrappers.<FieldConfigDO>update()
                .lambda()
                .eq(FieldConfigDO::getId, updateReqVO.getId());
        FieldConfigDO fieldConfigDO = new FieldConfigDO()
                .setUpdaterName(user.getNickname());
        fieldConfigMapper.update(fieldConfigDO, update);

        for (FieldItemRespVO fieldItemRespVO : updateReqVO.getFieldItems()) {
            for (int i = 0; i < fieldItemRespVO.getBelongTos().size(); i++) {
                Integer val = fieldItemRespVO.getBelongTos().get(i);
                if (val.intValue() == 1) {
                    FieldItemDO fieldItemDO = new FieldItemDO()
                            .setConfigId(updateReqVO.getId())
                            .setFieldCode(fieldItemRespVO.getFieldCode())
                            .setBelongTo(String.valueOf(i));
                    list.add(fieldItemDO);
                }
            }
        }
        fieldItemBatchInsertMapper.saveBatch(list);
    }

    // 版本自增
    private String versionsIncrement() {
        String versions = "SJFJEE";
        return versions + fieldConfigMapper.selectCount();
    }

    private Long createFieldConfig(FieldItemCreateReqVO createReqVO) {
        String config = "";
        for (FieldItemRespVO fieldItem : createReqVO.getFieldItems()) {
            config = fieldItem.getConfigCode();
            break;
        }
        if (StringUtils.isEmpty(config)) {
            throw exception(FIELD_CONFIGCODE_NOT_NULL);
        }
        AdminUserDO user = adminUserService.getUser(SecurityFrameworkUtils.getLoginUser().getId());
        FieldConfigDO fieldConfigDO = new FieldConfigDO()
                .setConfigCode(config)
                .setVersion(versionsIncrement())
                .setEnable(StatusEnum.ENABLE.getStatus())
                .setCreatorName(user.getNickname());
        fieldConfigMapper.insert(fieldConfigDO);
        return fieldConfigDO.getId();
    }

    private void createFieldItem(FieldItemCreateReqVO createReqVO, Long ConfigId) {
        List<FieldItemDO> list = new ArrayList<>();
        if (CollectionUtil.isEmpty(createReqVO.getFieldItems())) {
            throw exception(FIELD_ITEM_NOT_EXISTS);
        }
        for (FieldItemRespVO fieldItemRespVO : createReqVO.getFieldItems()) {
            for (int i = 0; i < fieldItemRespVO.getBelongTos().size(); i++) {
                Integer val = fieldItemRespVO.getBelongTos().get(i);
                if (val.intValue() == 1) {
                    FieldItemDO fieldItemDO = new FieldItemDO()
                            .setConfigId(ConfigId)
                            .setFieldCode(fieldItemRespVO.getFieldCode())
                            .setBelongTo(String.valueOf(i));
                    list.add(fieldItemDO);
                }
            }
        }
        fieldItemBatchInsertMapper.saveBatch(list);
    }

}
