<template>
  <div class="bm-main-box">
    <div class="flex items-center">
      <div class="bm-main-box-title">{{ $route.meta.title }}</div>
      <div class="ml-auto flex items-center gap-[var(--czr-gap)]">
        <CzrForm class="bm-filter" label-width="0px" @handleEnter="onSearch">
          <CzrFormColumn
            width="6.68rem"
            class="__czr-table-form-column"
            :span="24"
            label-width="0px"
            v-model:param="state.query.form.modeType"
            link="select"
            :options="DictionaryStore.modelTypes.list"
            placeholder="模型类型"
          />
          <CzrFormColumn
            width="6.68rem"
            class="__czr-table-form-column"
            :span="24"
            label-width="0px"
            v-model:param="state.query.form.status"
            link="select"
            :options="[
              { label: '停用', value: 0 },
              { label: '启用', value: 1 },
            ]"
            placeholder="模型状态"
          />
          <CzrFormColumn
            width="15.63rem"
            class="__czr-table-form-column"
            :span="24"
            label-width="0px"
            v-model:param="state.text"
            placeholder="输入关键词以检索"
            :prefix-icon="Search"
          />
          <CzrButton type="add" @click="onAdd" />
        </CzrForm>
      </div>
    </div>
    <div
      class="mt-[1rem] flex-1 overflow-hidden"
      v-loading="state.query.loading"
    >
      <CzrTableCard
        class="table-card"
        :page="state.query.page.pageNum"
        :pageSize="state.query.page.pageSize"
        :total="state.query.result.total"
        :data="state.query.result.data"
        @handlePage="onPage"
        :col="2"
      >
        <template #model="{ row, index }">
          <div
            class="model __hover"
            @click="
              $router.push({
                name: 'd91af45a-7258-4b1e-8e0b-178e8b66d847',
                params: {
                  id: row.id,
                },
              })
            "
          >
            <div class="flex">
              <img
                src="@/assets/images/model-default-logo.png"
                class="mr-[var(--czr-gap)] h-[3.25rem] w-[3.25rem]"
              />
              <div class="flex flex-1 flex-col justify-around overflow-hidden">
                <div class="text-[1.25rem] font-bold text-[#2E3238]" v-title>
                  {{ row.name }}
                </div>
                <div class="flex">
                  <div
                    class="flex h-[1.25rem] items-center justify-center rounded-[0.13rem] bg-gradient-to-r from-[#FF9E2D] to-[#FFB92D] px-[0.38rem] text-[0.63rem] font-bold text-[#ffffff]"
                  >
                    {{ DictionaryStore.modelTypes.map.get(row.type) }}
                  </div>
                </div>
              </div>
              <div class="mt-[0.25rem] ml-auto">
                <div
                  v-if="row.status == 1"
                  class="flex h-[1.56rem] w-[3.75rem] items-center justify-center rounded-[1.25rem] bg-gradient-to-r from-[#D5F9FE] to-[#E0DAFF] text-[0.75rem] font-bold text-[#1E3F92]"
                >
                  已启用
                </div>
              </div>
            </div>
            <div
              class="mt-[var(--czr-gap)] mb-auto h-[3rem] text-[0.88rem] text-[#606266]"
              style="line-height: 1.4rem"
              v-title="{ lines: 2 }"
            >
              {{ row.description }}
            </div>
            <div
              class="mt-[0.5rem] flex items-center gap-[var(--czr-gap)] text-[0.75rem] text-[#6F7889]"
            >
              <div>
                {{ DictionaryStore.modelProvides.map.get(row.pluginClass) }}
              </div>
              <div>|</div>
              <div>(创建单位)</div>
              <div>|</div>
              <div>{{ row.createNickName }}</div>
              <div>|</div>
              <div>{{ YMDHms(row.updateTime) }}</div>
            </div>
            <div
              class="mt-[0.5rem] flex items-center gap-[var(--czr-gap)] text-[0.75rem] text-[#6F7889]"
            >
              <div class="ml-auto" @click.capture.stop="onSwitch(row)">
                <a-switch
                  v-model:checked="row.status"
                  checked-children="启用"
                  un-checked-children="停用"
                  :checked-value="1"
                  :un-checked-value="0"
                  size="small"
                />
              </div>
              <template v-if="row.status == 0">
                <el-tooltip content="编辑" effect="light" placement="top">
                  <SvgIcon
                    name="czr_edit"
                    size="14"
                    class="__hover"
                    @click.stop="onEdit(row)"
                  />
                </el-tooltip>
                <el-tooltip content="删除" effect="light" placement="top">
                  <SvgIcon
                    name="czr_del"
                    size="16"
                    class="__hover"
                    @click.stop="onDel(row)"
                  />
                </el-tooltip>
              </template>
            </div>
          </div>
        </template>
      </CzrTableCard>
    </div>
    <detailCom
      v-model:show="state.detail.show"
      :transfer="state.detail.transfer"
      @refresh="onSearch"
    />
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { debounce } from 'lodash'
import { useAppStore, useDialogStore, useDictionaryStore } from '@/stores'
import { ElMessage } from 'element-plus'
import detailCom from './detail.vue'
import {
  pluginDel,
  pluginGetInstanceList,
  pluginUpdateStatus,
} from '@/api/modules/model'
import { YMDHms } from '@/utils/czr-util'

const AppStore = useAppStore()
const DialogStore = useDialogStore()
const DictionaryStore = useDictionaryStore()
const emit = defineEmits([])
const props = defineProps({})
const { proxy }: any = getCurrentInstance()
const state: any = reactive({
  text: '',
  query: {
    init: false,
    loading: false,
    page: {
      pageNum: 1,
      pageSize: 20,
    },
    form: {},
    formReal: {},
    result: {
      total: 0,
      data: [],
    },
  },
  detail: {
    show: false,
    transfer: {},
  },
})
const setText = debounce((v) => {
  state.query.form.keyword = v
}, 1000)
watch(
  () => state.text,
  (n) => {
    setText(n)
  },
)
watch(
  () => state.query.form,
  (n) => {
    if (state.query.init) {
      onSearch()
    }
  },
  { deep: true },
)
const onPage = (pageNum, pageSize) => {
  setTimeout(() => {
    state.query.init = true
  }, 100)
  state.query.page = {
    pageNum: pageNum,
    pageSize: pageSize,
  }
  const params = {
    page: state.query.page.pageNum,
    size: state.query.page.pageSize,
  }
  //  添加表单参数
  for (const [k, v] of Object.entries(state.query.formReal)) {
    if (proxy.$czrUtil.isValue(v)) {
      params[k] = v
    }
  }
  state.query.loading = true
  pluginGetInstanceList(params)
    .then(({ data }: any) => {
      state.query.result.total = data.total
      state.query.result.data = data.records
    })
    .catch(({ message }: any) => {
      ElMessage.error(message)
    })
    .finally(() => {
      state.query.loading = false
    })
}
const onSearch = () => {
  state.query.formReal = JSON.parse(JSON.stringify(state.query.form))
  onPage(1, state.query.page.pageSize)
}
const onReset = () => {
  state.query.page = {
    pageNum: 1,
    pageSize: 20,
  }
  state.query.form = {}
  onSearch()
}
const onAdd = () => {
  state.detail.transfer = {
    mode: 'add',
  }
  state.detail.show = true
}
const onEdit = (row) => {
  state.detail.transfer = {
    mode: 'edit',
    id: row.id,
  }
  state.detail.show = true
}
const onDel = (row: any) => {
  DialogStore.confirm({
    title: '删除确认',
    content: `${row.p6}个应用正在使用该大模型，删除将导致不可用，请确认是否删除`,
    onSubmit: () => {
      pluginDel(row.id)
        .then(() => {
          ElMessage.success('删除成功！')
        })
        .catch(({ message }: any) => {
          ElMessage.error(message)
        })
        .finally(() => {
          onSearch()
        })
    },
  })
}
const onSwitch = (row) => {
  if (row.status == 1) {
    DialogStore.confirm({
      title: '停用确认',
      content: `${row.p6}个应用正在使用该大模型，停用将导致不可用，请确认是否停用`,
      onSubmit: () => {
        pluginUpdateStatus({ ids: [row.id], status: 0 })
          .then(() => {
            ElMessage.success('停用成功！')
          })
          .catch(({ message }: any) => {
            ElMessage.error(message)
          })
          .finally(() => {
            onSearch()
          })
      },
      onCancel: () => {},
    })
  } else {
    pluginUpdateStatus({ ids: [row.id], status: 1 })
      .then(() => {
        ElMessage.success('启用成功！')
      })
      .catch(({ message }: any) => {
        ElMessage.error(message)
      })
      .finally(() => {
        onSearch()
      })
  }
}
onMounted(() => {
  initDictionary()
  onReset()
})
const initDictionary = () => {
  DictionaryStore.initModelTypes()
  DictionaryStore.initModelProvides()
}
</script>

<style lang="scss" scoped>
.model {
  width: 100%;
  background-image: url('@/assets/images/model-icon-7.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  padding: 1rem 1.5rem;
  border-radius: var(--czr-gap);
  box-shadow: 0rem 0.25rem 0.63rem 0rem rgba(40, 83, 247, 0.05);
  border: var(--czr-border);
  display: flex;
  flex-direction: column;
}
</style>
