package com.yeejoin.amos.boot.module.common.biz.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.yeejoin.amos.boot.biz.common.utils.MenuFrom;
import com.yeejoin.amos.boot.biz.common.utils.TreeParser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.module.common.api.dto.DynamicFormColumnDto;
import com.yeejoin.amos.boot.module.common.api.dto.DynamicFormInitDto;
import com.yeejoin.amos.boot.module.common.api.dto.DynamicFormInstanceDto;
import com.yeejoin.amos.boot.module.common.api.dto.SelectItem;
import com.yeejoin.amos.boot.module.common.api.dto.SelectItems;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormColumn;
import com.yeejoin.amos.boot.module.common.api.mapper.DynamicFormColumnMapper;
import com.yeejoin.amos.boot.module.common.api.service.IDynamicFormColumnService;

/**
 * 动态表单树形分组字段表服务实现类
 *
 * @author system_generator
 * @date 2021-07-06
 */
@Service
public class DynamicFormColumnServiceImpl extends BaseService<DynamicFormColumnDto, DynamicFormColumn, DynamicFormColumnMapper> implements IDynamicFormColumnService {

    @Autowired
    DataDictionaryServiceImpl iDataDictionaryService;


    /**
     * 分页查询
     */
    public Page<DynamicFormColumnDto> queryForDynamicFormColumnPage(Page<DynamicFormColumnDto> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<DynamicFormColumnDto> queryForDynamicFormColumnList() {
        return this.queryForList("", false);
    }

    public List<String> queryListByFormId(String groupCode) {
        return this.queryListByTypeCode(groupCode).stream().map(c -> c.getFieldCode()).collect(Collectors.toList());
    }

    public List<DynamicFormColumnDto> queryListByTypeCode(String groupCode) {
        return this.queryForList(null, false, groupCode);
    }

    public List<DynamicFormInitDto> getFormlist(String code) {

        QueryWrapper<DynamicFormColumn> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_code", code);
        queryWrapper.eq("is_delete", false);
        queryWrapper.orderByAsc("sort");
        List<DynamicFormColumn> dynamicFormColumn = this.list(queryWrapper);
        List<DynamicFormInitDto> listForm = new ArrayList<DynamicFormInitDto>();
        String appKey = RequestContext.getAppKey();
        // 组装数据
        dynamicFormColumn.stream().forEach(dynamicForm -> {
            if (dynamicForm.getFieldType().equals("input") ||
                    dynamicForm.getFieldType().equals("string") ||
                    dynamicForm.getFieldType().equals("datetime") ||
                    dynamicForm.getFieldType().equals("textarea") ||
                    dynamicForm.getFieldType().equals("upload") ||
                    dynamicForm.getFieldType().equals("tagging") ||
                    dynamicForm.getFieldType().equals("inputBitmap")) {

                DynamicFormInitDto vo = new DynamicFormInitDto(dynamicForm.getFieldCode(), dynamicForm.getFieldName(),
                        dynamicForm.getFieldType(), new SelectItems(), null);
                DynamicFormInstanceDto dynamicFormValue = new DynamicFormInstanceDto();
                BeanUtils.copyProperties(dynamicForm, dynamicFormValue);
                dynamicFormValue.setSequenceNbr(null);
                dynamicFormValue.setFormColumnId(dynamicForm.getSequenceNbr());
                dynamicFormValue.setAppKey(appKey);

                if (dynamicForm.getFieldType().equals("datetime")) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date();
                    String dateString = formatter.format(date);
                    dynamicFormValue.setFieldValue(dateString);
                    vo.setDefaultValue(date);
                }
                vo.setFormItemDescr(dynamicFormValue);
                vo.setSort(dynamicFormValue.getSort());
                listForm.add(vo);
            } else if (dynamicForm.getFieldType().equals("treeSelect")) {
                try {

                DynamicFormInstanceDto dynamicFormValue = null;
                JSONObject columnConfigJson = dynamicForm.getColumnConfig();
                QueryWrapper<DataDictionary> queryWrappercolumnMap = new QueryWrapper<>();
                queryWrappercolumnMap.eq("type", columnConfigJson.get("dict"));
                queryWrappercolumnMap.orderByAsc("sort_num");
                Collection<DataDictionary> list = iDataDictionaryService.list(queryWrappercolumnMap);

//                    List<Menu> menus = TreeParser.getTree(null, list, DataDictionary.class.getName(), "getCode", 0, "getName"
//                            , "getParent", null);


                    List<MenuFrom> menus = TreeParser.getTreexin(null, list, DataDictionary.class.getName(), "getCode", 0,
                            "getName", "getParent", null);


                    List<SelectItem> result = getdata(list);
                    DynamicFormInitDto vo = new DynamicFormInitDto();
                    vo.setKey(dynamicForm.getFieldCode());
                    vo.setData(menus);
                    vo.setLabel( dynamicForm.getFieldName());
                    vo.setType(dynamicForm.getFieldType());
                    vo.setColumnConfig(dynamicForm.getColumnConfig().toJSONString());
                dynamicFormValue = new DynamicFormInstanceDto();
                BeanUtils.copyProperties(dynamicForm, dynamicFormValue);
                dynamicFormValue.setSequenceNbr(null);
                dynamicFormValue.setFormColumnId(dynamicForm.getSequenceNbr());
                dynamicFormValue.setAppKey(appKey);
                vo.setFormItemDescr(dynamicFormValue);
                vo.setSort(dynamicFormValue.getSort());
                listForm.add(vo);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                // 查询数据项
                DynamicFormInitDto vo = null;
                DynamicFormInstanceDto dynamicFormValue = null;

                JSONObject columnConfigJson = dynamicForm.getColumnConfig();
                String type = ObjectUtils.isEmpty(columnConfigJson) ? "" : columnConfigJson.get("type").toString();
                switch (type) {
                    case "custom":
                        List<SelectItem> selectItems = JSONArray.parseArray(columnConfigJson.get("data").toString(), SelectItem.class);
                        vo = new DynamicFormInitDto(dynamicForm.getFieldCode(), dynamicForm.getFieldName(),
                                dynamicForm.getFieldType(), new SelectItems(selectItems), dynamicForm.getColumnConfig().toJSONString());
                        dynamicFormValue = new DynamicFormInstanceDto();
                        BeanUtils.copyProperties(dynamicForm, dynamicFormValue);
                        dynamicFormValue.setSequenceNbr(null);
                        dynamicFormValue.setFormColumnId(dynamicForm.getSequenceNbr());
                        dynamicFormValue.setAppKey(appKey);
                        if (dynamicForm.getFieldType().equals("radio")) {
                            vo.setDefaultValue(selectItems.get(0).getValue());
                            dynamicFormValue.setFieldValue(selectItems.get(0).getLabel());
                            dynamicFormValue.setFieldValueLabel(selectItems.get(0).getValue());
                        }

                        vo.setFormItemDescr(dynamicFormValue);
                        vo.setSort(dynamicFormValue.getSort());
                        listForm.add(vo);
                        break;
                    case "action":
                        vo = new DynamicFormInitDto(dynamicForm.getFieldCode(), dynamicForm.getFieldName(),
                                dynamicForm.getFieldType(), new SelectItems(new ArrayList<>()), dynamicForm.getColumnConfig().toJSONString());
                        dynamicFormValue = new DynamicFormInstanceDto();
                        BeanUtils.copyProperties(dynamicForm, dynamicFormValue);
                        dynamicFormValue.setSequenceNbr(null);
                        dynamicFormValue.setFormColumnId(dynamicForm.getSequenceNbr());
                        dynamicFormValue.setAppKey(appKey);
                        vo.setFormItemDescr(dynamicFormValue);
                        vo.setSort(dynamicFormValue.getSort());
                        listForm.add(vo);
                        break;
                    case "dict":
                        QueryWrapper<DataDictionary> queryWrappercolumnMap = new QueryWrapper<>();
                        queryWrappercolumnMap.eq("type", columnConfigJson.get("dict"));
                        queryWrappercolumnMap.orderByAsc("sort_num");
                        Collection<DataDictionary> listDataDictionary = iDataDictionaryService.list(queryWrappercolumnMap);
                        List<SelectItem> list = getdata(listDataDictionary);
                        vo = new DynamicFormInitDto(dynamicForm.getFieldCode(), dynamicForm.getFieldName(),
                                dynamicForm.getFieldType(), new SelectItems(list), dynamicForm.getColumnConfig().toJSONString());
                        dynamicFormValue = new DynamicFormInstanceDto();
                        BeanUtils.copyProperties(dynamicForm, dynamicFormValue);
                        dynamicFormValue.setSequenceNbr(null);
                        dynamicFormValue.setFormColumnId(dynamicForm.getSequenceNbr());
                        dynamicFormValue.setAppKey(appKey);

                        if (dynamicForm.getFieldType().equals("radio")) {
                            vo.setDefaultValue(list.get(0).getValue());
                            dynamicFormValue.setFieldValue(list.get(0).getValue());
                            dynamicFormValue.setFieldValueLabel(list.get(0).getLabel());
                        }

                        vo.setFormItemDescr(dynamicFormValue);
                        vo.setSort(dynamicFormValue.getSort());
                        listForm.add(vo);
                        break;
                    case "url":
                        vo = new DynamicFormInitDto(dynamicForm.getFieldCode(), dynamicForm.getFieldName(),
                                dynamicForm.getFieldType(), new SelectItems(new ArrayList<>()), columnConfigJson.toJSONString());
                        vo.setUrl(columnConfigJson.getString("url"));
                        dynamicFormValue = new DynamicFormInstanceDto();
                        BeanUtils.copyProperties(dynamicForm, dynamicFormValue);
                        dynamicFormValue.setSequenceNbr(null);
                        dynamicFormValue.setFormColumnId(dynamicForm.getSequenceNbr());
                        dynamicFormValue.setAppKey(appKey);

                        vo.setFormItemDescr(dynamicFormValue);
                        vo.setSort(dynamicFormValue.getSort());
                        listForm.add(vo);
                        break;
                    default:
                        vo = new DynamicFormInitDto(dynamicForm.getFieldCode(), dynamicForm.getFieldName(),
                                dynamicForm.getFieldType(), new SelectItems(new ArrayList<>()), null);
                        dynamicFormValue = new DynamicFormInstanceDto();
                        BeanUtils.copyProperties(dynamicForm, dynamicFormValue);
                        dynamicFormValue.setSequenceNbr(null);
                        dynamicFormValue.setFormColumnId(dynamicForm.getSequenceNbr());
                        dynamicFormValue.setAppKey(appKey);
                        vo.setFormItemDescr(dynamicFormValue);
                        vo.setSort(dynamicFormValue.getSort());
                        listForm.add(vo);
                        break;
                }
            }
        });

        return listForm.stream().sorted(Comparator.nullsFirst(Comparator.comparing(DynamicFormInitDto::getSort))).collect(Collectors.toList());
    }

    public List<SelectItem> getdata(Collection<DataDictionary> list) {
        List<SelectItem> listAlertListvalue = new ArrayList<SelectItem>();
        for (DataDictionary dataDictionary : list) {

            listAlertListvalue.add(new SelectItem(dataDictionary.getSequenceNbr().toString(),
                    dataDictionary.getName(), dataDictionary.getCode()));
        }
        return listAlertListvalue;
    }


}
