<template>
  <div class="flex h-full w-full flex-col">
    <div
      class="__hover flex items-center text-sm text-[var(--czr-main-color)]"
      @click="toBack"
    >
      <SvgIcon
        name="czr_arrow"
        rotate="180"
        size="13"
        :active="true"
        class="mr-1"
      />应用中心
    </div>
    <div class="bm-main-box mt-4">
      <div class="grid h-full w-full grid-cols-3 gap-4">
        <div
          class="col-span-2 flex flex-col gap-2 overflow-hidden rounded-lg bg-[#F6F8FC] p-4"
        >
          <div
            class="flex h-14 w-full items-center gap-2.5 rounded-lg bg-[#ffffff] px-6"
          >
            <div class="text-2xl font-bold text-[#303133]">编排</div>
            <div class="text-[#576275]" v-if="state.autoSaveTimestamp">
              自动保存{{ state.autoSaveTimestamp }}
            </div>
            <div class="mx-auto" />
            <div
              class="flex items-center text-[var(--czr-error-color)]"
              v-if="state.autoSaveTimestamp"
            >
              <SvgIcon
                name="czr_tip"
                color="var(--czr-error-color)"
                class="mr-1"
              />
              有未发布的修改
            </div>
            <CzrButton type="primary" title="发布" @click="onPublish" />
            <el-popover
              :show-arrow="false"
              width="26rem"
              placement="bottom-end"
              :popper-style="{
                padding: 0,
              }"
            >
              <template #reference>
                <div
                  class="__hover flex h-8 w-8 items-center justify-center rounded-sm border-1 border-[var(--czr-main-color)]"
                >
                  <SvgIcon name="history" :active="true" size="16" />
                </div>
              </template>
              <div>
                <div
                  class="flex h-11 w-full items-center bg-[url('@/assets/images/knowledge/knowledge-back-test.png')] bg-[length:100%_100%] bg-no-repeat px-4 text-base font-bold text-[#303133]"
                >
                  历史版本
                </div>
                <div class="h-[68vh] overflow-y-auto px-4 py-2">
                  <template v-for="(item, index) in state.history">
                    <div class="flex">
                      <div
                        class="relative mr-3 flex flex-col items-center justify-center"
                      >
                        <div
                          class="h-[50%] w-0.5"
                          :class="`${index > 0 ? 'bg-[#DEE9FF]' : ''}`"
                        />
                        <div
                          class="h-[50%] w-0.5"
                          :class="`${index < state.history.length - 1 ? 'bg-[#DEE9FF]' : ''}`"
                        />
                        <div
                          class="absolute flex size-2 items-center justify-center rounded bg-[var(--czr-main-color)]"
                        >
                          <div class="size-1 rounded bg-[#DEE9FF]" />
                        </div>
                      </div>
                      <div
                        class="my-2 flex flex-1 items-center justify-between rounded-lg bg-[#F4F8FF] px-4 py-3"
                      >
                        <div
                          class="text-base font-bold"
                          :class="{
                            'text-[var(--czr-success-color)]':
                              item.type === 'publish' || item.type === 'apply',
                            'text-[var(--czr-warning-color)]':
                              item.type === 'submit',
                            'text-[#2E3238]': item.type === 'create',
                          }"
                        >
                          {{ item.type }}
                        </div>
                        <div class="text-[#909399]">{{ item.date }}</div>
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </el-popover>
          </div>
          <CzrForm class="form" ref="ref_form">
            <div class="grid h-full flex-1 grid-cols-2 gap-4">
              <div class="col-span-1 flex flex-col rounded-lg bg-[#ffffff]">
                <div
                  class="flex h-12 w-full items-center gap-2.5 bg-[url('@/assets/images/knowledge/knowledge-back-test.png')] bg-[length:100%_100%] bg-no-repeat px-6"
                >
                  <div class="mr-auto font-bold text-[#303133]">提示词</div>
                  <CzrButton
                    type="normal"
                    title="保存为模板"
                    @click="onAddTipsTemplate"
                  />
                  <CzrButton
                    type="normal"
                    title="使用模板"
                    @click="onTipsTemplate"
                  />
                </div>
                <div class="flex-1 p-4">
                  <textarea
                    class="h-full w-full"
                    style="resize: none; line-height: 1.4"
                    ref="ref_tips"
                    v-model="state.form.tips"
                  ></textarea>
                </div>
              </div>
              <div
                class="col-span-1 overflow-y-auto rounded-lg bg-[#ffffff] p-4"
              >
                <div class="__czr-title_2">模型选择</div>
                <div class="mt-4">
                  <CzrFormColumn
                    class="__czr-table-form-column"
                    required
                    label="模型选择"
                    :span="24"
                    v-model:param="state.form.model.name"
                    placeholder="点击选择模型"
                    readonly
                    @click="onModel"
                    default-error-msg="请选择模型"
                  />
                </div>
                <div class="__czr-title_2 mt-4">
                  组件
                  <template v-if="state.form.components.length > 0">
                    ({{ state.form.components.length }})
                  </template>
                  <!--                  <CzrButton type="normal" title="新增" class="ml-auto" />-->
                </div>
                <template v-if="state.form.components.length > 0"> </template>
                <template v-else>
                  <div
                    class="mt-2 flex h-8 items-center justify-center rounded-sm bg-[#F6F8FC] text-xs text-[#A7ADB9]"
                  >
                    暂未添加组件
                  </div>
                </template>
                <div class="__czr-title_2 mt-4">
                  知识库
                  <template v-if="state.form.knowledges.length > 0">
                    ({{ state.form.knowledges.length }})
                  </template>
                  <CzrButton
                    type="normal"
                    title="新增"
                    class="ml-auto"
                    @click="onAddKnowledge"
                  />
                </div>
                <template v-if="state.form.knowledges.length > 0">
                  <div
                    class="mt-2 flex max-h-42 flex-col gap-2 overflow-y-auto pr-2"
                  >
                    <template v-for="(item, index) in state.form.knowledges">
                      <div class="flex items-center gap-1.5">
                        <div
                          class="flex flex-1 items-center overflow-hidden rounded-sm bg-[#F6F8FC] p-2.5"
                        >
                          <img
                            src="@/assets/images/knowledge/knowledge-item-icon.png"
                            class="mr-4 size-6"
                          />
                          <div
                            class="flex-1 text-sm font-bold text-[#2E3238]"
                            v-title
                          >
                            {{ item.name }}
                          </div>
                        </div>
                        <SvgIcon
                          class="__hover"
                          name="czr_del"
                          color="var(--czr-error-color)"
                          @click="state.form.knowledges.splice(index, 1)"
                        />
                      </div>
                    </template>
                  </div>
                </template>
                <template v-else>
                  <div
                    class="mt-2 flex h-8 items-center justify-center rounded-sm bg-[#F6F8FC] text-xs text-[#A7ADB9]"
                  >
                    暂未添加知识库
                  </div>
                </template>
                <div class="__czr-title_2 mt-4">
                  工作流
                  <template v-if="state.form.workflows.length > 0">
                    ({{ state.form.workflows.length }})
                  </template>
                  <CzrButton
                    type="normal"
                    title="新增"
                    class="ml-auto"
                    @click="onAddWorkflow"
                  />
                </div>
                <template v-if="state.form.workflows.length > 0">
                  <div
                    class="mt-2 flex max-h-42 flex-col gap-2 overflow-y-auto pr-2"
                  >
                    <template v-for="(item, index) in state.form.workflows">
                      <div class="flex items-center gap-1.5">
                        <div
                          class="flex flex-1 items-center overflow-hidden rounded-sm bg-[#F6F8FC] p-2.5"
                        >
                          <img
                            src="@/assets/images/workflow/workflow-default-icon.png"
                            class="mr-4 size-15"
                          />
                          <div
                            class="flex flex-1 flex-col gap-2 overflow-hidden"
                          >
                            <div
                              class="text-sm font-bold text-[#2E3238]"
                              v-title
                            >
                              {{ item.name }}
                            </div>
                            <div
                              class="text-sm text-[#6F7889]"
                              v-title="{ lines: 2 }"
                            >
                              {{ item.description }}
                            </div>
                          </div>
                        </div>
                        <SvgIcon
                          class="__hover"
                          name="czr_del"
                          color="var(--czr-error-color)"
                          @click="state.form.workflows.splice(index, 1)"
                        />
                      </div>
                    </template>
                  </div>
                </template>
                <template v-else>
                  <div
                    class="mt-2 flex h-8 items-center justify-center rounded-sm bg-[#F6F8FC] text-xs text-[#A7ADB9]"
                  >
                    暂未添加工作流
                  </div>
                </template>
                <div class="__czr-title_2 mt-4">开场白</div>
                <div class="mt-4">
                  <CzrFormColumn
                    class="__czr-table-form-column"
                    required
                    label-width="0px"
                    :span="24"
                    v-model:param="state.form.prologue"
                    link="rich"
                    :height="300"
                    default-error-msg="请输入开场白"
                  />
                </div>
                <div class="__czr-title_2 mt-4">
                  开场白引导问题
                  <template v-if="state.form.prologueQuestions.length > 0">
                    ({{ state.form.prologueQuestions.length }})
                  </template>
                  <div class="ml-auto">
                    <el-radio-group
                      v-model="state.form.prologueType"
                      size="small"
                    >
                      <el-radio-button value="three">显示前3条</el-radio-button>
                      <el-radio-button value="all">显示全部</el-radio-button>
                    </el-radio-group>
                  </div>
                </div>
                <div class="mt-2 flex flex-col">
                  <div
                    class="drag-body col relative flex max-h-42 flex-col gap-2 overflow-y-auto pr-2"
                    ref="ref_prologueBody"
                    v-if="state.dragRefresh"
                  >
                    <template
                      v-for="(item, index) in state.form.prologueQuestions"
                    >
                      <div
                        class="flex items-center gap-2"
                        style="-webkit-user-drag: element"
                      >
                        <SvgIcon
                          name="czr_drag"
                          color="#999999"
                          class="drag-icon cursor-move"
                        />
                        <div
                          class="__hover flex h-7 flex-1 items-center rounded-sm bg-[#F6F8FC] px-2.5 text-sm text-[#A7ADB9]"
                          @click="onPrologue(item)"
                        >
                          <template v-if="item.__edit">
                            <CzrFormColumn
                              ref="ref_prologue"
                              class="transparent-input"
                              label-width="0px"
                              :span="24"
                              v-model:param="item.__value"
                              :transparent="true"
                              :clearable="false"
                              maxlength="40"
                              show-word-limit
                              @keyup.enter.stop="onEditPrologue(item)"
                              @blur="onEditPrologue(item)"
                            />
                          </template>
                          <template v-else> {{ item.value }} </template>
                        </div>
                        <SvgIcon
                          class="__hover"
                          name="czr_del"
                          color="var(--czr-error-color)"
                          @click="state.form.prologueQuestions.splice(index, 1)"
                        />
                      </div>
                    </template>
                  </div>
                  <div class="mt-2 flex items-center gap-2">
                    <div
                      class="__hover flex h-7 flex-1 items-center rounded-sm bg-[#F6F8FC] px-2.5 text-sm text-[#A7ADB9]"
                      @click="onPrologue(null)"
                    >
                      <template v-if="state.prologuesAdd.__edit">
                        <CzrFormColumn
                          ref="ref_prologue"
                          class="transparent-input"
                          label-width="0px"
                          :span="24"
                          v-model:param="state.prologuesAdd.value"
                          :transparent="true"
                          :clearable="false"
                          maxlength="40"
                          show-word-limit
                          @keyup.enter.stop="onAddPrologue"
                          @blur="state.prologuesAdd.__edit = false"
                        />
                      </template>
                      <template v-else> 点击输入问题，enter以新增 </template>
                    </div>
                  </div>
                </div>
                <div class="__czr-title_2 mt-4">用户输入方式</div>
                <div class="mt-4">
                  <CzrFormColumn
                    class="__czr-table-form-column"
                    required
                    label="输入方式"
                    :span="24"
                    v-model:param="state.form.method"
                    link="select"
                    :options="[
                      { value: 1, label: '文字/语音输入' },
                      { value: 2, label: '语音通话' },
                    ]"
                    :clearable="false"
                  />
                  <div
                    class="mt-4 flex items-center"
                    v-if="state.form.method == 2"
                  >
                    <div class="flex-1">
                      <CzrFormColumn
                        class="__czr-table-form-column"
                        required
                        label="语音包"
                        :span="24"
                        v-model:param="state.form.voicePackage"
                        link="select"
                        :options="[
                          { value: 1, label: '语音包1' },
                          { value: 2, label: '语音包2' },
                        ]"
                        :clearable="false"
                      >
                        <template #row="{ row }">
                          <div class="flex h-full items-center">
                            {{ row.label }}
                            <div
                              class="__hover ml-auto text-[var(--czr-main-color)]"
                              @click.stop=""
                            >
                              试听
                            </div>
                          </div>
                        </template>
                      </CzrFormColumn>
                    </div>
                    <div
                      class="__hover ml-4 text-sm text-[var(--czr-main-color)]"
                    >
                      试听
                    </div>
                  </div>
                </div>
                <div class="__czr-title_2 mt-4">
                  问题建议
                  <div class="ml-auto">
                    <el-checkbox-group
                      v-model="state.form.advise.types"
                      size="small"
                    >
                      <el-checkbox-button value="open">
                        开启
                      </el-checkbox-button>
                      <template v-if="state.form.advise.types.includes('open')">
                        <el-checkbox-button value="tips">
                          自定义提示词
                        </el-checkbox-button>
                        <el-checkbox-button value="knowledge">
                          仅从知识库建议
                        </el-checkbox-button>
                      </template>
                    </el-checkbox-group>
                  </div>
                </div>
                <template v-if="state.form.advise.types.includes('open')">
                  <div class="mt-4">
                    <CzrFormColumn
                      class="__czr-table-form-column"
                      required
                      label="模型选择"
                      :span="24"
                      v-model:param="state.form.advise.model.name"
                      placeholder="点击选择模型"
                      readonly
                      @click="onAdviseModel"
                      default-error-msg="请选择问题建议模型"
                    />
                    <div
                      class="mt-2 flex h-10 items-center gap-1 rounded-sm bg-[#FFFAEA] px-3.5 text-sm text-[#6F7889]"
                    >
                      <SvgIcon
                        name="czr_tip"
                        color="var(--czr-warning-color)"
                      />
                      应用每次回复后，根据对话内容提出最多3条问题建议
                    </div>
                    <template v-if="state.form.advise.types.includes('tips')">
                      <div class="mt-2">
                        <CzrFormColumn
                          class="__czr-table-form-column"
                          label-width="0px"
                          :span="24"
                          v-model:param="state.form.advise.tips"
                          type="textarea"
                          :rows="4"
                          placeholder="问题应该与你最后一轮的回复紧密相关，可以引发进一步的讨论。&#10;问题不要与上文已经提问或者回答过的内容重复。&#10;每句话只包含一个问题，但也可以不是问句而是一句指令。&#10;推荐你有能力回答的问题。"
                        />
                      </div>
                    </template>
                  </div>
                  <template
                    v-if="state.form.advise.types.includes('knowledge')"
                  >
                    <div class="__czr-title_2 mt-4">
                      问题建议知识库
                      <template v-if="state.form.advise.knowledges.length > 0">
                        ({{ state.form.advise.knowledges.length }})
                      </template>
                      <CzrButton
                        type="normal"
                        title="新增"
                        class="ml-auto"
                        @click="onAddAdviseKnowledge"
                      />
                    </div>
                    <template v-if="state.form.advise.knowledges.length > 0">
                      <div
                        class="mt-2 flex max-h-42 flex-col gap-2 overflow-y-auto pr-2"
                      >
                        <template
                          v-for="(item, index) in state.form.advise.knowledges"
                        >
                          <div class="flex items-center gap-1.5">
                            <div
                              class="flex h-10 flex-1 items-center overflow-hidden rounded-sm bg-[#F6F8FC] px-2.5"
                            >
                              <img
                                src="@/assets/images/knowledge/knowledge-item-icon-2.png"
                                class="mr-4 size-6"
                              />
                              <div
                                class="flex-1 text-sm font-bold text-[#2E3238]"
                                v-title
                              >
                                {{ item.name }}
                              </div>
                            </div>
                            <SvgIcon
                              class="__hover"
                              name="czr_del"
                              color="var(--czr-error-color)"
                              @click="
                                state.form.advise.knowledges.splice(index, 1)
                              "
                            />
                          </div>
                        </template>
                      </div>
                    </template>
                    <template v-else>
                      <div
                        class="mt-2 flex h-8 items-center justify-center rounded-sm bg-[#F6F8FC] text-xs text-[#A7ADB9]"
                      >
                        暂未添加问题建议知识库
                      </div>
                    </template>
                  </template>
                </template>
              </div>
            </div>
          </CzrForm>
        </div>
        <div
          class="col-span-1 flex flex-col gap-2 overflow-hidden rounded-lg bg-[#F6F8FC] p-4"
        >
          <div
            class="flex h-14 w-full items-center gap-2.5 rounded-lg bg-[#ffffff] px-6"
          >
            <div class="text-2xl font-bold text-[#303133]">预览</div>
            <div
              class="flex items-center gap-2 text-sm text-[var(--czr-error-color)]"
              v-if="modelApplyCpt"
            >
              <SvgIcon name="czr_tip" color="var(--czr-error-color)" />
              编排中有申请中的模型，预览暂不可用
            </div>
            <el-tooltip content="重新开始" :raw-content="true" placement="top">
              <SvgIcon class="__hover ml-auto" name="refresh" :active="true" />
            </el-tooltip>
          </div>
          <div class="relative flex-1 overflow-hidden">
            <chat />
            <div
              v-if="!state.isDebug"
              class="absolute inset-0 flex h-full w-full flex-col rounded-lg bg-white/50 p-20 backdrop-blur-sm"
            >
              <div class="text-2xl font-bold text-[#1d2939]">编排已改变</div>
              <div class="mt-6 text-[#667085]">
                修改编排将重置调试区域，确定吗？
              </div>
              <div class="mt-6 flex gap-2">
                <CzrButton
                  type="primary"
                  title="重新开始"
                  icon="refresh"
                  size="18"
                  @click="state.isDebug = true"
                />
                <CzrButton
                  type="normal"
                  title="取消"
                  @click="state.isDebug = true"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <knowledgeSelect
      v-model:show="state.knowledgeSelect.show"
      :transfer="state.knowledgeSelect.transfer"
      @refresh="getKnowledge"
    />
    <modelSelect
      v-model:show="state.modelSelect.show"
      :transfer="state.modelSelect.transfer"
      @refresh="getModel"
    />
    <workflowSelect
      v-model:show="state.workflowSelect.show"
      :transfer="state.workflowSelect.transfer"
      @refresh="getWorkflow"
    />
    <templateSelect
      v-model:show="state.templateSelect.show"
      @insert="(val) => ((state.form.tips = val), ref_tips.focus())"
    />
    <templateDetail
      v-model:show="state.templateDetail.show"
      :transfer="state.templateDetail.transfer"
    />
    <CzrDialog
      :show="state.publish.show"
      title="发布"
      @onClose="state.publish.show = false"
      @onSubmit="onPublishSubmit"
      width="42.5rem"
      height="auto"
    >
      <div class="bm-form">
        <CzrForm ref="ref_formPublish">
          <CzrFormColumn
            required
            label="发布渠道"
            :span="24"
            v-model:param="state.publish.form.name"
            link="select"
            :options="[
              { label: '个人', value: '1' },
              { label: '公共空间(需审批)', value: '2' },
            ]"
            :clearable="false"
          />
          <CzrFormColumn
            v-if="state.publish.form.name == 2"
            label="申请留言"
            :span="24"
            v-model:param="state.publish.form.description"
            type="textarea"
            :rows="10"
          />
        </CzrForm>
      </div>
    </CzrDialog>
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  getCurrentInstance,
  inject,
  nextTick,
  onMounted,
  reactive,
  ref,
  watch,
} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElLoading, ElMessage } from 'element-plus'
import { useDialogStore, useDictionaryStore } from '@/stores'
import { Search } from '@element-plus/icons-vue'
import knowledgeSelect from './knowledge-select.vue'
import modelSelect from './model-select.vue'
import { isValue, YMDHms } from '@/utils/czr-util'
import Sortable from 'sortablejs'
import { debounce } from 'lodash'
import chat from '@/views/chat/index.vue'
import templateSelect from './template-select.vue'
import templateDetail from './template-detail.vue'
import workflowSelect from './workflow-select.vue'
import CzrForm from '@/components/czr-ui/CzrForm.vue'
import CzrDialog from '@/components/czr-ui/CzrDialog.vue'

const DictionaryStore = useDictionaryStore()
const DialogStore = useDialogStore()
const route = useRoute()
const router = useRouter()
const emit = defineEmits([])
const props = defineProps({})
const { proxy }: any = getCurrentInstance()
const state: any = reactive({
  ID: route.params.id,
  autoSaveTimestamp: '',
  form: {
    tips: '',
    model: { name: '' },
    components: [],
    knowledges: [
      {
        name: '水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水',
        description:
          '水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水',
      },
    ],
    workflows: [
      {
        name: '水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水',
        description:
          '水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水水',
      },
    ],
    prologue: '',
    prologueQuestions: [
      { value: '1' },
      { value: '2' },
      { value: '3' },
      { value: '4' },
      { value: '5' },
    ],
    prologueType: 'three',
    method: 1,
    voicePackage: '',
    advise: {
      types: [],
      model: { name: '' },
      tips: '',
      knowledges: [],
    },
  },
  detail: {},
  knowledgeSelect: {
    show: false,
    transfer: {},
  },
  modelSelect: {
    show: false,
    transfer: {},
  },
  workflowSelect: {
    show: false,
    transfer: {},
  },
  templateSelect: {
    show: false,
  },
  templateDetail: {
    show: false,
    transfer: {},
  },
  publish: {
    show: false,
    transfer: {},
    form: {},
  },
  prologuesAdd: {
    value: '',
  },
  dragRefresh: true,
  isDebug: true,
  history: [
    { type: 'submit', date: '2024-03-06 22:24:54' },
    { type: 'publish', date: '2024-03-06 22:24:54' },
    { type: 'apply', date: '2024-03-06 22:24:54' },
    { type: 'publish', date: '2024-03-06 22:24:54' },
    { type: 'submit', date: '2024-03-06 22:24:54' },
    { type: 'publish', date: '2024-03-06 22:24:54' },
    { type: 'submit', date: '2024-03-06 22:24:54' },
    { type: 'publish', date: '2024-03-06 22:24:54' },
    { type: 'create', date: '2024-03-06 22:24:54' },
  ],
})
const ref_form = ref()
const ref_formPublish = ref()
const ref_tips = ref()
const ref_prologue = ref()
const ref_prologueBody = ref()
const modelApplyCpt = computed(() => {
  return true
})
const initDetail = () => {
  if (state.ID) {
    state.detail = {}
    // pluginDetail(state.ID)
    //   .then(({ data }: any) => {
    //     state.detail = data
    //   })
    //   .catch(() => {})
    //   .finally(() => {})
    initDrag()
  } else {
    router.push({ name: 'd446bfb3-4605-477f-a0f4-b7a0a1aa78fe' })
  }
}
const initDrag = () => {
  nextTick(() => {
    const tbody =
      ref_prologueBody.value.parentElement.querySelector('.drag-body')
    new Sortable(tbody, {
      animation: 150,
      handle: '.drag-icon', // 设置可拖拽行的类名(el-table自带的类名)
      onEnd: ({ newIndex, oldIndex }: any) => {
        const d = [...state.form.prologueQuestions]
        const targetRow = d[oldIndex]
        d.splice(oldIndex, 1)
        d.splice(newIndex, 0, targetRow)
        state.form.prologueQuestions = [...d]
        state.dragRefresh = false
        setTimeout(() => {
          state.dragRefresh = true
          initDrag()
        }, 0)
      },
    })
  })
}

const toBack = () => {
  router.push({
    name: 'd446bfb3-4605-477f-a0f4-b7a0a1aa78fe',
  })
}
const onAddKnowledge = () => {
  state.knowledgeSelect.transfer = {
    ids: state.form.knowledges.map((v) => v.id),
    type: 'knowledge',
  }
  state.knowledgeSelect.show = true
}
const onAddAdviseKnowledge = () => {
  state.knowledgeSelect.transfer = {
    ids: state.form.advise.knowledges.map((v) => v.id),
    type: 'advise',
  }
  state.knowledgeSelect.show = true
}
const onPrologue = (row) => {
  if (row) {
    row.__value = row.value + ''
    row.__edit = true
  } else {
    state.prologuesAdd.__edit = true
  }
  const t = setInterval(() => {
    const r = ref_prologue.value
    if (r) {
      if (r.length) {
        r[0].focus()
      } else {
        r.focus()
      }
      clearInterval(t)
    }
  }, 100)
}
const onAddPrologue = () => {
  state.form.prologueQuestions.push({ value: state.prologuesAdd.value + '' })
  state.prologuesAdd.value = ''
}
const onEditPrologue = (row) => {
  if (isValue(row.__value.trim())) {
    row.value = row.__value + ''
  }
  row.__edit = false
}
const getKnowledge = (arr) => {
  switch (state.knowledgeSelect.transfer.type) {
    case 'knowledge':
      {
        state.form.knowledges.push(...arr)
      }
      break
    case 'advise':
      {
        state.form.advise.knowledges.push(...arr)
      }
      break
  }
}
const getModel = (val) => {
  switch (state.modelSelect.transfer.type) {
    case 'model':
      {
        state.form.model = val
      }
      break
    case 'advise':
      {
        state.form.advise.model = val
      }
      break
  }
}
const onModel = () => {
  state.modelSelect.transfer = {
    type: 'model',
    id: state.form.model.id,
  }
  state.modelSelect.show = true
}
const onAdviseModel = () => {
  state.modelSelect.transfer = {
    type: 'advise',
    id: state.form.advise.model.id,
  }
  state.modelSelect.show = true
}
const onPublish = () => {
  ref_form.value
    .submit()
    .then(() => {
      if (state.detail.type == 1) {
        if (state.form.workflows.length === 0) {
          ElMessage.warning('请添加工作流！')
          return
        }
      }
      if (state.form.advise.types.includes('knowledge')) {
        if (state.form.advise.knowledges.length === 0) {
          ElMessage.warning('请添加问题建议知识库！')
          return
        }
      }
      // if (modelApplyCpt.value) {
      //   DialogStore.confirm({
      //     content: `编排中有申请中的模型，暂不可发布！`,
      //     props: {
      //       showSubmit: false,
      //       showCancel: false,
      //     },
      //   })
      // }
      // if (1) {
      //   DialogStore.confirm({
      //     title: '发布失败',
      //     content: `该应用有发布中的申请，无法提交发布！<br/>申请提交时间：2023-02-02 15:21:23`,
      //     onSubmit: () => {},
      //     props: {
      //       submitText: '撤销上一次的申请，重新发布',
      //       cancelText: '等待审批',
      //     },
      //   })
      // }
      if (1) {
        state.publish.transfer = {}
        state.publish.show = true
      }
    })
    .catch((e) => {
      ElMessage({
        message: e[0].message,
        grouping: true,
        type: 'warning',
      })
    })
}
const onPublishSubmit = () => {
  ref_formPublish.value
    .submit()
    .then(() => {
      DialogStore.confirm({
        content: `请确认是否提交？`,
        onSubmit: () => {
          state.publish.show = false
        },
      })
    })
    .catch((e) => {
      ElMessage({
        message: e[0].message,
        grouping: true,
        type: 'warning',
      })
    })
}
watch(
  () => state.form,
  (n) => {
    autoSave(n)
  },
  { deep: true },
)
const autoSave = debounce((v) => {
  const loading = ElLoading.service({
    text: '自动保存中……',
    background: 'rgba(0, 0,0, 0.3)',
  })
  setTimeout(() => {
    loading.close()
    state.autoSaveTimestamp = YMDHms(new Date())
    state.isDebug = false
  }, 1000)
}, 3000)
const onAddTipsTemplate = () => {
  state.templateDetail.transfer = {
    mode: 'add',
    tips: state.form.tips + '',
  }
  state.templateDetail.show = true
}
const onTipsTemplate = () => {
  state.templateSelect.show = true
}
const onAddWorkflow = () => {
  state.workflowSelect.transfer = {
    id: state.form.workflows[0]?.id,
  }
  state.workflowSelect.show = true
}
const getWorkflow = (val) => {
  state.form.workflows = [val]
}
onMounted(() => {
  initDictionary()
  initDetail()
})
const initDictionary = () => {
  // DictionaryStore.initModelProvides()
  // DictionaryStore.initModelTypes()
}
</script>

<style lang="scss" scoped>
:deep(.form) {
  flex: 1;
  overflow: hidden;
  .el-form {
    width: 100%;
    height: 100%;
    .el-row {
      width: 100%;
      height: 100%;
      .transparent-input {
        .el-input__wrapper {
          padding: 0;
        }
      }
    }
  }
}
.__czr-title_2 {
  height: 2rem;
}
</style>
