<template>
    <view class="dynamic_form_input container">
      <component-form_input
        ref="inputFormRef"
        class="comp-form_input"
        v-model:controls="container.controls"
        v-model:data="container.data"
        v-model:buttons="container.buttons"

        :contriner="container"
        :menu_id="container.menu_id"
        :module_code="container.container_code"
      />
    </view>
  </template>
  
<script setup lang="ts">
import { ref, reactive, computed, onBeforeMount, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { onPullDownRefresh, onLoad, onShow } from '@dcloudio/uni-app'
import { ConfigStore } from '../../stores/ConfigStore'
import { DataStore } from '../../stores/DataStore'
import { ParamsStore } from '../../stores/ParamsStore'
import { Form_Controls_Logic } from '../../js/logic'
import { getDefaultData } from '../../js/events'
import { http } from '@/common/utils/request'
  
// store
const store_config = ConfigStore()
const store_data = DataStore()
const store_params = ParamsStore()

// config
const page_code = <any>computed(()=>props.container.page_code)
const container_code = <any>computed(()=>props.container.container_code)

// props
const props = defineProps({
  container: { type: Object, required: true, }
})


const inputFormRef = <any>ref()

const loading_api = <any>ref(false)
const query = () => {
  let event = props.container['queryEvent'] || ''
  let primarykey = event['primarykey'] || ''

  if(event){
    let run =  event['run']
    let api = run['to_API']
    if(api['request_uri'] && api['request_method']){
      let storeParams = {}
      if(Array.isArray(store_params.container[props.container.page_code][props.container.container_code])){
        storeParams = store_params.container[props.container.page_code][props.container.container_code][0]
      }else{
        storeParams = store_params.container[props.container.page_code][props.container.container_code]
      }

      let params = {
        ...storeParams,// 传参
        ...api['params'], // access事件固定参数
      }
      // 存储过程
      if(api['program']){
        Object.assign(params, {
          "[ProcedureName]": api['program']
        })
      }

      // 处理 udf_param_json
      let udf_param_json = {
          "container_id": props.container['container_id'],
          "run_id": run['run_id'],
      }
      if(api['cross_container_to_table']){
          Object.assign(udf_param_json, {cross_container_to_table: api['cross_container_to_table']})
      }
      if(api['order_by']){
          Object.assign(udf_param_json, {order_by: api['order_by']})
      }
      if(api['auth']){
          Object.assign(udf_param_json, {auth: api['auth']})
      }
      Object.assign(params, {
          'udf_param_json': JSON.stringify(udf_param_json)
      })

      loading_api.value = true
      http[api['request_method'].toLowerCase()](api['request_uri'],params).then(async (result:any) => {
        let data = result['result'][0]
        if(data)
          props.container.data = data
        loading_api.value = false
        if(primarykey){
          Object.assign(props.container.data, {'exec_type': 'UP'})
        }
      }).catch((err:any) => {
        loading_api.value = false
      })
    }
  }

}

onBeforeMount(async() => {
  await getDefaultData(props.container.controls,props.container.data)
  if(store_params.container[props.container.page_code]&&store_params.container[props.container.page_code][props.container.container_code]){
    if(Array.isArray(store_params.container[props.container.page_code][props.container.container_code])){
      
      let event = props.container['queryEvent'] || ''
      let primarykey = event['primarykey'] || ''
      let primarykey_arr = []
      if(primarykey){
        primarykey_arr = primarykey.split(',')
        let listData:any = []
        for(let row of store_params.container[props.container.page_code][props.container.container_code]){
          let obj = <any>{}
          for(let key of primarykey_arr){
            await Object.assign(obj, {
              [key]: row[key]
            })
          }
          await listData.push(obj)
        }
        props.container.listData = listData
      }
      props.container.data = await Object.assign(props.container.data, store_params.container[props.container.page_code][props.container.container_code][0] || {})
    }else{
      props.container.data = await Object.assign(props.container.data, store_params.container[props.container.page_code][props.container.container_code] || {})
    }
  }
  for(let key in props.container.controls){
      if(props.container.data[key] == undefined){
        props.container.data[key] = ''
      }
  }
})
onMounted( async ()=>{
  let timer = setTimeout(()=>{
    if(props.container['queryEvent'] && props.container['queryEvent']['primarykey']){
      let hasPrimary = true
      if(props.container.data){
        let primarys = props.container['queryEvent']['primarykey'].split(',')
        for(let primarykey of primarys){
          if(props.container.data[primarykey] == undefined || props.container.data[primarykey] == ''){
            hasPrimary = false
            break;
          }
        }
      }else{
        hasPrimary = false
      }
      if(hasPrimary){
        query()
      }else{
        Object.assign(props.container.data, {'exec_type': 'AD'})
      }
    }
    clearTimeout(timer)
  },100)
})
onUnmounted(() => {
})
const isMounted = ref(false)
onShow(()=>{
  if(isMounted.value){
    query()
  }
})
  

watch(
  ()=>props.container.data,
  async ()=>{
    let data:any
    if(props.container.listData){
      data = []
      for(let row of props.container.listData){
        data.push({
          ...props.container.data,
          ...row,
        })
      }
    }else{
      data = props.container.data
    }
    
    await store_data.set({
      page_code:props.container.page_code, 
      container_code:props.container.container_code, 
      data:data, 
    })

    // 逻辑控制， 控制控件的状态
    await Form_Controls_Logic({
      container: props.container, 
      data: props.container.data, 
      controls: props.container.controls
    })
  },
  { deep: true , immediate: true }
)

const container_params = <any>computed(()=>store_params.container[props.container.page_code][props.container.container_code])

</script>

<style lang="scss">
</style>
  