<template>
  <CzrDialog
    :show="show"
    :title="titleCpt"
    @onClose="$emit('update:show', false)"
    @onSubmit="onSubmit"
    width="62.5rem"
    height="auto"
    max-height="90%"
    :loading="state.loading"
  >
    <div class="bm-form">
      <CzrForm ref="ref_form" label-width="100px" :form-view="isViewCpt">
        <div class="__czr-title_1">基本信息</div>
        <CzrFormColumn
          required
          :span="12"
          label="模型类型"
          v-model:param="state.form.type"
          link="select"
          :options="DictionaryStore.modelTypes.list"
          @change="state.form.pluginClass = ''"
        />
        <template v-if="state.form.type">
          <CzrFormColumn
            required
            :span="12"
            label="模型供应商"
            v-model:param="state.form.pluginClass"
            link="select"
            :options="
              DictionaryStore.modelProvides.list.filter(
                (v) => v.type === state.form.type,
              )
            "
            @getObject="getModelProvide"
          />
        </template>
        <template v-if="state.form.pluginClass">
          <CzrFormColumn
            required
            :span="24"
            label="模型名称"
            v-model:param="state.form.name"
          />
          <CzrFormColumn
            :span="24"
            label="模型简介"
            v-model:param="state.form.description"
            type="textarea"
            :rows="4"
          />
        </template>
        <CzrFormColumn
          required
          :span="24"
          label="共享条件"
          v-model:param="state.form.openStrategy"
          link="radio"
          :options="DictionaryStore.shareConditions"
        />
        <template v-if="state.form.pluginClass">
          <template v-if="state.baseForms?.length > 0">
            <div class="__czr-title_1">基本参数配置</div>
            <template v-for="item in state.baseForms">
              <modelFormInit :config="item" :form="state.form.basicConfigs" />
            </template>
          </template>
          <template v-if="state.paramForms?.length > 0">
            <div class="__czr-title_1">模型参数配置</div>
            <template v-for="item in state.paramForms">
              <modelFormInit :config="item" :form="state.form.paramConfigs" />
            </template>
          </template>
          <template v-if="state.bizForms?.length > 0">
            <div class="__czr-title_1">业务参数配置</div>
            <template v-for="item in state.bizForms">
              <modelFormInit :config="item" :form="state.form.bizConfigs" />
            </template>
          </template>
        </template>
      </CzrForm>
    </div>
  </CzrDialog>
</template>

<script setup lang="ts">
import {
  computed,
  getCurrentInstance,
  nextTick,
  reactive,
  ref,
  watch,
} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAppStore, useDialogStore, useDictionaryStore } from '@/stores'
import { useRouter } from 'vue-router'
import modelFormInit from './model-form-init.vue'
import {
  pluginAddInstance,
  pluginDetail,
  pluginUpdateInstance,
} from '@/api/modules/model'

const router = useRouter()
const AppStore = useAppStore()
const DictionaryStore = useDictionaryStore()
const DialogStore = useDialogStore()
const emit = defineEmits(['update:show', 'refresh'])
const { proxy } = getCurrentInstance()
const props = defineProps({
  show: { default: false },
  transfer: <any>{},
})
const state: any = reactive({
  loading: false,
  form: {
    basicConfigs: {},
    paramConfigs: {},
    bizConfigs: {},
  },
  baseForms: [],
  paramForms: [],
  bizForms: [],
})
const ref_form = ref()
const titleCpt = computed(() => {
  let t = '模型'
  switch (props.transfer.mode) {
    case 'add':
      t = '创建' + t
      break
    case 'edit':
      t = '编辑' + t
      break
    case 'view':
      t = '查看' + t
      break
  }
  return t
})
const isViewCpt = computed(() => props.transfer?.mode === 'view')
watch(
  () => props.show,
  (n) => {
    if (n) {
      initDictionary()
      state.form = {
        tenantId: AppStore.tenantInfo?.id,
        basicConfigs: {},
        paramConfigs: {},
        bizConfigs: {},
      }
      state.baseForms = []
      state.paramForms = []
      state.bizForms = []
      if (props.transfer.mode !== 'add') {
        initData()
      }
      nextTick(() => {
        ref_form.value.reset()
      })
    }
  },
)
const initDictionary = () => {
  DictionaryStore.initModelProvides()
}
const initData = () => {
  state.loading = true
  pluginDetail(props.transfer.id)
    .then(({ data }: any) => {
      state.form = data
    })
    .catch(({ message }: any) => {
      ElMessage.error(message)
    })
    .finally(() => {
      state.loading = false
    })
}
const onSubmit = () => {
  ref_form.value
    .submit()
    .then(() => {
      DialogStore.confirm({
        content: `请确认是否提交？`,
        onSubmit: () => {
          state.loading = true
          if (props.transfer.mode === 'add') {
            pluginAddInstance(state.form)
              .then(() => {
                ElMessage.success(`${titleCpt.value}成功！`)
                emit('update:show', false)
                emit('refresh')
              })
              .catch(({ message }: any) => {
                ElMessage.error(message)
              })
              .finally(() => {
                state.loading = false
              })
          } else {
            pluginUpdateInstance(state.form)
              .then(() => {
                ElMessage.success(`${titleCpt.value}成功！`)
                emit('update:show', false)
                emit('refresh')
              })
              .catch(({ message }: any) => {
                ElMessage.error(message)
              })
              .finally(() => {
                state.loading = false
              })
          }
        },
      })
    })
    .catch((e) => {
      ElMessage({
        message: e[0].message,
        grouping: true,
        type: 'warning',
      })
    })
}
const getModelProvide = (obj) => {
  console.log(obj)
  state.form.name = obj.name
  state.form.description = obj.description
  state.baseForms = obj.basicConfigAttr
    ? Object.values(obj.basicConfigAttr)
    : []
  state.paramForms = obj.paramConfigAttr
    ? Object.values(obj.paramConfigAttr)
    : []
  state.bizForms = obj.bizConfigAttr ? Object.values(obj.bizConfigAttr) : []
}
</script>

<style lang="scss" scoped></style>
