<template>
    <div>
        <van-field v-show="false" v-model="valueModel" :name="data.id"  :rules="[{validator: validator}]"></van-field>
        <van-field v-model="pickerModel" is-link readonly :label="data.name"   :placeholder="data.placeholder" @click="showPicker = true"  />
        <van-popup v-model="showPicker" round position="bottom">
            <van-picker :columns="columns"  @cancel="showPicker = false" :default-index="defaultIndex" item-height="88" @confirm="onConfirm" />
        </van-popup>
    </div>
</template>

<script>
import {
    ref,
    reactive
} from "vue"
export default {
    props: {
        data: {
            type: Object
        },
        validator:{
            type:Function
        }
    },
    setup(props,ctx) {
        const {
            answer,
            list,
            id
        } = reactive(props).data, columns = ref([]),
            showPicker = ref(false),valueModel = ref(0),
            pickerModel = ref(ctx.attrs.modelValue),defaultIndex = ref(ctx.attrs.modelValue);
        if (list) {
            let keys =  ctx.attrs.modelValue?ctx.attrs.modelValue.replace(/[^\d]/gi,",").split(","):[];
             if (id == "gestationWeek"&&ctx.attrs.modelValue) {
                 keys = [`${Math.floor(ctx.attrs.modelValue/7)}`, `${ctx.attrs.modelValue%7}`];
                 pickerModel.value = `${keys[0]}周${keys[1]}天`;
             }
            columns.value = list.map((a,index) => {
                let values = [];
                const {min = 0,max = 100,unit} = a;
                for (let i = min; i <= max; i++) {
                    values.push(i + unit);
                }
                return {
                    values,
                    defaultIndex:keys[index]?keys[index] - min:min
                }
            });
        } else {
            columns.value = answer.map((a,index) => {
                if(a.name == ctx.attrs.modelValue){
                    defaultIndex.value =index;
                }
                return a.name
            });
        }
        const onConfirm = (value) => {
            let _value = value instanceof Array?value.join(""):value;
            if (id == "gestationWeek") {
                valueModel.value = parseInt(value[0].replace("周", "")) * 7 + parseInt(value[1].replace("天", ""))*1;
            }else{
                valueModel.value = _value;
            }
            pickerModel.value = _value;
            showPicker.value = false;
        };
      
        return {
            pickerModel,
            columns,
            onConfirm,
            showPicker,
            defaultIndex,
            valueModel
        }
    }
}
</script>

<style lang="less" scoped>

</style>
