<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 + '_' + 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 + '_' + 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 + '_' + 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 + '_' + 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）regent(药剂) gsp(供试品) mix（药剂/供试品/给药制剂） -->
                <template v-else-if="sItem.type === 'instrument' || sItem.type === 'regent' || sItem.type === 'gsp' || sItem.type === 'mix' || sItem.type === 'xb'">
                    <HandleFormItem class="step-row" :field-item-label="fieldItemLabel" :field-key="prefixKey + '_' + key"
                        type="clickable" @clickable="handleClickInstrument(key,sItem.type)" :error="errors[key]"
                        @update:error="errors[key] = false" @resetRecord="resetRecord(key)" :item="getClickableItem(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>
            
                <div v-show="isShowOther(formFields[key])" class="flex flex1">
                    <div class="other-title">{{sItem.otherLabel ? $t(sItem.otherLabel) : $t("template.common.other") }}</div>
                    <HandleFormItem 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 { isShowOther } from "@/utils/formPackageCommon.js";
import { EventBus } from "@/utils/eventBus";
import { getuuid } from "@/utils/index.js";
import moment from 'moment'
export default {
    inject: ['templateFillType','templateData'],
    components: {
        HandleFormItem,
    },
    mixins: [formPackageMixins],
    props: {
        formConfig: {
            type: Array,
            default: []
        },
        formData: {
            type: Object,
            value: () => ({})
        },
        //主要标识当前表单属于哪个模块，用于传给后端
        fieldItemLabel: {
            type: String,
            default: "",
        },
        prefixKey: {
            type: String,
            default: ""
        }
    },
    mounted() {
        EventBus.$on("onReagentSubmit",this.onReagentSubmit)
        EventBus.$on("onInstrumentSubmit",this.onInstrumentSubmit)
        EventBus.$on("onMixReagentSubmit",this.onMixReagentSubmit)
    },
    unmounted() {
        EventBus.$off("onReagentSubmit",this.onReagentSubmit)
        EventBus.$off("onInstrumentSubmit",this.onInstrumentSubmit)
        EventBus.$off("onMixReagentSubmit",this.onMixReagentSubmit)
    },
    data() {
        return {
            formFields: {},//表单绑定字段
            allFieldsConfig: {},//包含config的所有字段,主要用于校验表单是否填写
            errors: {},//存储表单错误信息，用于标红提示
            orangeBgFields: {},// 存储需要橙色背景的字段
            isShowOther,
            currentClickKey: "",//当前点击的字段key
            uuid:getuuid(),
        }
    },
    methods: {
        getSjResource(){
            const {allFieldsConfig,formFields} = this;
            const sjResource = [],yqResource = [];
            for(const key in allFieldsConfig){
                const item = allFieldsConfig[key];
                if(item.type === "xb" || item.type === "regent" || 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 === "instrument"){
                    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.formFields["startDate"] = moment().format('YYYY-MM-DD HH:mm:ss');
            }else if(buttonName === '结束' && config.hasOwnProperty("endDate")){
                this.formFields["endDate"] = moment().format('YYYY-MM-DD HH:mm:ss');
            }
            this.$emit("clickButton",e,item)
        },
        // 获取按钮项
        getButtonItem(sItem) {
            return {
                ...sItem,
                fillType:sItem.fillType || "actFill",
            }
        },
        // 处理选择试剂/供试品/给药制剂提交
        onMixReagentSubmit(data){
            if(data.uuid !== this.uuid) return;
            this.updateFormData(this.currentClickKey,data.selectedId)
            if(data.selectType){
                this.allFieldsConfig[this.currentClickKey].sjSelectType = data.selectType;
                this.formFields[`selectInfo_${this.currentClickKey}`] = data.selectInfo;
            }
            this.$emit("onDialogSubmit",data)
        },
        // 处理选择试剂提交
        onReagentSubmit(data){
            if(data.uuid !== this.uuid) return;
            this.updateFormData(this.currentClickKey,data.selectedId)
        },
        // 处理选择仪器提交,不确定后续还会不会有其他操作，所以和选择试剂提交区分开。
        onInstrumentSubmit(data){
            if(data.uuid !== this.uuid) return;
            this.updateFormData(this.currentClickKey,data.selectedId)
            // this.formFields[this.currentClickKey] = data.selectedId;
            this.formFields[`selectInfo_${this.currentClickKey}`] = data.selectInfo;
        },
        getClickableItem(sItem) {
            return {
                ...sItem,
                type:"clickable",
            
            }
        },
        handleClickInstrument(key,type) {
            this.currentClickKey = key;
            if(type === 'regent'){//试剂
                EventBus.$emit("showSelectMixReagentDialog",{
                    studyFormId:this.templateData.id,
                    uuid:this.uuid,
                    sourceFrom:'step',
                    type:"1"
                })  
            }else if(type === 'gyzj'){//给药制剂
                EventBus.$emit("showSelectMixReagentDialog",{
                    studyFormId:this.templateData.id,
                    uuid:this.uuid,
                    sourceFrom:'step',
                    type:"3"
                })  
            }else if(type === 'mjy'){//麻精药
                EventBus.$emit("showSelectMixReagentDialog",{
                    studyFormId:this.templateData.id,
                    uuid:this.uuid,
                    sourceFrom:'step',
                    type:"5"
                })  
            }else if(type === 'gsp'){//供试品
                EventBus.$emit("showSelectMixReagentDialog",{
                    studyFormId:this.templateData.id,
                    uuid:this.uuid,
                    sourceFrom:'step',
                    type:"7"
                })  
            }else if(type === 'mix'){
                EventBus.$emit("showSelectMixReagentDialog",{
                    studyFormId:this.templateData.id,
                    uuid:this.uuid,
                    sourceFrom:'step',
                    type:"1",
                    mixType:true,
                })  
            }else if(type === 'xj'){//细菌
                EventBus.$emit("showSelectMixReagentDialog",{
                    studyFormId:this.templateData.id,
                    uuid:this.uuid,
                    sourceFrom:'step',
                    type:"9",
                })  
            }else if(type === 'xb'){//细胞
                EventBus.$emit("showSelectMixReagentDialog",{
                    studyFormId:this.templateData.id,
                    uuid:this.uuid,
                    sourceFrom:'step',
                    type:"11",
                })  
            }else if(type === 'instrument'){
                EventBus.$emit("showSelectInstrumentDialog",{
                    studyFormId:this.templateData.id,
                    uuid:this.uuid,
                })  
            }
        },
    
   
    }
}
</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>