<template>


    
        <!-- <span style="font-size: 14px; margin-right: 12px;padding-top: 4px;" class="small-span" >{{ props.data.item?props.data.item.label:"关联表单" }}</span> -->
        <!-- <div style="margin-right: 12px;"></div> -->
        <!-- <span style="width: 7px;"></span> -->
        <el-select v-if="!tableFlag" v-model="value1" placeholder="请选择"  @change="asfValueChanged" :style="getFormItemInputStyle(configStyle,2)" >
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-if="tableFlag" v-model="value2" placeholder="请选择"  @change="asfValueChangedTable" :style="getFormItemInputStyle(configStyle,2)">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
    

</template>

<script lang='ts' setup>
import request from '@/utils/axios/index'
import { AnalysisCss,AnalysisInputCss } from '@/api/common/cssInfo'
import { inject } from 'vue'
import { FormList,FormItem } from "@/api/lowCode/form/type"
import { 
    formatNumber, 
	objectToArray,
	constControlChange,
    constSetFormOptions,
    constFormProps,
    constGetControlByName
} from '@/api/lowCode/utils';
//组件css部分
const configStyle = computed(() => {
    return props.data.styles || {}
})
const getFormItemInputStyle = (ele: any,sty:number) => {
    if(ele?.inputStyle){
      //console.log("返回栅格宽度4",AnalysisInputCss(ele?.inputStyle,sty))
      return AnalysisInputCss(ele?.inputStyle,sty)
    }
}
const asfRangeDoubleCondiChangeObj = inject('asfRangeDoubleCondiChangeObj')
watch(() => asfRangeDoubleCondiChangeObj, (newVal: any) => {
    value1.value = ""
    value2.value = ""

    let newValObj = JSON.parse(JSON.stringify(newVal.value));

    let toShowDoubleCondiValValStr = newValObj.toShowDoubleCondiValVal + "";

    const filteredData = asfDataTitlesData.filter((item: any) => item.doubleCondiVal == toShowDoubleCondiValValStr);

    options.value = filteredData

}, { deep: true })
const props = withDefaults(
    defineProps<{
        data: FormList
        formProps: Object
        tablekey: any
        rowIndex: number
        modelValue?: any // 子表和弹性布局时时有传
        tProp?: string // 子表时的form-item的prop值，用于子表校验用
    }>(),
    {}
)

const emits = defineEmits(["valueChanged", "valueChangedTable","change","update:modelValue","asfValueChanged"]);
const value1 = ref('')
const value2 = ref('')
const valueTest = ref('')
let tableFlag = false
const options = ref([])


function hasTableProperty(obj: object): boolean {
    for (let key in obj) {
        if (key.startsWith("table")) {
            return true;
        }
    }
    return false;
}
let asfDataTitlesData: any = []
onMounted(() => {
    if (props.data.control.formid != null && props.data.control.formid != "") {
        getAsfDataTitles().then(({ data }) => {
            asfDataTitlesData = data
            //console.log(data)
            options.value = data
            //console.log(props)
            value1.value = props.formProps.model[props.data.name]



            // 确定哪个或哪些表单是被放置在子表中的 
            valueTest.value = props.formProps.model
            for (let key in valueTest.value) {
                if (key.startsWith("table")) {
                    if (Array.isArray(valueTest.value[key])) {

                        if (valueTest.value[key].length > 0) {
                            for (let key1 in valueTest.value[key][0]) {
                                if (key1 == props.data.name) {
                                    tableFlag = true

                                    //当前关联表单在子表的第几行
                                    //console.log(props.formProps.model[key][props.rowIndex][key1])
                                    value2.value = props.formProps.model[key][props.rowIndex][key1]
                                }
                            }
                        }
                    }
                }
            }





        });
    }


})
let fillFieldsMaster = "";
let fillFieldsChild: any
function asfValueChanged() {

    let val = {
        options: options.value,
        currentVal: value1.value,
        fillFieldsMaster: fillFieldsMaster,
        fillFieldsChild: fillFieldsChild,
        asfFormId: props.data.control.formid,
        glbbddbd: props.data.control.glbbddbd,
        tableFlag: false,
    }

    valueChanged(val)
    //emits("valueChanged", val)
}

function asfValueChangedTable() {

    let val = {
        options: options.value,
        currentVal: value2.value,
        fillFieldsMaster: fillFieldsMaster,
        fillFieldsChild: fillFieldsChild,
        asfFormId: props.data.control.formid,
        glbbddbd: props.data.control.glbbddbd,
        tableFlag: true,
    }
    valueChangedTable(val)
    //emits("valueChangedTable", val)
}

function getAsfDataTitles() {
    let dataTitle = ''
    //console.log(props)
    if (props.tablekey && props.tablekey.dataTitle && props.tablekey.dataTitle != null && props.tablekey.dataTitle.length > 0) {
        for (let i = 0; i < props.tablekey.dataTitle.length; i++) {
            dataTitle = dataTitle + props.tablekey.dataTitle[i] + "###"
        }
    }
    //数据填充规则条件参数处理


    //console.log(props.data.control.fillRoles)
    //let fillRoles = JSON.parse(JSON.stringify(props.data.control.fillRoles))
    if (props.data.control.fillRoles && props.data.control.fillRoles.master && props.data.control.fillRoles.master.length > 0) {
        for (let i = 0; i < props.data.control.fillRoles.master.length; i++) {
            if (props.data.control.fillRoles.master[i].leftValue != "" && props.data.control.fillRoles.master[i].rightValue != "") {
                fillFieldsMaster = fillFieldsMaster + props.data.control.fillRoles.master[i].id + "_" + props.data.control.fillRoles.master[i].leftValue + "_" + props.data.control.fillRoles.master[i].rightValue + ";"
            }
        }
    }
    if (props.data.control.fillRoles.child) {
        fillFieldsChild = JSON.parse(JSON.stringify(props.data.control.fillRoles.child))
        fillFieldsChild = fillFieldsChild.filter((item: any) => {
            //console.log(item)
            return item.asfChildTableKey != ""
        })


        //console.log(fillFieldsChild)
        for (let i = 0; i < fillFieldsChild.length; i++) {
            if (fillFieldsChild[i].asfChildTableKey != "") {
                if (fillFieldsChild[i].childRoles.length > 0) {
                    fillFieldsChild[i].childRoles = fillFieldsChild[i].childRoles.filter((element: any) => {
                        if (element.leftValue != "" && element.rightValue != "") {
                            return element
                        }
                    });
                }

            }
        }
        //console.log(fillFieldsMaster)
    }



    /* 
    
    */
    fillFieldsChild = JSON.stringify(fillFieldsChild)
    //console.log(fillFieldsChild)
    return request({
        url: '/javasys/lowCode/AssociatedForms/getAsfDataTitles',
        method: 'post',
        data: {
            glbbddbd: props.data.control.glbbddbd,
            formId: props.data.control.formid,
            dataTitle: dataTitle,
            rangeFormula: props.data.control.dataRangeGongShi.mathsFormula,
            rangeString: props.data.control.dataRangeGongShi.mathsString,
            hideFormula: props.data.control.hideGongShi.mathsFormula,
            hideString: props.data.control.hideGongShi.mathsString,
            masterOnField: props.data.name,
            fillFieldsMaster: fillFieldsMaster,
            fillFieldsChild: fillFieldsChild,
        },
    });
}

const changeEvent = inject(constControlChange, '') as any
const value = computed({
	get() {
		if (props.tProp) {
			// 表格和弹性布局
			return props.modelValue
		} else {
			return formProps.value.model[props.data.name]
		}
	},
	set(newVal: any) {
		if (props.tProp) {
			emits('update:modelValue', newVal)
		}
		updateModel(newVal)
	}
})
const updateModel = (val: any) => {
	//console.log("dfsasdfasdf")
	let controlAttribute = ""
	if (props.data.control) {
		if (props.data.control.type) {
			controlAttribute = props.data.control.type
		}
	}
	changeEvent &&
		changeEvent({
			key: props.data.name,
			value: val,
			data: props.data,
			tProp: props.tProp,
			type: props.data.type,
			attribute: controlAttribute
		})
}



const valueChanged = (val: any) => {
	//console.log("关联表单选择--->", val)

	value.value = val.currentVal
	emits("asfValueChanged", val)





}


const valueChangedTable = (val: any) => {
	//console.log("关联表单选择table--->", val)
	
	
	//emits("asfValueChanged", val)


	//确定哪个或哪些表单是被放置在子表中的
	//valueTest.value = formProps.model
	//console.log(formProps.value.model)
	for (let key in props.formProps.model) {
		if (key.startsWith("table")) {
			if (Array.isArray(props.formProps.model[key])) {
				if (props.formProps.model[key].length > 0) {
					for (let key1 in props.formProps.model[key][0]) {

						if (key1 == props.data.name) {
							/* console.log(key1)
							//当前关联表单在子表的第几行
							console.log(props.rowIndex)
							//当值变化时
							console.log(formProps.value.model[key][props.rowIndex][key1])
							console.log(val.currentVal) */
							props.formProps.model[key][props.rowIndex][key1] = val.currentVal
							val.key = key
							val.propsRowIndex = props.rowIndex
							val.key1 = key1
							emits("asfValueChanged", val)
						}
					}
				}

			}

		}
	}

}




</script>

<style>

</style>