package com.huigou.topsun.resource.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huigou.cache.DictUtil;
import com.huigou.topsun.resource.domain.ResourceFieldValue;
import com.huigou.topsun.resource.domain.ResourceFiled;
import com.huigou.topsun.resource.domain.ResourceType;
import com.huigou.topsun.resource.mapper.ResourceFiledMapper;
import com.huigou.topsun.resource.mapper.ResourceTypeMapper;
import com.huigou.topsun.resource.service.ResourceFiledService;
import com.huigou.topsun.resource.vo.ResourceFiledVo;
import com.huigou.topsun.util.CommonUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
* @author 16508
* @description 针对表【resource_filed(资源字段设置)】的数据库操作Service实现
* @createDate 2023-10-25 16:08:43
*/
@Service
public class ResourceFiledServiceImpl extends ServiceImpl<ResourceFiledMapper, ResourceFiled>
    implements ResourceFiledService {

    @Resource
    private ResourceFiledMapper resourceFiledMapper;
    @Resource
    private ResourceTypeMapper resourceTypeMapper;
    @Override
    public ResourceFiledVo saveResourceFiled(ResourceFiledVo resourceFiledVo) {
        ResourceFiled resourceFiled = ResourceFiledVo.getResourceFiled(resourceFiledVo);
        this.save(resourceFiled);
        resourceFiledVo.setResourceFieldId(resourceFiled.getResourceFieldId().toString());
        return resourceFiledVo;
    }

    @Override
    public void createTable(List<ResourceFiledVo> resourceFileds, String tableName, String tableTile){
        resourceFiledMapper.createTable(tableName,tableTile,resourceFileds);
    }

    @Override
    public void updateTableAddColumn(List<ResourceFiledVo> resourceFileds, String tableName) {
        resourceFiledMapper.updateTableAddColumn(tableName,resourceFileds);
    }

    @Override
    public void updateTableChangeColumn(List<ResourceFiledVo> resourceFileds, String tableName){
        resourceFiledMapper.updateTableChangeColumn(tableName,resourceFileds);
    }

    @Override
    public StringBuffer matchFieldType(ResourceFiledVo resourceField,StringBuffer sql){
        /*//默认或者自定义字符串大小
        if ("string".equals(resourceField.getResourceFieldType())){
            sql.append(" varchar(").append(resourceField.getResourceFieldSize() == null ? 255 : resourceField.getResourceFieldSize()).append(")");
        } else if ("number".equals(resourceField.getResourceFieldType())) {//数字
            sql.append(" int(0)");
        }else if ("datetime".equals(resourceField.getResourceFieldType())){//日期
            sql.append(" datetime(0)");
        }else if ("long".equals(resourceField.getResourceFieldType())){//长整形
            sql.append(" bigint(0)");
        } else if ("text".equals(resourceField.getResourceFieldType())) {//文本
            sql.append(" text");
        } else if ("decimal".equals(resourceField.getResourceFieldType())) {//数值
            sql.append(" decimal(").append(resourceField.getIntegerLength()).append(",").append(resourceField.getDecimalPrecision()).append(")");
        } else if ("float".equals(resourceField.getResourceFieldType())) {//单精度
            sql.append(" float(").append(resourceField.getIntegerLength()).append(",").append(resourceField.getDecimalPrecision()).append(")");
        } else if ("double".equals(resourceField.getResourceFieldType())) {//双精度
            sql.append(" double(").append(resourceField.getIntegerLength()).append(",").append(resourceField.getDecimalPrecision()).append(")");
        }*/
        return sql;
    }

    @Override
    public ResourceFiledVo updateResourceFiled(ResourceFiledVo resourceFiledVo) {
        this.save(ResourceFiledVo.getResourceFiled(resourceFiledVo));
        return resourceFiledVo;
    }

    @Override
    public void deleteById(String id) {
        this.removeById(id);
    }

    @Override
    public void deleteByResourceTypeId(String resourceTypeId) {
        LambdaQueryWrapper<ResourceFiled> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ResourceFiled::getResourceTypeId,resourceTypeId);
        this.remove(queryWrapper);
    }

    @Override
    public ResourceFiledVo findById(String id) {
        ResourceFiled resourceFiled = this.getById(id);
        return ResourceFiledVo.getResourceFiledVo(resourceFiled);
    }

    @Override
    public List<ResourceFiledVo> findList() {
        List<ResourceFiled> list = this.list();
        return JSON.parseArray(JSON.toJSONString(list),ResourceFiledVo.class);
    }

    @Override
    public List<ResourceFiledVo> findByResourceTypeId(String resourceTypeId) {
        LambdaQueryWrapper<ResourceFiled> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ResourceFiled::getResourceTypeId,resourceTypeId);
        List<ResourceFiled> list = this.list(queryWrapper);
        List<ResourceFiledVo> resourceFiledVos = JSON.parseArray(JSON.toJSONString(list), ResourceFiledVo.class);
        resourceFiledVos
                .forEach(resourceFiledVo -> {
                    String resourceFieldTypeText = DictUtil.getDictionaryDetailText("resourceFieldType", resourceFiledVo.getResourceFieldType());
                    resourceFiledVo.setResourceFieldTypeTextView(resourceFieldTypeText);

                    String yesornoText = DictUtil.getDictionaryDetailText("yesorno", resourceFiledVo.getResourceFieldShow());
                    resourceFiledVo.setResourceFieldShowTextView(yesornoText);
                });
        return resourceFiledVos;
    }

    @Override
    public int saveResourceFiledValue(Map<String,Object> map) {
        String resourceTypeId = (String) map.get("resourceTypeId");
        ResourceType resourceType = resourceTypeMapper.selectById(resourceTypeId);
        //获取表名
        String tableName = resourceType.getResourceTableName();
        //获取字段
        List<ResourceFiledVo> resourceFiledList = this.findByResourceTypeId(resourceTypeId);
        //自动生成uuid值
        List<ResourceFieldValue> resourceFieldValues = this.dealFieldAndValue(resourceFiledList, map);
        Object idObj = map.get("id");
        if (idObj == null || idObj == ""){
            return resourceFiledMapper.insertData(tableName,resourceFieldValues);
        }else {
            return resourceFiledMapper.updateData(idObj.toString(),tableName,resourceFieldValues);
        }
    }

    /**
     * 组装字段和值
     * @param resourceFiledList
     * @param map
     * @return
     */
    public List<ResourceFieldValue> dealFieldAndValue(List<ResourceFiledVo> resourceFiledList, Map<String, Object> map){
        Set<String> keySet = map.keySet();
        List<ResourceFieldValue> resourceFieldValues = new ArrayList<>();
        resourceFiledList
                .stream()
                .forEach(resourceFiled -> {
                    for (String key : keySet) {
                        if (resourceFiled.getResourceFieldName().equals(key)){
                            ResourceFieldValue resourceFieldValue = new ResourceFieldValue();
                            resourceFieldValue.setField(key);
                            Object obj = map.get(key);
                            if (ObjectUtil.isEmpty(obj)){
                                resourceFieldValue.setValue("NULL");
                            }else {
                                //如果值是字符串，文本，日期格式的需要加英文状态下的引号： ''
                                if ("string".equals(resourceFiled.getResourceFieldType()) ||
                                        "date".equals(resourceFiled.getResourceFieldType())){
                                    resourceFieldValue.setValue("'" + obj + "'");
                                }else {
                                    resourceFieldValue.setValue(obj);
                                }
                            }
                            resourceFieldValues.add(resourceFieldValue);
                        }
                    }
                });
        Object idObj = map.get("id");
        if (idObj == null || idObj == ""){
            ResourceFieldValue resourceFieldValue = new ResourceFieldValue();
            resourceFieldValue.setField("id");
            String uuid = CommonUtil.createUuid();
            resourceFieldValue.setValue("'"+uuid+"'");
            resourceFieldValues.add(resourceFieldValue);
        }
        return resourceFieldValues;
    }

    @Override
    public List<Map<String, Object>> getResourceFieldValueList(String resourceTypeId){
        List<Map<String, Object>> maps = new ArrayList<>();
        if (resourceTypeId == null){
            return maps;
        }else {
            ResourceType resourceType = resourceTypeMapper.selectById(resourceTypeId);
            //获取表名
            String tableName = resourceType.getResourceTableName();
            maps = resourceFiledMapper.selectDataList(tableName);
            return maps;
        }
    }

    @Override
    public List<Map<String, Object>> getResourceFieldValueListByProcess(String processType) {
        String tableName = DictUtil.getDictionaryDetailValue("processResourceMapping", processType);
        List<Map<String, Object>> maps = resourceFiledMapper.selectDataList(tableName);
        return maps;
    }

    @Override
    public int deleteResourceFieldValue(String resourceTypeId, String id){
        ResourceType resourceType = resourceTypeMapper.selectById(resourceTypeId);
        //获取表名
        String tableName = resourceType.getResourceTableName();
        return resourceFiledMapper.deleteDataById(tableName,id);
    }

    @Override
    public List<ResourceFiledVo> findFieldValueByResourceTypeIdAndId(String resourceTypeId, String id) {
        ResourceType resourceType = resourceTypeMapper.selectById(resourceTypeId);
        //获取表名
        String tableName = resourceType.getResourceTableName();
        Map<String, Object> map = resourceFiledMapper.findFieldValueByResourceTypeIdAndId(tableName, id);
        List<ResourceFiledVo> filedVoList = this.findByResourceTypeId(resourceTypeId);
        if (map == null){
            return filedVoList;
        }
        for (ResourceFiledVo resourceFiledVo : filedVoList) {
            Object value = map.get(resourceFiledVo.getResourceFieldName());
            resourceFiledVo.setResourceFieldValue(value);
        }
        return filedVoList;
    }

    @Override
    public void dropTableByResourceName(String tableName) {
        resourceFiledMapper.dropTableByResourceTableName(tableName);
    }
}




