<script setup lang="ts">
import type { FormInst } from 'naive-ui'
import { commonApi } from '@/api/common'
import { isOriginalList, isPublicList } from '@/constants/index'
import { Asterisk } from 'lucide-vue-next'

const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
    default: () => ({ workFlow: {}, workFlowVersionList: [] }),
  },
})
const emit = defineEmits(['update:modelValue', 'nextStep'])
const message = useMessage()

const formRef = ref<FormInst | null>(null)
const rules = {
  'workFlow.workflowName': {
    required: true,
    message: '',
    trigger: 'blur',
  },
  'workFlow.modelType': {
    required: true,
    message: '',
    trigger: 'blur',
  },
}
function handleValidateClick() {
  formRef.value?.validate((errors) => {
    if (!errors) {
      emit('nextStep')
    }
    else {
      console.log(errors)
    }
  })
}
const activityList = ref([])
async function getActivityList() {
  try {
    const res = await request.post('/ToActivity/list', {})
    activityList.value = res.rows
  }
  catch (error) {
    console.log(error)
  }
}
getActivityList()

const localForm = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  },
})

watch(
  () => localForm.value,
  (newVal) => {
    emit('update:modelValue', newVal)
  },
  { immediate: true, deep: true },
)
function handleIsPublic(value: number) {
  localForm.value.workFlow.jurisdiction = value
}
function handleIsOriginal(value: number) {
  localForm.value.workFlow.original = value
  // if (value === 0) {
  //   localForm.value.workFlow.authorName = ''
  // }
}

// 内容类别
interface DictItem {
  dictLabel: string
  dictValue: string | number
  children?: DictItem[]
}

// interface FormData {
//   workFlow: {
//     type: (string | number)[]
//   }
// }

// // 表单数据
// const localForm = ref<FormData>({
//   workFlow: {
//     type: [],
//   },
// })
const workFlowTypeList = ref<DictItem[]>([])
async function getDictType() {
  try {
    const [res1, res2] = await Promise.all([
      commonApi.dictType({ type: 'work_flow_type' }),
      commonApi.dictType({ type: 'work_flow_type_child' }),
    ])

    // modelPartCategory.value = res1.data
    workFlowTypeList.value = res1.data
    // 遍历第一个数据数组，检查是否有子项
    workFlowTypeList.value.forEach((item: any) => {
      // 给每个对象添加一个children属性，初始化为空数组
      item.children = []
      // 遍历第二个数据数组
      res2.data.forEach((child: any) => {
        // 检查parentId是否与dictValue相等
        if (child.partId === item.dictCode) {
          // 将符合条件的子项放入children数组中
          item.children.push(child)
        }
      })
    })
    console.log('object', workFlowTypeList.value)
  }
  catch (error) {
    console.log(error)
  }
}
getDictType()
function handleUpdateValue(value: any) {
  localForm.value.workFlow.typeList = value
  if (value.length > 2) {
    message.error('最多只能选择两项')
    value = value.splice(0, 2)
    localForm.value.workFlow.typeList = value
  }
  else {
    localForm.value.workFlow.typeList = value
  }
}
</script>

<template>
  <div class="flex justify-center mx-auto mt-10">
    <div class="w-[1137px] flex items-start">
      <div class="bg-gray-100 p-4 h-auto w-[60%] mr-2 rounded-lg">
        <n-form
          ref="formRef"
          :label-width="80"
          :model="localForm"
          :rules="rules"
          size="large"
        >
          <n-form-item label="工作流名称" path="workFlow.workflowName">
            <n-input v-model:value="localForm.workFlow.workflowName" placeholder="简单描述用途， 如: 图像一键放大" />
          </n-form-item>
          <div>
            内容类别
          </div>
          <div class="text-gray-400 -mb-4 text-[12px]">
            填写类别可让工作流获得更精准的流量，平台也有权基于标准修改你的类别标签
          </div>
          <n-form-item path="workFlow.activityId">
            <!-- <n-select
              v-model:value="localForm.workFlow.typeList" label-field="dictLabel"
              value-field="dictValue" filterable :options="workFlowTypeList"
              @update:value="handleUpdateValue"
              placeholder="请选择类型"
            /> -->
            <n-cascader
              v-model:value="localForm.workFlow.typeList"
              multiple
              clearable
              placeholder="请选择类型"
              max-tag-count="responsive"
              :options="workFlowTypeList"
              check-strategy="child"
              label-field="dictLabel"
              value-field="dictValue"
              @update:value="handleUpdateValue"
            />
          </n-form-item>
          <div>
            参与活动
          </div>
          <div class="text-gray-400 -mb-4 text-[12px]">
            参与特定活动或比赛,下拉选择
          </div>
          <n-form-item path="workFlow.activityParticipation">
            <n-select
              v-model:value="localForm.workFlow.activityParticipation"
              label-field="activityName"
              value-field="id"
              placeholder="请选择参与哪个活动"
              :options="activityList"
            />
          </n-form-item>
        </n-form>
      </div>
      <div class="w-[40%]">
        <div class=" bg-gray-100 p-4 rounded-lg">
          <div class="flex -mb-2">
            是否公开<Asterisk :size="10" color="#ff0000" class="mt-1" />
          </div>
          <div class="flex justify-center items-center mt-5 bg-white h-10 rounded-lg">
            <div
              v-for="(item, index) in isPublicList"
              :key="index"
              :style="{
                backgroundColor:
                  localForm.workFlow.jurisdiction === item.value
                    ? 'rgba(49, 98, 255, 0.1)'
                    : '#fff',
                color: localForm.workFlow.jurisdiction === item.value ? '#3162ff' : '#000',
              }" class="flex-1 rounded-lg h-full flex items-center justify-center cursor-pointer" @click="handleIsPublic(item.value)"
            >
              {{ item.label }}
            </div>
          </div>
          <div class="text-gray-400 text-[12px] mt-2">
            <div v-if="localForm.workFlow.jurisdiction === 1">
              公开状态: 对网站所有人可见
            </div>
            <div v-if="localForm.workFlow.jurisdiction === 2">
              非公开状态: 仅自己可见，可在“在线生图”自用
            </div>
          </div>

          <div class="flex -mb-2 mt-2">
            是否原创<Asterisk :size="10" color="#ff0000" class="mt-1" />
          </div>
          <div class="flex justify-center items-center mt-5 bg-white h-10 rounded-lg">
            <div
              v-for="(item, index) in isOriginalList"
              :key="index"
              :style="{
                backgroundColor:
                  localForm.workFlow.original === item.value
                    ? 'rgba(49, 98, 255, 0.1)'
                    : '#fff',
                color: localForm.workFlow.original === item.value ? '#3162ff' : '#000',
              }" class="flex-1 rounded-lg h-full flex items-center justify-center cursor-pointer" @click="handleIsOriginal(item.value)"
            >
              {{ item.label }}
            </div>
          </div>
          <div v-if="localForm.workFlow.original === 0" class="text-gray-400 text-[12px] mt-2">
            发布原创模型拿收益：<span class="text-[#3162ff] cursor-pointer">创作者激励计划</span>
          </div>
          <n-form
            v-if="localForm.workFlow.original === 1"
            :label-width="80"
            :model="localForm"
            :rules="rules"
            size="large"
          >
            <n-form-item path="workFlow.authorName">
              <n-input v-model:value="localForm.workFlow.authorName" placeholder="请输入原创作者" />
            </n-form-item>
          </n-form>
        </div>

        <div class="mt-4 bg-gray-100 p-4 rounded-lg">
          <div class="text-[#3162ff] mb-4">
            用户使用时, 我授予用户以下权限
          </div>
          <div>
            <div class="flex mb-2">
              <n-checkbox
                v-model:checked="localForm.workFlow.onlineUse"
                :checked-value="0"
                :unchecked-value="1"
              />
              <div class="text-[12px] ml-2">
                <div class="text-gray-600">
                  允许在线使用
                </div>
                <div class="text-gray-400">
                  您的工作流为公开状态时，默认同意此条款，他人不能随意转载
                </div>
              </div>
            </div>
            <div class="flex mb-2">
              <n-checkbox
                v-model:checked="localForm.workFlow.download"
                :checked-value="0"
                :unchecked-value="1"
              />
              <div class="text-[12px] ml-2">
                <div class="text-gray-600">
                  允许下载工作流
                </div>
                <div class="text-gray-400">
                  允许下载后，您的工作流可能会被他人转载，我们无法控制该行为
                </div>
              </div>
            </div>
          </div>

          <div class="text-[#3162ff] mb-4">
            用户使用时，我授予用户以下商业用途权限:
          </div>
          <div>
            <div class="flex mb-2">
              <n-checkbox
                v-model:checked="localForm.workFlow.sell"
                :checked-value="0"
                :unchecked-value="1"
              />
              <div class="text-[12px] ml-2">
                <div class="text-gray-600">
                  生成图片可出售或用于商业目的
                </div>
              </div>
            </div>
          </div>
        </div>

        <div
          class="flex justify-center items-center mt-5 text-white w-30 h-10 rounded-lg bg-[#3162ff] cursor-pointer" @click="handleValidateClick"
        >
          下一步
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>
