<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" :class="sItem.type === 'radio' ? 'radio-row' : ''" :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+'_' + key"
                        :ref="key"
                        @copy="onCopy(sItem, key)" :error="errors[key]" @update:error="errors[key] = false"
                        :orange-bg="getOrangeBg(key,sItem)" />
                </template>
                <template v-else-if="sItem.type === 'inputNumber'">
                    <HandleFormItem class="step-row" :field-item-label="fieldItemLabel" :field-key="prefixKey+'_' + key"
                        type="inputNumber" @blur="onBlur(key, $event)" :item="sItem" :ref="key"
                        @input="onInputNumberChange(key, $event)" v-model="formFields[key]" @copy="onCopy(sItem, key)"
                        :error="errors[key]" @update:error="errors[key] = false" :orange-bg="getOrangeBg(key,sItem)" />
                </template>
                <template v-else-if="sItem.type === 'select'">
                    <HandleFormItem class="step-row" :field-item-label="fieldItemLabel" :field-key="prefixKey+'_' + key"
                        type="select" @blur="onBlur(key, $event)" :item="sItem" v-model="formFields[key]"
                        @change="onSelectChange(key, $event, sItem.type)" :ref="key"
                        @copy="onCopy(sItem, key)" :error="errors[key]" @update:error="errors[key] = false"
                        :orange-bg="orangeBgFields[key]" />
                </template>
                <template v-else-if="sItem.type === 'checkbox' || sItem.type === 'radio'">
                    <HandleFormItem :class="sItem.type === 'checkbox' ? 'step-row' : ''" :field-item-label="fieldItemLabel" :field-key="prefixKey+'_' + key"
                        :type="sItem.type" :item="sItem" v-model="formFields[key]"
                        @change="onSelectChange(key, $event, sItem.type)" :ref="key"
                        @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" 
                        @beforeSaveRecord="(data, callback)=>onBeforeSaveRecord(data, callback,sItem)"
                        :field-key="prefixKey+'_' + key"
                        :item="getButtonItem(sItem)"
                        @clickButton="(e,v,data)=>handleClickButton(e,item,key,data)" />
                </template>
                <!-- 仪器（instrument）sj(药剂) gsp(供试品) mix（药剂/供试品/给药制剂） -->
                <template v-else-if="isRegent(sItem)">
                    <HandleFormItem class="step-row" :field-item-label="fieldItemLabel" :field-key="prefixKey+ '_' + key"
                        :type="sItem.type" :error="errors[key]"
                        @onRegentSubmit="(data)=>onRegentSubmit(data,key,sItem)"
                        @beforeReagentSubmit="(data, callback) => onBeforeReagentSubmit(data, callback, key)"
                        @update:error="errors[key] = false"  :item="getRegentItem(sItem)"
                        :orange-bg="regentIsExpired(key)"
                        :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'">
                    <ZLSubPackage 
                        @onSubPackageSubmit="onSubPackageSubmit(key) "
                        :stepIndex="stepIndex" :prefixKey="prefixKey+'_'+index" @update="(data)=>onSubPackageUpdate(data,key)" :subData = "formFields[key]" :ref="'zlSubPackageRef_'+key" />
                </template>
                <template v-else-if="isShowJcb(sItem,key)">
                    <JcbComp @update="(data)=>onJcbUpdate(data,key)" :type = "sItem.type" :ref="'jcbComp_'+key" :stepIndex="stepIndex" :prefixKey="prefixKey+'_'+index" @resetRecord = "resetRecord" :item="sItem" :formData="formData[key]" />
                </template>
                <template v-else-if="sItem.type === 'cdmd'">
                    <CdmdComp @update="(data)=>onCdmdUpdate(data,key)" :type = "sItem.type" :cs="formFields.cs" :ref="'cdmdComp_'+key" :stepIndex="stepIndex" :prefixKey="prefixKey+'_'+index" :formData="formData[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+'_'+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 JcbComp from '@/components/Template/StepComponents/JcbComp.vue'
import CdmdComp from '@/components/Template/StepComponents/CdmdComp.vue'
import ZLSubPackage from '@/components/Template/StepComponents/ZLSubPackage.vue'
import { isShowOther } from "@/utils/formPackageCommon.js";
import { EventBus } from "@/utils/eventBus";
import { isRegent,justUpdateFilledFormData} from "@/utils/index.js";
import moment from 'moment'
export default {
    inject: ['templateFillType','templateData'],
    components: {
        HandleFormItem,
        ZLSubPackage,
        JcbComp,
        CdmdComp,
    },
    mixins: [formPackageMixins],
    props: {
        formConfig: {
            type: Array,
            default: []
        },
        formData: {
            type: Object,
            value: () => ({})
        },
        //主要标识当前表单属于哪个模块，用于传给后端
        fieldItemLabel: {
            type: String,
            default: "",
        },
        prefixKey: {
            type: String,
            default: ""
        },
        stepIndex: {
            type: Number,
            default: 0
        }
    },
    mounted() {
    },
    unmounted() {
    },
    data() {
        return {
            formFields: {},//表单绑定字段
            allFieldsConfig: {},//包含config的所有字段,主要用于校验表单是否填写
            errors: {},//存储表单错误信息，用于标红提示
            orangeBgFields: {},// 存储需要橙色背景的字段
            isShowOther,
            currentClickKey: "",//当前点击的字段key
            isRegent,
        }
    },
    methods: {
        
        isShowJcb(item,key){
            const {stepTableFormData = []} = this.formData[key] || {};
            return item.type === 'qb' || (item.type === 'dcjcb' && stepTableFormData.length > 0);
        },
        // 子组件提交处理方法
        onSubPackageSubmit(key){
            this.$emit("onSubPackageSubmit", {key,formData:this.formFields});
        },
        // //试剂/仪器等弹窗提交
        onRegentSubmit(data,key,item){
            this.updateFormData(key,data.selectedId);
            console.log(data.selectedId,key,item,"data.selectedId")
            if(data.selectType){
                this.allFieldsConfig[key].sjSelectType = data.selectType;
            }
            this.formFields[`selectInfo_${key}`] = data.selectInfo;
            if(data.type === "yq"){
                this.formFields[`yqInfo_${key}`] = data.row;
            }
            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;
        },
        // 子组件数据更新处理方法
        onJcbUpdate(data,key){
            this.formFields[key] = data.jcbInfo;
            this.$nextTick(() => {
                justUpdateFilledFormData();
            });
        },
        onCdmdUpdate(data,key){
            this.formFields[key] = data;
            this.$nextTick(() => {
                justUpdateFilledFormData();
                this.$emit("onCdmdUpdate", {key,formData:this.formFields[key]});
            });
        },
        // 重写子组件校验钩子方法，检查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);
                                
                            }
                        }else if(sItem.type === 'qb'){
                            const refName = `jcbComp_${key}`;
                            const jcbCompRef = this.$refs[refName];
                            // 检查ZLSubPackage组件的表单验证
                            if (jcbCompRef) {
                                refs.push(jcbCompRef);
                            }
                        }else if(sItem.type === 'cdmd'){
                            const refName = `cdmdComp_${key}`;
                            const cdmdCompRef = this.$refs[refName];
                            // 检查ZLSubPackage组件的表单验证
                            if (cdmdCompRef) {
                                refs.push(cdmdCompRef);
                            }
                        }
                    }
                }
            }
            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 === "xj" || 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}`],
                        });
                    }
                }
            }
            console.log(sjResource,yqResource,allFieldsConfig,formFields,"sjResource")
            return {
                sjResource,
                yqResource,
            }
        },
        // 点击按钮
        handleClickButton(e,item,key,data){
            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,key,data)
        },
        // 获取按钮项
        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;
}
.radio-row{
    padding-top: 4px;
}
</style>