<template>
    <div>
        <div v-for="(item, index) in formConfig" :key="index" class="step-form-package">
            <div v-for="(sItem, key) in item.config" class="step-item" :key="key">
                <template v-if="sItem.type === 'input'">
                    <HandleFormItem class="step-row" :field-item-label="fieldItemLabel" @blur="onBlur(key, $event)"
                        :item="sItem" v-model="formFields[key]" :field-key="prefixKey+uuid + '_' + key"
                        @copy="onCopy(sItem, key)" :error="errors[key]" @update:error="errors[key] = false"
                        :orange-bg="orangeBgFields[key]" />
                </template>
                <template v-else-if="sItem.type === 'inputNumber'">
                    <HandleFormItem class="step-row" :field-item-label="fieldItemLabel" :field-key="prefixKey+uuid + '_' + key"
                        type="inputNumber" @blur="onBlur(key, $event)" :item="sItem"
                        @input="onInputNumberChange(key, $event)" v-model="formFields[key]" @copy="onCopy(sItem, key)"
                        :error="errors[key]" @update:error="errors[key] = false" :orange-bg="orangeBgFields[key]" />
                </template>
                <template v-else-if="sItem.type === 'select'">
                    <HandleFormItem class="step-row" :field-item-label="fieldItemLabel" :field-key="prefixKey+uuid + '_' + key"
                        type="select" @blur="onBlur(key, $event)" :item="sItem" v-model="formFields[key]"
                        @change="onSelectChange(key, $event, sItem.type)"
                        @copy="onCopy(sItem, key)" :error="errors[key]" @update:error="errors[key] = false"
                        :orange-bg="orangeBgFields[key]" />
                </template>
                <template v-else-if="sItem.type === 'checkbox'">
                    <HandleFormItem class="step-row" :field-item-label="fieldItemLabel" :field-key="prefixKey+uuid + '_' + key"
                        type="checkbox" :item="sItem" v-model="formFields[key]"
                        @change="onSelectChange(key, $event, sItem.type)"
                        @copy="onCopy(sItem, key)" :error="errors[key]" @update:error="errors[key] = false"
                        :orange-bg="orangeBgFields[key]" />
                </template>
                <template v-else-if="sItem.type === 'button'">
                    <HandleFormItem 
                        type="button" 
                        :item="getButtonItem(sItem)"
                        @clickButton="(e)=>handleClickButton(e,item)" />
                </template>
                <!-- 仪器（instrument）sj(药剂) gsp(供试品) mix（药剂/供试品/给药制剂） -->
                <template v-else-if="isRegent(sItem)">
                    <HandleFormItem class="step-row" :field-item-label="fieldItemLabel" :field-key="prefixKey+uuid + '_' + key"
                        :type="sItem.type" :error="errors[key]"
                        @onRegentSubmit="(data)=>onRegentSubmit(data,key,sItem)"
                        @update:error="errors[key] = false"  :item="getRegentItem(sItem)"
                        :value="formFields[key]" />
                </template>
                <template v-else-if="sItem.type === 'text'">
                    <span>{{ sItem.label }}</span>
                </template>
                <template v-else-if="sItem.type === 'span'">
                    <span>{{ formFields[key] }}</span>
                </template>
                <template v-else-if="sItem.type === 'zlfz'">
                    {{ key }}
                    <ZLSubPackage @update="(data)=>onSubPackageUpdate(data,key)" :subData = "formFields[key]" :ref="'zlSubPackageRef_'+key" />
                </template>
            
                <div v-show="isShowOther(formFields[key])" class="flex flex1">
                    <div class="other-title">{{sItem.otherLabel ? $t(sItem.otherLabel) : $t("template.common.other") }}</div>
                    <HandleFormItem sourceFrom = "step" class="step-row" :field-item-label="fieldItemLabel" :field-key="prefixKey+uuid+'_'+sItem.otherCode" @blur="onBlur(key, $event)" :item="getOtherItem(sItem)"
                        v-model="formFields[sItem.otherCode]" @copy="onCopy(sItem, key)"
                        :error="errors[sItem.otherCode]" @update:error="errors[sItem.otherCode] = false"
                        :orange-bg="orangeBgFields[sItem.otherCode]" />
                </div>
            </div>
        </div>
    
    </div>
</template>

<script>
import HandleFormItem from '@/components/Template/HandleFormItem.vue'
import formPackageMixins from '@/components/Template/mixins/formPackageMixins.js'
import ZLSubPackage from '@/components/Template/StepComponents/ZLSubPackage.vue'
import { isShowOther } from "@/utils/formPackageCommon.js";
import { EventBus } from "@/utils/eventBus";
import { getuuid,isRegent} from "@/utils/index.js";
import moment from 'moment'
export default {
    inject: ['templateFillType','templateData'],
    components: {
        HandleFormItem,
        ZLSubPackage
    },
    mixins: [formPackageMixins],
    props: {
        formConfig: {
            type: Array,
            default: []
        },
        formData: {
            type: Object,
            value: () => ({})
        },
        //主要标识当前表单属于哪个模块，用于传给后端
        fieldItemLabel: {
            type: String,
            default: "",
        },
        prefixKey: {
            type: String,
            default: ""
        }
    },
    mounted() {
    },
    unmounted() {
    },
    data() {
        return {
            formFields: {},//表单绑定字段
            allFieldsConfig: {},//包含config的所有字段,主要用于校验表单是否填写
            errors: {},//存储表单错误信息，用于标红提示
            orangeBgFields: {},// 存储需要橙色背景的字段
            isShowOther,
            currentClickKey: "",//当前点击的字段key
            uuid:getuuid(),
            isRegent,
        }
    },
    methods: {
        // //试剂/仪器等弹窗提交
        onRegentSubmit(data,key,item){
            this.updateFormData(key,data.selectedId);
            console.log(data.selectedId,key,"data.selectedId")
            if(data.selectType){
                this.allFieldsConfig[key].sjSelectType = data.selectType;
            }
            this.formFields[`selectInfo_${key}`] = data.selectInfo;
            // this.$emit("onRegentSubmit", {selectInfo:data,key,config:item});
        },
        getRegentItem(item,fieldCode="type"){
            const type = item[fieldCode] ;
            return {
                label: "",
                type,
                fillType: item.subFillType || item.fillType,
                parentLabel: item.label,
            }
        },
        updateZlfzData(key,data){
            const ref = this.$refs[`zlSubPackageRef_${key}`][0];
            if(ref){
                ref.updateFormData(data);
            }
        },
        // 子组件数据更新处理方法
        onSubPackageUpdate(data,key){
            this.formFields[key] = data;
        },
        // 重写子组件校验钩子方法，检查ZLSubPackage的表单验证
        validateSubComponents() {
            const refs = [];
            // 遍历formConfig，找到所有type为zlfz的项
            for (const item of this.formConfig) {
                if (item.config) {
                    for (const key in item.config) {
                        const sItem = item.config[key];
                        if (sItem.type === 'zlfz') {//质量分装
                            // 根据key构建ref名称
                            const refName = `zlSubPackageRef_${key}`;
                            const zlSubPackageRef = this.$refs[refName];
                            // 检查ZLSubPackage组件的表单验证
                            if (zlSubPackageRef) {
                                refs.push(zlSubPackageRef);
                                
                            }
                        }
                    }
                }
            }
            if(refs.length === 0){
                return {valid: true, error: ''};
            }else{//目前一个步骤只会有一个质量分装，所以不考虑多个的情况
                return refs[0][0].validateFormData();
            }
        },
        getSjResource(){
            const {allFieldsConfig,formFields} = this;
            const sjResource = [],yqResource = [];
            for(const key in allFieldsConfig){
                const item = allFieldsConfig[key];
                if(item.type === "xb" || item.type === "sj" || item.type === "gsp" || item.type === "mix"){
                    if(formFields[key]){
                        let o = {
                            ...formFields[`selectInfo_${key}`],
                            value:formFields[key],
                        }
                        if(item.ylCode){
                            o.syl = formFields[item.ylCode];//用量
                        }
                        if(item.dwCode){
                            o.syldw = formFields[item.dwCode];//单位
                        }
                        sjResource.push(o);
                    }
                }else if(item.type === "yq"){
                    if(formFields[key]){
                        yqResource.push({
                            type:item.type,
                            value:formFields[key],
                            ...formFields[`selectInfo_${key}`],
                        });
                    }
                }
            }
            return {
                sjResource,
                yqResource,
            }
        },
        // 点击按钮
        handleClickButton(e,item){
            const {buttonName = ""} = e;
            const {config} = item;
            if(buttonName === '开始' && config.hasOwnProperty("startDate")){
                this.updateFormData("startDate",moment().format('YYYY-MM-DD HH:mm'))
            }else if(buttonName === '结束' && config.hasOwnProperty("endDate")){
                this.updateFormData("endDate",moment().format('YYYY-MM-DD HH:mm'))
            }
            this.$emit("clickButton",e,item)
        },
        // 获取按钮项
        getButtonItem(sItem) {
            return {
                ...sItem,
                fillType:sItem.fillType || "actFill",
            }
        },
        getClickableItem(sItem) {
            return {
                ...sItem,
                type:sItem.type,
            
            }
        },
    }
}
</script>

<style lang="scss" scoped>
.step-form-package {
    display: flex;
    align-items: center;
    font-size: 14px;
    flex-wrap: wrap;
}

.step-row {
    min-width: 180px;
}

.step-item {
    display: flex;
    align-items: center;
    margin-left: 5px;
    margin-bottom: 10px;
    min-height: 28px;
}
</style>