import { verifyReportCode } from '@/api/design/report';
import { getAllDbDicData } from '@/api/design/table';
import { cloneDeep } from 'lodash-es';
// 数据字典
export const dicObj = {
  dic_whether: [
    { label: '是', value: 'Y' },
    { label: '否', value: 'N' },
  ],
  tableSelect: [
    { label: '多选', value: 'multiple' },
    { label: '单选', value: 'radio' },
    { label: '禁用', value: 'disabled' },
  ],
  dataConfig: [
    { label: '分页', value: 'page' },
  ],
  dataConfigSelect: [
    { label: '需登录', value: 'authFalse', desc: '访问该表接口：需登录' },
    { label: '需登录、鉴权', value: 'authTrue', desc: '访问该表接口：需登录并且需要配置菜单权限' },
    { label: '不登录可查询数据', value: 'authOpen', desc: '访问该表查询接口：不需要登录' },
  ],
  tableConfig: [
    { label: '固定表格高度', value: 'height' },
    { label: '序号列', value: 'index' },
    { label: '纵向边框', value: 'border' },
    { label: '斑马纹样式', value: 'stripe' },
    { label: '隐藏导出按钮', value: 'hideExport' },
  ],
  fieldType: [
    { label: '字符串 String', value: 'String' },
    { label: '整数 Integer', value: 'Integer' },
    { label: '大整数 BigInt', value: 'BigInt' },
    { label: '小数 BigDecimal', value: 'BigDecimal' },
    { label: '日期 Date', value: 'Date' },
    { label: '时间 Time', value: 'Time' },
    { label: '日期时间 DateTime', value: 'DateTime' },
    { label: '文本 Text', value: 'Text' },
    { label: '大文本 LongText', value: 'LongText' },
    { label: '二进制 Blob', value: 'Blob' },
  ],
  cellWidthType: [
    { label: '固定', value: 'fixed' },
    { label: '最小', value: 'min' },
  ],
  queryMode: [
    { label: '精确查询', value: 'EQ' },
    { label: '模糊查询', value: 'LIKE' },
    { label: '范围查询（仅适用于日期、时间、数字）', value: 'RANGE' },
    { label: '包含查询（in）', value: 'IN' },
    { label: '多选查询（in）', value: 'MORE_IN' },
    { label: '不等于（!=）', value: 'NE' },
  ],
}
export const getDicObj = (key) => {
  const obj = {}
  if (dicObj[key]) dicObj[key].forEach(item => obj[item.value] = item.label)
  return obj
}

const rules_required = (label, type = '') => [{ required: true, message: `${['select'].includes(type) ? '请选择' : '请输入'} ${label}`, trigger: "blur" }]
const reportCode_required = async (rule, value, callback) => {
  if (value === '') callback(new Error('请输入 报表编码'));
  else {
    const bool = await verifyReportCode(value)
    if (bool) callback(new Error('报表编码已存在，请修改'));
    else callback()
  }
};

const dataSourcesCode_dicFormatter = (data) => {
  data = data.map(item => {
    if (item.id === 0) {
      item.dbCode = 'master'
      item.name = `${item.name}（本地数据源）`
    }
    else item.name = `${item.name}（${item.dbType}）`
    return item
  })
  return data.filter(item => item.dbCode)
}

const dataOriginDicObj = {}

export const getDataOriginDicData = (dbCode, isReacquire?) => {
  return new Promise(async resolve => {
    if (isReacquire) for (const key in dataOriginDicObj) delete dataOriginDicObj[key]
    if (dataOriginDicObj[dbCode]) return resolve(dataOriginDicObj[dbCode])
    let data = []
    if (dbCode == 'master') data = await getAllDbDicData({ systemFlag: 'Y' })
    else data = await getAllDbDicData({ dataSourcesCode: dbCode })
    dataOriginDicObj[dbCode] = dataOrigin_dicFormatter(data, dbCode)
    resolve(dataOriginDicObj[dbCode])
  })

}

const dataOriginObj = {}
const dataOrigin_dicFormatter = (data, dbCode) => {
  const sysList: any[] = []
  const dbList: any[] = []
  data.forEach(item => {
    const row = {
      label: `${item.tableName}（${item.tableDescribe}）`,
      tableText: item.tableDescribe,
      tableName: item.tableName,
      value: item.tableId,
      type: 'table',
      fieldList: item.fieldModelList.map(child => {
        let label = child.fieldCode
        if (child.fieldName) label = `${label}（${child.fieldName}）`
        return { label, value: child.fieldCode, tableName: item.tableName, type: 'field', fieldType: child.fieldType }
      })
    }
    if (item.tableId == item.tableName) sysList.push(row)
    else if (item.tableClassify !== 2) dbList.push(row)
    if (!dataOriginObj[dbCode]) dataOriginObj[dbCode] = {}
    dataOriginObj[dbCode][item.tableId] = row
  })
  const dicData: any[] = []
  if (sysList.length) dicData.push({ label: '系统表', value: 'sys', disabled: true, children: sysList })
  if (dbList.length) dicData.push({ label: '表单开发', value: 'dbForm', disabled: true, children: dbList })
  return dicData
}

//表格配置
const tableOptionColumn = {
  reportName: { label: '报表名称', display: false, search: true, minWidth: 140 },
  reportCode: { label: '报表编码', display: false, search: true, minWidth: 140, overHidden: true },
  javaConfig: { label: 'JAVA类路径', display: false, search: true, minWidth: 140, overHidden: true, searchLabelWidth: 100, },
  createTime: { label: '创建时间', type: 'datetime', format: 'YYYY-MM-DD HH:mm:ss', valueFormat: 'x', display: false, width: 160 },
  custom_form: { label: '', labelWidth: 0, span: 24, hide: true, showColumn: false },
  custom_info: { label: '', labelWidth: 0, span: 24, hide: true, showColumn: false }
}
// 表单配置
const customFormColumn = {
  reportName: { label: '报表名称', rules: rules_required('报表名称') },
  reportCode: { label: '报表编码', rules: [...rules_required('报表编码'), { validator: reportCode_required, trigger: 'blur', required: true }] },
  groupReportId: { label: '分组类型', type: 'tree', value: '', dicData: [], filterable: true, defaultExpandAll: true, props: { label: 'name', value: 'id' } },
  dataSourcesCode: { label: '数据源', type: 'select', value: 'master', span: 6, clearable: false, dicUrl: '/infra/data-source-config/list', props: { label: 'name', value: 'dbCode' }, dicFormatter: dataSourcesCode_dicFormatter },
  dataOrigin: { label: '数据表', type: 'tree', value: '', span: 8, dataType: 'string', multiple: true, filterable: true, parent: false, defaultExpandAll: true, dicData: [] },
  originButton: { label: '', labelWidth: 0, },
  javaConfig: { label: 'JAVA类路径', span: 12 },
  dataConfig: { label: '数据配置', type: 'checkbox', span: 24, dicData: dicObj.dataConfig, dataType: 'string', value: ['page', 'authFalse'] },
  tableConfig: { label: '表格配置', type: 'checkbox', span: 24, dicData: dicObj.tableConfig, dataType: 'string', value: ['height', 'header', 'menu', 'index', 'border'] },
}

const infoColumn = {
  fieldColumn: {
    fieldCode: { title: '字段编码', minWidth: 120, editRender: { name: 'LowInput', verifyEdit: true } },
    fieldName: { title: '字段名称', minWidth: 120, editRender: { name: 'LowInput' } },
    parentFieldName: { title: '父字段名称', width: 120, editRender: { name: 'LowSelect', dicData: [], filterable: true, clearable: true } },
    labelI18n: { title: '国际化配置', width: 140, editRender: { name: 'LowMonacoEditorInput', events: {} } },
    fieldType: { title: '字段类型', minWidth: 100, editRender: { name: 'LowSelect', verifyEdit: true, dicData: dicObj.fieldType, dicObj: getDicObj('fieldType') } },
    queryIsDb: { title: '接口查询', width: 75, align: "center", editRender: { name: 'LowCheckbox' } },
    queryIsWeb: { title: '查询控件', width: 75, align: "center", editRender: { name: 'LowCheckbox' } },
    queryMode: { title: '查询模式', width: 130, editRender: { name: 'LowSelect', verifyEdit: true, dicData: dicObj.queryMode, dicObj: getDicObj('queryMode') } },
    dictCode: { title: '字典Code', width: 180, editRender: { name: 'LowSelect', verifyEdit: true, filterable: true, noStop: true, dicData: [] } },
    isExport: { title: '是否可导出', width: 90, align: "center", editRender: { name: 'LowCheckbox' } },
    isHideCol: { title: '隐藏列', width: 90, align: "center", editRender: { name: 'LowCheckbox' } },
    isAmount: { title: '是否合计', width: 75, align: "center", editRender: { name: 'LowCheckboxSum' } },
    isDimension: { title: '是否维度', width: 75, align: "center", editRender: { name: 'LowCheckbox' } },

    isHideDimension: { title: '维度隐藏列', width: 180, editRender: { name: 'LowSelectMultiple', verifyEdit: true, filterable: true, multiple:true,dicData: [] } },
    isShowSort: { title: '是否排序', width: 75, align: "center", editRender: { name: 'LowCheckbox' } },
    hasChildren: { title: '子字段', width: 90, align: "center", editRender: { name: 'LowButton', disabled: (row) => row.isSubField === true, buttonText: '添加子字段', buttonType: 'primary', buttonSize: 'small' } },
  },
}

const infoApiKey = {}
const apiKey = { fieldColumn: 'fieldList' }
for (const key in infoColumn) {
  if (apiKey[key]) {
    const keys = Object.keys(infoColumn[key])
    if (key == 'fieldColumn') {
      keys.push('sortNum')
      // 确保父子关系字段被包含
      if (!keys.includes('parentFieldCode')) {
        keys.push('parentFieldCode')
      }
      if (!keys.includes('hasChildren')) {
        keys.push('hasChildren')
      }
    }
    infoApiKey[apiKey[key]] = keys
  }
}

//默认值
const infoDefaultData = {
  basics: {
    fieldCode: '', fieldName: '', parentFieldName: '', labelI18n: '', fieldType: 'String', queryIsDb: 'N', queryIsWeb: 'N', queryMode: 'LIKE', dictCode: '',isHideCol:'N', isExport: 'Y', isShowSort: 'N', isAmount: '', isDimension: '',isHideDimension:'', hasChildren: 'N', isSubField: false, parentFieldId: '', parentFieldCode: '',
  },
}


//格式化接口初始数据
const formattingInitData = (editInfoData) => {
  const optionObj = {}

  for (const apiKey in infoApiKey) {
    const key = apiKey
    optionObj[key] = {}
    editInfoData[key]?.forEach(item => optionObj[key][item.fieldCode] = item)
  }

  const infoData = [] as any
  editInfoData.fieldList.forEach(fieldItem => {
    const fieldCode = fieldItem.fieldCode
    const infoItem: any = {}

    for (const apiKey in infoApiKey) {
      const dataKey = apiKey
      if (!optionObj[dataKey]) continue
      const editItem = optionObj[dataKey][fieldCode] || cloneDeep(infoDefaultData)

      infoItem[`${apiKey}_id`] = editItem.id
      for (const i in infoApiKey[apiKey]) {
        const key = infoApiKey[apiKey][i]
        if (apiKey != 'fieldList' && ['fieldCode', 'fieldName'].includes(key)) continue
        infoItem[key] = editItem[key]
      }
    }
    infoData.push(infoItem)
  })
  return { infoData }
}

export const pageOption = {
  tableOptionColumn, customFormColumn, dataOriginObj,
  infoApiKey,
  reportCode_required
}
export const tableInfoOption = {
  infoColumn,
  infoDefaultData,
  formattingInitData,
}
