<!--
  Jeepay 通用状态切换按钮，  支持switch和badge两个格式， 根据权限进行判断

  @author terrfly
  @site https://www.jeepay.vip
  @date 2021/5/8 07:18
-->
<template>
  <div>
    <template v-if="!showSwitchType">
      <div v-if="state == 0">
        <a-badge status="error" :text="props.badgeTextArray[1]" />
      </div>
      <div v-else-if="state == 1">
        <a-badge status="processing" :text="props.badgeTextArray[0]" />
      </div>
      <div v-else>
        <a-badge status="warning" :text="props.badgeTextArray[2]" />
      </div>
    </template>

    <template v-if="showSwitchType">
      <!-- 启用停用文字去掉 -->
      <a-switch checked-children="" un-checked-children="" :checked="data.switchChecked" @change="onChangeInner" />
    </template>
  </div>
</template>

<script lang="ts" setup>
import {reactive,watch,onMounted,nextTick} from 'vue'

  // 传递数据参数 ( 父-->子 参数 )
 const  props =defineProps ({
    state: { type: Number, default: -1 }, // 初始化列表数据， 默认true
    showSwitchType: { type: Boolean, default: false }, // 默认 badge
    onChange: { type: Function, default: (checked) => { return new Promise<void>(resolve => { resolve( ) }) } }, // change回调事件
    badgeTextArray: { type: Array, default: () => ['启用','停用','未知'] } // 显示文字数组 
  })

      const data = reactive({
          switchChecked : false
      })


    // 监听 props属性
    watch(() => props.state, function(o, n){
          data.switchChecked = props.state === 1
        }
    )


  onMounted(()=>{
    data.switchChecked = props.state === 1
  })


  function  onChangeInner(checked) {

      data.switchChecked = checked

      // 回调输出 0 和 1; 成功不需要处理， 失败需要经状态变更为原始状态
      props.onChange((checked ? 1 : 0)).then().catch(res => {
       nextTick(() => { data.switchChecked = !checked })
      })
    }
</script>
<style lang="less">
.ant-table-row-level-1{
  background:#c3c3c3 !important ;
}
.ant-table-row-level-2{
  background:#e3e3f3 !important ;
}
</style>
