import { defineComponent, reactive, watch } from 'vue';
import styles from '../operation.module.less';
import { Button, Field, showToast } from 'vant';
import { verifiyNumberInteger } from '@/helpers/toolsValidate';
import { formatterTimer } from '../operation';

export default defineComponent({
  name: 'input-timer',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    time: {
      type: Number,
      default: null
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    const timer = formatterTimer(props.time);
    console.log(timer, 'timer');
    const forms = reactive({
      minute: timer.minute,
      second: timer.secord || null
    });

    // 过滤输入的数字
    const formatter = (value: any) => {
      if (value && value >= 0) {
        return verifiyNumberInteger(value);
      } else {
        return '';
      }
    };

    // 过滤输入的数字 最大60秒
    const formatter2 = (value: any) => {
      if (value && value >= 0) {
        const num = verifiyNumberInteger(value);
        return (Number(num) >= 60 ? 59 : num) + '';
      } else {
        return '';
      }
    };

    watch(
      () => props.show,
      () => {
        if (!props.show) {
          const timer = formatterTimer(props.time);
          forms.minute = timer.minute;
          forms.second = timer.secord;
        }
      }
    );

    watch(
      () => props.time,
      () => {
        const timer = formatterTimer(props.time);
        forms.minute = timer.minute;
        forms.second = timer.secord;
      }
    );
    return () => (
      <div class={styles.popupContainer}>
        <h2 class={styles.popupTitle}>请输入节目时长</h2>
        <div class={styles.popupContent}>
          <div class={styles.popupTimer}>
            <Field
              v-model={forms.minute}
              type="tel"
              formatter={formatter}
              border={false}
              maxlength={2}
              autocomplete="off"
            />
            分
            <Field
              v-model={forms.second}
              type="tel"
              formatter={formatter2}
              border={false}
              maxlength={2}
              autocomplete="off"
            />
            秒
          </div>
        </div>

        <div class={['btnGroupPopup']}>
          <Button round onClick={() => emit('close')}>
            取消
          </Button>
          <Button
            type="primary"
            round
            onClick={() => {
              if (!forms.minute || !forms.second) {
                showToast('时长输入有误');
                return;
              }
              const allTime = forms.minute * 60 + forms.second;
              if (allTime <= 0) {
                showToast('时长输入必须大于0');
                return;
              }
              emit('confirm', forms);
            }}>
            确定
          </Button>
        </div>
      </div>
    );
  }
});
