
import { ConfigStore } from '../stores/ConfigStore'
import { ParamsStore } from '../stores/ParamsStore'
import { DataStore } from '../stores/DataStore'

// 跳转页面
export const goto_page = ({page_code,page_name,}:any) => {
  uni.navigateTo({
      url: `/common/views/pages/dynamic/child?page_code=${page_code}`,
    })
}
export const goto_back = ({page_code, params}:any) => {
  uni.navigateBack()
}



// 获取值
export const gather = ({page_code, container_code, type, run, event_type}:any) => {
  return new Promise((resolve, reject) => {
    let filters:any = run?.filter?.split(',') || null
    let data = DataStore().container[page_code][container_code]
    if(type=='form'){
      let newData:any
      if(Array.isArray(data)){
        newData = []
        for(let row of data){
          let obj:any = {}
          if(run?.filter && filters?.length>0){
            for(let key of filters){
              if(row[key]){
                Object.assign(obj, {[key]:row[key]})
              }
            } 
          }else{
            Object.assign(obj, row)
          }
          newData.push(obj)
        }
      }else{
        newData = {}
        if(run?.filter && filters?.length>0){
          for(let key of filters){
            if(data[key]){
              Object.assign(newData, {[key]:data[key]})
            }
          } 
        }else{
          Object.assign(newData, data)
        }
      }
      resolve(newData)
    }
    else if(type=='table'){
      let newData = []
      // 校验主键必填
      if(filters){
        for(let row of data){
          let newRow = {}
          for(let key of filters){
            if(row[key]){
              Object.assign(newRow, {[key]:row[key]})
            }
          }
          newData.push(newRow)
        }
      }else{
        newData = data
      }
      resolve(newData)
    }
  })
}


// 设置参数
export const set_params = ({data, page_code, container_code}:any) => {
    ParamsStore().set({data, page_code, container_code})
}



// 事件中跨容器取参数   $$COM
export const get$$containerParams = (apiParams:any) => {
  let newApiParams = <any>{}
  let CONTAINER = DataStore().container
  for(let key in apiParams){
      if(apiParams[key].indexOf('$$CON')==0){
          let arr = apiParams[key].slice(6).split('.')
          let target:any = CONTAINER
          for(let index of arr){
              target = target[index]
          }
          newApiParams[key] = target || ''
      }else{
          newApiParams[key] = apiParams[key]
      }
  } 
  return newApiParams
}



// 处理默认值
export const getDefaultData = (controls:any, data:any) => {
  let def_values:any = {}
  for(let key in controls){
      // key 是字段； 以配置了默认值的字段为主；
      let control = controls[key]
      let contorlType = control['type']
      let def_value = control['def_value']
      if(!def_value) continue

      if(contorlType=='select' ){
          if(def_value.indexOf('$$SELECT(')==0){
            continue
          }
          else if(contorlType=='select' && def_value){
              control['select'].getDefault = [def_value]
          }
          else if(contorlType=='select' && def_value.indexOf(',')>0){
              def_values[key] = def_value.split(',')
          }
      }else if((contorlType=='date' || contorlType=='datetime' ) && def_value.indexOf('$$DATE(')==0){
           // 时间默认值
          def_values[key] = dateFormat(def_value)
      }
      else if((contorlType=='daterange' || contorlType=='datetimerange' ) && def_value.indexOf('$$DATE(')==0){
        // 时间区域默认值
        let arr = def_value.split('|') 
        def_values[key] = [dateFormat(arr[0]), dateFormat(arr[1])]
      }
      // 其他
      else{
          def_values[key] = def_value
      }
  }
  Object.assign(data, def_values)
}

import dayjs from 'dayjs'
const dateFormat = ( $$date:any ) => {
  let arr = $$date.split(')') // 分解字符串，以')'；
  arr.splice(arr.length - 1, 1) // 删除最后一位无效元素；
  // 处理字符串 生成format
  let format = arr[0].replace('$$DATE(','')
    .replace('yyyy','YYYY')
    .replace('mm','MM')
    .replace('dd','DD')
    .replace('hh','HH')
    .replace('nn','mm')
    .replace('iii','SSS')
  arr.shift() // 删除第一位元素， 为format， 剩下的将被处理成方法； 
  let date:any = dayjs().format(format)
  for(let str of arr){
      str = str.replace('(',',')
          .replace('m','M')
          .replace('n','m')
          .replace('i','ms')
          .split(',');
      if(str[0]=='+') date = dayjs(date).add(str[1], str[2])
      else if(str[0]=='-') date = dayjs(date).subtract(str[1], str[2])
  }

  return dayjs(date).format(format)
}


// 清除当前页面的值和store值、传参
export const clearPage = ({page}:any) => {
  let page_code = page.page_code


  if(page.container_query){
    page.container_query.data = {}
  }
  for(let container of page.containers){
    if(container.type=='form'){
      container.data = {}
    }else if(container.type=='table'){
      container.data = []
    }
  }

  // store
  const store_data = DataStore()
  const store_params = ParamsStore()



  store_data.container[page_code] = {}
  store_params.container[page_code] = {}
}



// 带参 list_carry
export const setMappings = (data:any, control:any) => {
  let Mappings = control.select.mappings
  if(!Mappings) return 
  let options = control.select.activeOption 
  if(!options) return  // 行数据在
  if(options instanceof Array) return  // 如果多选 return
  for(let item of Mappings){
      let target = item['param'] || item['control']
      if(options[target] != null && options[target] != undefined){
          data[item['control']] = options[target] 
      }
  }
}