<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" :form-view="isViewCpt" layout="y">
        <CzrFormColumn
          required
          :span="24"
          label="应用名称"
          v-model:param="state.form.name"
        />
        <CzrFormColumn
          required
          :span="24"
          v-model:param="state.form.type"
          link="radio"
          :options="DictionaryStore.appTypes"
          :disabled="transfer.mode !== 'add'"
        >
          <template #label>
            应用类型
            <el-tooltip
              content="简介：选择模型即可使用<br/>高级：需配置应用工作流才可使用"
              :raw-content="true"
              placement="top"
            >
              <SvgIcon name="czr_tip" size="14" class="ml-2" />
            </el-tooltip>
          </template>
        </CzrFormColumn>
        <CzrFormColumn
          :span="24"
          label="应用介绍"
          v-model:param="state.form.description"
          type="textarea"
          :rows="4"
        />
        <CzrFormColumn
          required
          :span="24"
          label="图标"
          v-model:param="state.icon"
          link="upload"
          type="img"
          uploadLayout="card"
          :limit="1"
          :delRule="(file) => true"
        />
        <template v-if="state.form.status == 1">
          <CzrFormColumn
            :span="24"
            label="公开访问URL"
            v-model:param="state.form.url1"
            :readonly="true"
          >
            <template #label>
              公开访问URL
              <div class="ml-auto" @click.capture.stop="onSwitchUrl">
                <a-switch v-model:checked="state.form.enabled1" size="small" />
              </div>
            </template>
            <template #suffix>
              <CopyDocument
                class="w-4 cursor-pointer"
                @click="onCopy(state.form.url1)"
              />
            </template>
          </CzrFormColumn>
          <CzrFormColumn
            :span="24"
            label="后端访问API"
            v-model:param="state.form.url2"
            :readonly="true"
          >
            <template #label>
              公开访问URL
              <div class="ml-auto" @click.capture.stop="onSwitchApi">
                <a-switch v-model:checked="state.form.enabled2" size="small" />
              </div>
            </template>
            <template #suffix>
              <CopyDocument
                class="w-4 cursor-pointer"
                @click="onCopy(state.form.url2)"
              />
            </template>
          </CzrFormColumn>
          <div class="__czr-title_1 mb-2">
            API密钥
            <CzrButton title="新增" type="add" class="ml-auto" @click="onAdd" />
          </div>
          <div class="max-h-[300px] w-full">
            <CzrTable
              v-loading="state.query.loading"
              :data="state.query.result.data"
              :head="state.query.head"
              :no-foot="true"
              :full="true"
            >
              <template #caozuo-column-value="{ scope }">
                <div class="__czr-table-operations">
                  <CzrButton
                    type="table"
                    title="复制"
                    @click="onCopy(scope.row.key)"
                  />
                  <CzrButton
                    type="table"
                    title="编辑"
                    @click="onEdit(scope.row)"
                  />
                  <CzrButton type="table-del" @click="onDel(scope.row)" />
                </div>
              </template>
            </CzrTable>
          </div>
        </template>
      </CzrForm>
    </div>
    <apiKey
      v-model:show="state.apiKey.show"
      :transfer="state.apiKey.transfer"
      @refresh="onApi"
    />
  </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 { CopyDocument } from '@element-plus/icons-vue'
import { copy } from '@/utils/czr-util'
import apiKey from './api-key.vue'
import { appAdd, appCopy, appDetail, appEdit } from '@/api/modules/app'

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: {},
  icon: [],
  query: {
    loading: false,
    head: [
      { value: 'p1', label: '密钥', show: true },
      {
        value: 'createTime',
        label: '创建时间',
        show: true,
        width: 180,
        datetime: true,
      },
      {
        value: 'updateTime',
        label: '最后使用',
        show: true,
        width: 180,
      },
      {
        value: 'p1',
        label: '备注',
        show: true,
      },
      {
        value: 'caozuo',
        label: '操作',
        show: true,
        width: 200,
        fixed: 'right',
        popover: false,
      },
    ],
    result: {
      data: [],
    },
  },
  apiKey: {
    show: false,
    transfer: {},
  },
})
const ref_form = ref()
const titleCpt = computed(() => {
  let t = '应用'
  switch (props.transfer.mode) {
    case 'add':
      t = '新增' + t
      break
    case 'copy':
      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 = {}
      state.icon = []
      if (props.transfer.mode !== 'add') {
        initData()
      }
      onApi()
      nextTick(() => {
        ref_form.value.reset()
      })
    }
  },
)
const initData = () => {
  state.loading = true
  appDetail(props.transfer.id)
    .then(({ data }: any) => {
      if (data.icon) {
        state.icon = [{ url: data.icon, name: data.icon }]
      }
      if (props.transfer.mode === 'copy') {
        state.form = {
          name: data.name,
          type: data.type,
          description: data.description,
        }
      } else {
        state.form = data
      }
    })
    .catch(() => {})
    .finally(() => {
      state.loading = false
    })
}
const onSubmit = () => {
  ref_form.value
    .submit()
    .then(() => {
      DialogStore.confirm({
        content: `请确认是否提交？`,
        onSubmit: () => {
          state.loading = true
          state.form.icon = state.icon[0].url
          if (props.transfer.mode === 'add') {
            appAdd(state.form)
              .then(() => {
                ElMessage.success(`${titleCpt.value}成功！`)
                emit('update:show', false)
                emit('refresh')
              })
              .catch(() => {})
              .finally(() => {
                state.loading = false
              })
          } else if (props.transfer.mode === 'edit') {
            appEdit(state.form)
              .then(() => {
                ElMessage.success(`${titleCpt.value}成功！`)
                emit('update:show', false)
                emit('refresh')
              })
              .catch(() => {})
              .finally(() => {
                state.loading = false
              })
          } else if (props.transfer.mode === 'copy') {
            appCopy(props.transfer.id, state.form)
              .then(() => {
                ElMessage.success(`${titleCpt.value}成功！`)
                emit('update:show', false)
                emit('refresh')
              })
              .catch(() => {})
              .finally(() => {
                state.loading = false
              })
          }
        },
      })
    })
    .catch((e) => {
      ElMessage({
        message: e[0].message,
        grouping: true,
        type: 'warning',
      })
    })
}
const onCopy = (str) => {
  copy(str)
  ElMessage.success('复制成功！')
}
const onSwitchUrl = () => {
  if (state.form.enabled1) {
    DialogStore.confirm({
      title: '停用确认',
      content: `请确认是否停用公开访问URL？`,
      onSubmit: () => {
        ElMessage.success('停用成功！')
      },
      onCancel: () => {},
    })
  } else {
    ElMessage.success('启用成功！')
  }
}
const onSwitchApi = () => {
  if (state.form.enabled2) {
    DialogStore.confirm({
      title: '停用确认',
      content: `请确认是否停用后端访问API？`,
      onSubmit: () => {
        ElMessage.success('停用成功！')
      },
      onCancel: () => {},
    })
  } else {
    ElMessage.success('启用成功！')
  }
}
const onAdd = () => {
  state.apiKey.transfer = {
    mode: 'add',
  }
  state.apiKey.show = true
}
const onEdit = (row) => {
  state.apiKey.transfer = {
    mode: 'edit',
    id: row.id,
  }
  state.apiKey.show = true
}
const onDel = (row) => {
  DialogStore.confirm({
    title: '删除确认',
    content: `请确认是否删除密钥？`,
    onSubmit: () => {
      ElMessage.success('删除成功！')
    },
    onCancel: () => {},
  })
}
const onApi = () => {
  state.query.result.data = [{}, {}, {}]
}
const initDictionary = () => {}
</script>

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