<template>
  <a-dropdown :trigger="['click']" v-model:open="visible" placement="bottom">
    <a-input v-model:value="value_">
    </a-input>
    <template #overlay>
      <a-menu>
        <a-card :tab-list="tabList" :active-tab-key="activeTabKey" @tabChange="onTabChange">
          <second @onChange="onChange" :unit="activeTabKey" :cron="cron"/>
        </a-card>
      </a-menu>
    </template>
  </a-dropdown>
</template>
<script>
  import {defineComponent, reactive, ref, toRefs, watch} from "vue";
  import second from "./second.vue";

  export default defineComponent({
    name: "cron",
    emits: ["onChange"],
    components: {
      second
    },
    setup(props, context) {
      //公共状态
      const state =
        reactive({
          //是否展开选择框
          visible: false,
          //默认选择秒
          activeTabKey: 's',
          //默认的cron表达式
          cron: {s: "*", m: "*", h: "*", d: "*", M: "*", w: "?", y: "*"}
        });

      const value_ = ref("* * * * * ? *");

      const tabList = [{
        key: 's',
        tab: '秒'
      }, {
        key: 'm',
        tab: '分'
      }, {
        key: 'h',
        tab: '时'
      }, {
        key: 'd',
        tab: '日'
      }, {
        key: 'M',
        tab: '月'
      }, {
        key: 'w',
        tab: '周'
      }, {
        key: 'y',
        tab: '年'
      }];

      const onTabChange = (key) => {
        state.activeTabKey = key
      };

      const onChange = (val) => {
        state.cron[state.activeTabKey] = val;
      };

      watch(() => state.cron, (cron) => {
        value_.value = Object.values(cron).join(" ");
      }, {deep: true});

      watch(value_, (val) => {
        context.emit("onChange", val)
      });

      return {...toRefs(state), value_, tabList, onTabChange, onChange}
    }
  })
</script>
