<template>
  <EdfsDialog
    @on-close="onClone"
    @on-save="onSave"
    title="新建升级任务"
    :is-show="isShow"
    width="44%"
    class="create-task-dlg"
  >
    <div class="dlg-body">
      <el-row>
        <FormItemInput label="任务名称" v-model="formData.name" require />
      </el-row>
      <el-row>
        <span class="label">固件选择：</span>
        <el-cascader
          :props="cascaderFirmware"
          v-model="firmwareSelect"
          ref="firmwareCascaderRef"
          :show-all-levels="false"
          placeholder="请选择"
        />
      </el-row>
      <el-row v-if="isShowDeviceSelect">
        <!-- <span class="label">设备选择</span>
        <el-cascader
          style="flex: 1"
          v-model="deviceSelect"
          :props="cascaderDevice"
          @change="devChange"
          ref="deviceCascaderRef"
          :show-all-levels="false"
          popper-class="task-device-select-cascader"
          placeholder="请选择"
          collapse-tags
          :max-collapse-tags="4"
          collapse-tags-tooltip
          @expand-change="changeSourceType"
        /> -->
      </el-row>
      <el-row>
        <span class="label">是否立即执行</span>
        <el-switch
          v-model="formData.executeNow"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        />
      </el-row>
      <el-row v-if="!formData.executeNow">
        <span class="label">任务执行时间</span>
        <el-date-picker
          v-model="formData.executeTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm"
          format="YYYY-MM-DD HH:mm"
          placeholder="Pick a day"
          :disabled-date="disabledExecuteDate"
        />
      </el-row>
      <el-row>
        <EdfsNumberInput labelName="监控超时" v-model="formData.monitorTimeout" require />
      </el-row>
      <el-row>
        <EdfsNumberInput labelName="重试次数" v-model="formData.retryCount" require />
      </el-row>
      <el-row>
        <EdfsNumberInput labelName="重试间隔" v-model="formData.retryInterval" require />
      </el-row>
    </div>
  </EdfsDialog>
</template>

<script setup lang="ts">
import EdfsDialog from '@/components/dashboard/Edfs-dialog.vue'
import FormItemInput from '@/components/dashboard/FormItemInput.vue'
import { isResError, useMessage } from '@/hooks/useMessage'
import EdfsNumberInput from '@/components/dashboard/Edfs-number-item-input.vue'
import FormItemSelect from '@/components/dashboard/FormItemSelect.vue'
import type { CascaderProps, CascaderValue, ElCascader } from 'element-plus'
// import { getSimpleStationList } from '@/api/module/app/station'
// import { getSimpleDeviceList } from '@/api/module/app/device'
import { getIntDictOptions } from '@/utils/dict'
import { getSimpleFirmwareList } from '@/api/module/eam/device/firmware'
import { isEmpty } from '@/utils/is'
import { clone, cloneDeep } from 'lodash'
import { createTask } from '@/api/module/eam/device/task'

const message = useMessage()
interface Props {
  isShow: boolean
}

const emits = defineEmits(['on-save', 'on-close'])
const props = withDefaults(defineProps<Props>(), {
  isShow: false,
})

const firmwareSelect = ref<CascaderValue>([])
const firmwareCascaderRef = ref<InstanceType<typeof ElCascader>>()
const cascaderFirmware: CascaderProps = {
  lazy: true,
  async lazyLoad(node, resolve) {
    const { level } = node

    if (level === 0) {
      const deviceTypes = getIntDictOptions('device_entity_type').map(item => ({
        value: item.value,
        label: item.label,
        isLeaf: false,
      }))
      resolve(deviceTypes)
    }
    if (level === 1) {
      const res = await getSimpleFirmwareList({
        type: node.data?.value as number,
      })
      const data = Array.isArray(res?.data) ? res.data : []
      const firmware = data.map((item: any) => ({
        value: item.id,
        label: item.name,
        isLeaf: true,
        leaf: true,
      }))
      resolve(firmware)
    }
  },
}

const selectFirmwareType = ref()
watch(firmwareSelect, (value: any) => {
  selectFirmwareType.value = value[0] ?? ''
  formData.value.firmwareId = String(value[1]) ?? ''
})

const isShowDeviceSelect = ref(false)
watch(
  () => selectFirmwareType.value,
  () => {
    isShowDeviceSelect.value = false
    nextTick(() => {
      isShowDeviceSelect.value =
        !isEmpty(selectFirmwareType.value) &&
        typeof selectFirmwareType.value !== 'undefined'
    })
  }
)

// const deviceCascaderRef = ref<InstanceType<typeof ElCascader>>()
// const cascaderDevice: CascaderProps = {
//   lazy: true,
//   multiple: true,
//   async lazyLoad(node, resolve) {
//     const { level } = node
//     if (level === 0) {
//       const res = await getSimpleStationList()
//       if (isResError(res)) return
//       const data = Array.isArray(res?.data) ? res.data : []
//       const nodes = data.map((item: any) => ({
//         value: item.id,
//         label: item.name,
//         isLeaf: false,
//       }))
//       resolve(nodes)
//     }
//     if (level === 1) {
//       const res = await getSimpleDeviceList({
//         siteId: node.data?.value as number,
//         type: selectFirmwareType.value,
//       })
      
//       const data = Array.isArray(res?.data) ? res.data : []
//       const devices = data.map((item: any) => ({
//         value: item.sn,
//         label: item.name,
//         isLeaf: true,
//         leaf: true,
//       }))
//       resolve(devices)
//     }
//   },
// }

const deviceSelect = ref<CascaderValue>([])
watch(deviceSelect, (value: any) => {
  formData.value.deviceSns = value.map((item: any) => item[1])
})

function devChange() {}

const cascaderTag = ref<any[]>([])
function changeSourceType(selectItem: any) {
  if (!cascaderTag.value.includes(selectItem[0])) {
    deviceSelect.value = []
  }
  cascaderTag.value = selectItem
}

const form = {
  name: '',
  executeNow: false, // 立即执行
  executeTime: '', // 执行时间
  retryCount: 3, // 重试次数
  retryInterval: 1000, // 重试间隔
  monitorTimeout: 1000, // 监控超时
  firmwareId: '', // 固件ID
  deviceSns: [], // 设备SN
}
const formData = ref(cloneDeep(form))

function validate() {
  if (!formData.value.name) {
    message.error('请输入任务名称')
    return true
  }
  if (!formData.value.firmwareId) {
    message.error('请选择固件')
    return true
  }
  if (!formData.value.deviceSns.length) {
    message.error('请选择设备')
    return true
  }
  if (!formData.value.executeNow && !formData.value.executeTime) {
    message.error('请选择执行时间')
    return true
  }
  if (!formData.value.monitorTimeout) {
    message.error('请输入监控超时')
    return true
  }
  if (!formData.value.retryCount) {
    message.error('请输入重试次数')
    return true
  }
  if (!formData.value.retryInterval) {
    message.error('请输入重试间隔')
    return true
  }
  return false
}

function disabledExecuteDate(time: Date) {
  return time.getTime() < Date.now() - 8.64e7
}
async function onSave() {
  if (validate()) return
  const res = await createTask(formData.value)
  if (isResError(res)) return
  emits('on-save')
  clearData()
}
function onClone() {
  clearData()
  emits('on-close')
}

function clearData() {
  formData.value = cloneDeep(form)
  firmwareSelect.value = []
  cascaderTag.value = []
  deviceSelect.value = []
}
</script>

<style lang="scss">
.task-device-select-cascader {
  .el-cascader-panel {
    .el-cascader-menu:first-child {
      .el-cascader-node {
        .el-checkbox {
          display: none !important;
        }
      }
    }
  }
}
</style>

<style scoped lang="scss">
.create-task-dlg {
  .dlg-body {
    max-height: 400px;
  }
  .el-row {
    height: 32px;
    width: 74%;
    margin-bottom: 20px;
    :deep(.label) {
      margin-right: 10px;
    }
    span {
      width: 110px;
      height: 32px;
      line-height: 32px;
      text-align: right;
    }
    :deep(.el-radio-group) {
      height: 100%;
    }
    :deep(.el-radio) {
      height: 100%;
    }
  }
  .require {
    color: red;
    margin-right: 4px;
  }
}
</style>
