package com.ssyf.module.custom.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssyf.common.core.domain.query.PageQuery;
import com.ssyf.common.core.util.AssertUtil;
import com.ssyf.common.security.domain.ClientInfo;
import com.ssyf.common.security.helper.ClientContextHelper;
import com.ssyf.common.web.apicode.ApiCodeUser;
import com.ssyf.common.web.error.ServiceRuntimeException;
import com.ssyf.module.custom.domain.entity.CustomData;
import com.ssyf.module.custom.domain.entity.CustomField;
import com.ssyf.module.custom.domain.query.CustomDataQuery;
import com.ssyf.module.custom.domain.query.CustomFieldQuery;
import com.ssyf.module.custom.service.CustomDataService;
import com.ssyf.module.custom.mapper.CustomDataMapper;
import com.ssyf.module.custom.service.CustomFieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
* @author admin
* @description 针对表【custom_data】的数据库操作Service实现
* @createDate 2024-08-13 09:29:55
*/
@Service
public class CustomDataServiceImpl extends ServiceImpl<CustomDataMapper, CustomData> implements CustomDataService {

    @Lazy
    @Autowired
    private CustomFieldService customFieldService;

    @Override
    public void cleanDataOfFieldName(String fieldName) {
        this.baseMapper.updateColumnByNameAndValue(fieldName ,"");
    }

    @Override
    public Map<String, Object> addOne(String tableUid, Map<String, Object> map) {
        List<CustomField> customFields = this.customFieldService.getAll(tableUid ,null);
        if(CollectionUtil.isEmpty(customFields)){
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode() ,"字段未配置");
        }
        CustomDataQuery customDataQuery = toCustomDataQuery(map ,customFields);

        CustomData customData = addOne(tableUid ,customDataQuery);
        return customDataToMap(customData ,customFields);
    }

    @Override
    public CustomData addOne(String tableUid, CustomDataQuery query) {
        CustomData customData = BeanUtil.toBean(query ,CustomData.class);
        customData.setUid(IdUtil.simpleUUID()).setTableUid(tableUid);
        if(ClientContextHelper.isLogin()){
            ClientInfo clientInfo = ClientContextHelper.getClientInfo();
            customData.setCreatorId(clientInfo.getId().toString());
            customData.setCreatorName(clientInfo.getNickname());
        }
        customData.setCreatedTime(LocalDateTime.now());

        save(customData);
        return customData;
    }

    @Override
    public void updateByUid(String uid, Map<String, Object> query) {
        CustomData customData = this.getByUid(uid);
        AssertUtil.isNotNull(customData , ServiceRuntimeException.instance(ApiCodeUser.PARAMETER_ERROR.getCode() ,"没有数据"));
        List<CustomField> customFields = this.customFieldService.getAll(customData.getTableUid() ,null);
        if(CollectionUtil.isEmpty(customFields)){
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode() ,"字段未配置");
        }
        CustomDataQuery customDataQuery = toCustomDataQuery(query ,customFields);

        updateByUid(uid ,customDataQuery);
    }

    @Override
    public void updateByUid(String uid, CustomDataQuery query) {
        CustomData customData = this.getByUid(uid);
        AssertUtil.isNotNull(customData , ServiceRuntimeException.instance(ApiCodeUser.PARAMETER_ERROR.getCode() ,"没有数据"));
        CustomData update = BeanUtil.toBean(query ,CustomData.class);
        //编码不能更新
        update.setUid(uid).setTableUid(null);

        update.setId(customData.getId());
        this.updateById(update);
    }

    @Override
    public void removeByUid(String uid) {
        remove(new LambdaQueryWrapper<CustomData>().eq(CustomData::getUid ,uid));
    }

    @Override
    public CustomData getByUid(String uid) {
        return getOne(new LambdaQueryWrapper<CustomData>().eq(CustomData::getUid ,uid));
    }

    @Override
    public PageInfo<CustomData> getPage(String tableUid, CustomDataQuery query) {
        List<CustomField> customFields = this.customFieldService.getAll(tableUid ,new CustomFieldQuery());
        QueryWrapper<CustomData> queryWrapper = this.createWrapper(tableUid ,customFields ,query);
        PageHelper.startPage(query.getPageNum() ,query.getPageSize());
        return PageInfo.of(list(queryWrapper));
    }

    @Override
    public List<CustomData> getAll(String tableUid, CustomDataQuery query) {
        List<CustomField> customFields = this.customFieldService.getAll(tableUid ,new CustomFieldQuery());
        QueryWrapper<CustomData> queryWrapper = this.createWrapper(tableUid ,customFields ,query);
        return list(queryWrapper);
    }

    @Override
    public PageInfo<Map<String, Object>> getPage(String tableUid, Map<String, Object> query, PageQuery pageQuery) {
        List<CustomField> customFields = this.customFieldService.getAll(tableUid ,new CustomFieldQuery());
        CustomDataQuery customDataQuery = toCustomDataQuery(query ,customFields);
        QueryWrapper<CustomData> queryWrapper = this.createWrapper(tableUid ,customFields ,customDataQuery);
        PageHelper.startPage(pageQuery.getPageNum() ,pageQuery.getPageSize());
        PageInfo<CustomData> pageInfo = PageInfo.of(list(queryWrapper));
        if(CollectionUtil.isEmpty(pageInfo.getList())){
            return PageInfo.emptyPageInfo();
        }
        List<Map<String ,Object>> list = pageInfo.getList().stream().collect(ArrayList::new ,(l ,r)->l.add(customDataToMap(r ,customFields)) ,( l,r)->{});
        PageInfo<Map<String ,Object>> result = PageInfo.of(list);
        result.setTotal(pageInfo.getTotal());
        result.setPageSize(pageInfo.getPageSize());
        result.setPageNum(pageInfo.getPageNum());
        return  result;
    }

    @Override
    public List<Map<String, Object>> getAll(String tableUid, Map<String, Object> query) {
        List<CustomField> customFields = this.customFieldService.getAll(tableUid ,new CustomFieldQuery());
        CustomDataQuery customDataQuery = toCustomDataQuery(query ,customFields);
        QueryWrapper<CustomData> queryWrapper = this.createWrapper(tableUid ,customFields ,customDataQuery);
        List<CustomData> list = list(queryWrapper);
        return list.stream().collect(ArrayList::new ,(l ,r)->l.add(customDataToMap(r ,customFields)) ,( l,r)->{});
    }

    private CustomDataQuery toCustomDataQuery(Map<String ,Object> map ,List<CustomField> customFields){
        CustomDataQuery customDataQuery = new CustomDataQuery();
        //设置值
        for (CustomField customField : customFields) {
            BeanUtil.setFieldValue(customDataQuery,customField.getMapCustomDataField() ,map.get(customField.getEnName()));
        }
        return customDataQuery;
    }

    private Map<String ,Object> customDataToMap(CustomData customData ,List<CustomField> customFields){
        Map<String ,Object> map = new HashMap<>();
        for(CustomField customField : customFields){
            map.put(customField.getEnName() ,BeanUtil.getFieldValue(customData ,customField.getMapCustomDataField()));
        }
        map.put("uid" ,customData.getUid());
        map.put("tableUid" ,customData.getTableUid());
        map.put("createTime" ,customData.getCreatedTime());
        return map;
    }

    private QueryWrapper<CustomData> createWrapper(String tableUid , List<CustomField> customFields , CustomDataQuery query) {
        QueryWrapper<CustomData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("table_uid" ,tableUid);
        queryWrapper.like(StrUtil.isNotBlank(query.getUid()),"uid" ,query.getUid());

        //查询条件封装，like查询，效率关注
        for(CustomField customField : customFields){
            //设置排序
            queryWrapper.orderByDesc(customField.getMapCustomDataField());

            Object value = BeanUtil.getFieldValue(query ,customField.getMapCustomDataField());
            if(value == null){
                continue;
            }
            queryWrapper.like(customField.getMapCustomDataField() ,value);
        }

//        //设置排序
//        Collections.sort(customFields ,(l,r)->{
//            int lo = l.getOrderSortPriority() == null ? 0 : l.getOrderSortPriority();
//            int ro = r.getOrderSortPriority() == null ? 0 : r.getOrderSortPriority();
//            return lo - ro;
//        });
//        for(CustomField customField : customFields){
//            queryWrapper.orderByDesc(customField.getMapCustomDataField());
//        }

        return queryWrapper;
    }
}




