<script lang="ts" setup>
import {reactive, ref, watch} from 'vue'
import {Card, Divider, Steps} from 'ant-design-vue'
import ModalTable from '../model/ModelTable.vue'
import PointTable from '../model/PointTable.vue'
import {createInstantForm} from './instant.data'
import {useI18n} from '@/hooks/web/useI18n'
import {BasicModal, useModalInner} from '@/components/Modal'
import {BasicForm, useForm} from '@/components/Form'
import {getModelVersionList} from '@/api/alert/run/model/index'
import {getCalcGroupList} from '@/api/alert/run/calcgroup/index'
import {createInstant, InstantVO} from '@/api/alert/run/instant/index'
import {useMessage} from '@/hooks/web/useMessage'

const emit = defineEmits(['success'])

const props = defineProps({
  isDisabled: {
    type: Boolean,
    default: true,
  }
})
const current = ref<number>(0)
const {createMessage} = useMessage()
const {t} = useI18n()
const state = reactive<any>({
  selectedRowKeys: [],
  selectedData: [],
  pointInfo: [],
  type: false,
})

const [registerCreateModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
  resetFields()
  current.value=0;
  state.selectedRowKeys=[];
  state.selectedData=[];
  setModalProps({destroyOnClose: true, showCancelBtn: false, showOkBtn: false})
})



function next() {
  current.value++
}

function prev() {
  current.value--
  if (current.value == 0) {
    console.log(state.selectedRowKeys)
    console.log(state.selectedData)
  }
}

const steps = [
  {
    title: '壹',
    content: 'First-content',
  },
  {
    title: '贰',
    content: 'Second-content',
  },
]
const items = steps.map(item => ({key: item.title, title: item.title}))

const [registerForm, {validate, resetFields, setFieldsValue, updateSchema, setProps}] = useForm({
  labelWidth: 100,
  schemas: createInstantForm,
  showSubmitButton: false,
  showResetButton: false,
  layout: 'horizontal',

  actionColOptions: {span: 2},
  disabled: true,
})

interface instantForms {
  modelId?: string
  mpName?: string
}

const instantForm = reactive<instantForms>({
  modelId: '',
  mpName: '',

})
// 本地isDisabled变量
const isDisabled = ref<boolean>(true)

// 监听父组件传递的isDisabled属性变化
watch(() => props.isDisabled, (newVal) => {
  if (newVal !== undefined) {
    isDisabled.value = newVal
  }
}, {immediate: true}) // immediate设置为true，确保组件初始化时也会执行一次


async function updatempName(selectedRowKeys, selectedRows) {
  console.log(selectedRowKeys)
  console.log(selectedRows)
  console.log(instantForm)
  resetFields()
  state.selectedRowKeys = selectedRowKeys;
  state.selectedData = selectedRows;
  //读出模型中的点号信息
  if (selectedRows.length !== 0) {
    state.type = selectedRows[0].algorithm === 'ANN'
    console.log(state.type)
    state.pointInfo = JSON.parse(selectedRows[0].modelInfo).pointInfo
    for (const p of state.pointInfo) {
      p.modelName = selectedRows[0].modelName
      p.modelDescription = selectedRows[0].description
      p.algorithm = selectedRows[0].algorithm
    }
  }

  // 下一步按钮的禁用与启用
  isDisabled.value = selectedRows.length === 0
  if (selectedRows.length === 0)
    setProps({disabled: true})

  else
    setProps({disabled: false})

  instantForm.modelId = selectedRows.length !== 0 ? `${selectedRows[0].modelId}` : ``

  instantForm.mpName = selectedRows.length !== 0 ? `${selectedRows[0].modelName}-实例` : ``
  setFieldsValue(instantForm)

  const versionData = selectedRows.length !== 0 ? await getModelVersionList({modelId: selectedRows[0].modelId}) : []
  const versionList = [] as any
  // // 组名下拉框问题
  versionData.forEach((item) => {
    versionList.push({label: `${item.version} (${item.conditionName})`, value: item.versionId})
  })
  const calcGroupData = selectedRows.length !== 0 ? await getCalcGroupList({unitId: selectedRows[0].unitId}) : []
  const calcGroupList = [] as any
  // // 组名下拉框问题
  calcGroupData.forEach((item) => {
    console.log(item)
    calcGroupList.push({label: item.groupName, value: item.groupId})
  })

  // 将数据放入下拉框中
  updateSchema({
    field: 'modelVersionId',
    componentProps: {
      options: versionList,
    },
  })
  updateSchema({
    field: 'calcGroup',
    componentProps: {
      options: calcGroupList,
    },
  })
}

function onCanel() {
  current.value = 0
  closeModal()
}

const loading = ref<boolean>(false)
const pointRef = ref()

async function CompleteCreate() {
  try {
    loading.value = true

    // 由于自定义按钮的，所以confirmLoading失效
    setModalProps({confirmLoading: true, loading: true})

    const values  = await validate()
    console.log(values)
    // if (unref(isUpdate)) {
    //   await updateDemo02Category(values)
    // } else {
    //   await createDemo02Category(values)
    // }
    // 插入数据库
    // 获取子组件的测点列表数据
    const pointInfoNew = pointRef.value.getPointTableData()
    values.pointInfo = pointInfoNew
    console.log(values)
    await createInstant(values)

    emit('success')
    createMessage.success(t('common.saveSuccessText'))
  } finally {
    closeModal()
    loading.value = false

    // 由于自定义按钮的，所以confirmLoading失效
    setModalProps({confirmLoading: false, loading: false})
  }
}
</script>

<template>
  <BasicModal v-bind="$attrs" title="新增模型实例" width="60%" height="500px"  @cancel="onCanel"
              @register="registerCreateModal">
    <Card title="实例信息">
      <BasicForm @register="registerForm" ref="instantFormRef"/>
    </Card>
    <Divider/>

    <Steps :current="current" :items="items"/>
    <div class="steps-content">
      <ModalTable v-if="current === 0" :selectedRowKeys="state.selectedRowKeys"
                  :selected-data="state.selectedData" @success="updatempName"/>
      <PointTable v-if="current === 1" ref="pointRef" :data="state.pointInfo" :type="state.type"/>
    </div>
    <!-- modal 底部区域插槽实现--替换原按钮 -->
    <template #footer>
      <div class="steps-action">
        <a-button v-if="current < steps.length - 1 " :disabled="isDisabled" type="primary"
                  @click="next">
          下一步
        </a-button>
        <a-button
          v-if="current === steps.length - 1"
          type="primary"
          :loading="loading"
          @click="CompleteCreate"
        >
          完成
        </a-button>
        <a-button v-if="current > 0" style="margin-left: 8px" @click="prev">
          上一步
        </a-button>
      </div>
    </template>
  </BasicModal>
</template>

<style scoped>
.steps-content {
  margin-top: 16px;
  text-align: center;
  background-color: #fafafa;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
}

.steps-action {
  margin-top: 24px;
}

[data-theme='dark'] .steps-content {
  background-color: #2f2f2f;
  border: 1px dashed #404040;
}
</style>
