<!-- 状态单选框表单组件 zhao -->
<template>
  <div>
    <van-field
      :readonly="true"
      :clickable="!readonly"
      :name="name"
      :label="label"
      :placeholder="placeholder"
      input-align="right"
      :required="required"
      :label-width="labelWidth || 'auto'"
      @click="toggle"
    >
      <template #right-icon>
        <van-checkbox v-model="checked"
                      :disabled="readonly"
                      shape="square"
        ></van-checkbox>
      </template>
    </van-field>
  </div>
</template>

<script>

export default {
  name: "fieldCheckbox",
  props: [
    'name', 'readonly', 'value', 'label', 'placeholder', 'required', 'rules',
    'labelWidth',
    'trueLabel', // 选中的值
    'falseLabel', // 未选中的值
  ],
  watch: {
    value: function (newVal, oldVal) {
      this.parseValue(newVal);
    },
    checked: function (newVal, oldVal) {
      if(newVal !== undefined)
        this.onChanged(newVal);
    },
  },
  created() {
    this.parseValue(this.value);
  },
  data() {
    return {
      internalValue: this.value,
      remoteColumns: null,
      remoteResponse: null,
      checked: false,
    };
  },
  methods: {
    onChanged(data) {
      let trueLabel = this.getTrueLabel();
      let falseLabel = this.getFalseLabel();
      let res = data ? trueLabel : falseLabel;
      if(res != this.internalValue)
      {
        this.internalValue = res;
        this.$emit('change', this.internalValue);
        this.$emit("input", this.internalValue);
      }
    },
    getFalseLabel() {
      return this.falseLabel !== undefined ? this.falseLabel : false;
    },
    getTrueLabel() {
      return this.trueLabel !== undefined ? this.trueLabel : true;
    },
    parseValue(data) {
      let trueLabel = this.getTrueLabel();
      let falseLabel = this.getFalseLabel();
      let res = data == trueLabel;
      this.internalValue = res ? trueLabel : falseLabel;
      this.checked = res;
    },
    toggle() {
      console.log(123);
      if(!this.readonly)
        this.checked = !this.checked;
    },
  },
}
</script>

<style scoped>

</style>
