package com.lightinit.hsdataplatform.impl.admin;

import com.lightinit.hsdataplatform.entity.Sector;
import com.lightinit.hsdataplatform.entity.SectorExample;
import com.lightinit.hsdataplatform.mapper.SectorMapper;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.SectorDataModel;
import com.lightinit.hsdataplatform.model.admin.TreeModel;
import com.lightinit.hsdataplatform.service.admin.ISectorMgrService;
import com.lightinit.hsdataplatform.service.admin.TreeDataBuilder;
import com.lightinit.hsdataplatform.spring.DynamicDataContextHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Function;

import static java.util.stream.Collectors.toList;

/**
 * @author WangYao
 * @date 2018/7/7 13:25
 * @description 部门管理业务实现
 */
@Service
public class SectorMgrServiceImpl implements ISectorMgrService {

    @Autowired
    private SectorMapper sectorMapper;

    public SectorDataModel queryOne(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        SectorDataModel outputModel = new SectorDataModel();
        Sector entity1 = sectorMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(entity1, outputModel);
        return outputModel;
    }

    public List<TreeModel> queryTreeData() {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        final List<Sector> dataList = getAllSector();
        Function<Sector,TreeModel> mapFunction = (q) -> {
            TreeModel treeModel =  new TreeModel(q.getId().toString(), q.getSectorCode(), q.getParentId() == null ? null : q.getParentId().toString(), q.getSectorName(), null);
            return treeModel;
        };
        List<TreeModel> treeModelList = dataList.stream().filter(q -> q.getParentId() == null).map(mapFunction).collect(toList());
        TreeDataBuilder.buildTreeModelRecursively(treeModelList, dataList, (pCurrentTreeModel, pDataList) -> pDataList.stream()
                .filter(q -> q.getParentId() != null && q.getParentId().toString().equals(pCurrentTreeModel.getId()))
                .map(mapFunction)
                .collect(toList()), (pCurrentTreeModel, pChildTreeModelList) -> {
            List<String> tags = new ArrayList<>();
            tags.add(String.valueOf(pChildTreeModelList.size()));
            pCurrentTreeModel.setTags(tags);
        });
        return treeModelList;
    }

    public List<Sector> getAllSector(){
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        SectorExample example1 = new SectorExample();
        SectorExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andDeletedAtIsNull();
        return sectorMapper.selectByExample(example1);
    }

    public ResultState<Long> add(SectorDataModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        if (isCodeExisting(inputModel.getSectorCode(), null)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("编码已存在");
            return resultState;
        }

        Date createdAt = new Date();
        Sector entity1 = new Sector();
        BeanUtils.copyProperties(inputModel, entity1);
        entity1.setCreatedAt(createdAt);
        int sqlResult1 = sectorMapper.insert(entity1);

        if (!(sqlResult1 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据插入失败");
        }
        resultState.setData(entity1.getId());
        return resultState;
    }

    public ResultState<Long> edit(SectorDataModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        Sector resource = sectorMapper.selectByPrimaryKey(inputModel.getId());
        if (resource == null){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据不存在");
            return resultState;
        }
        if (isCodeExisting(inputModel.getSectorCode(), inputModel.getId())){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("编码已存在");
            return resultState;
        }

        Sector entity1 = new Sector();
        BeanUtils.copyProperties(inputModel, entity1);
        SectorExample example1 = new SectorExample();
        SectorExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIdEqualTo(inputModel.getId());
        int sqlResult1 = sectorMapper.updateByExampleSelective(entity1, example1);

        if (!(sqlResult1 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据更新失败");
        }
        resultState.setData(inputModel.getId());
        return resultState;
    }

    public ResultState<Long> delete(long id, Long deletedBy) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();

        Sector resource = sectorMapper.selectByPrimaryKey(id);
        if (resource == null){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据不存在");
            return resultState;
        }

        Sector entity1 = new Sector();
        entity1.setId(id);
        entity1.setDeletedAt(new Date());
        entity1.setDeletedBy(deletedBy);
        int sqlResult1 = sectorMapper.updateByPrimaryKeySelective(entity1);

        if (!(sqlResult1 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据更新失败");
        }
        resultState.setData(id);
        return resultState;
    }

    /**
     * @param code 编码
     * @param id ID（排除的ID）
     * @return 编码是否存在
     */
    private boolean isCodeExisting(String code, Long id){
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        SectorExample example1 = new SectorExample();
        SectorExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andDeletedAtIsNull();
        criteria1.andSectorCodeEqualTo(code);
        if (id != null && id > 0){
            criteria1.andIdNotEqualTo(id);
        }
        List<Sector> list = sectorMapper.selectByExample(example1);
        return list != null && list.size() > 0;
    }
}
