<script setup lang="ts">
import type { Strategy } from '../types'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { updateStatusRuleList, dateUnitList, weekList } from '@/utils/dictionary'
import { createStrategy, updateStrategy, getStrategyInfo } from '../api'
import { pick } from 'lodash-es'
import { useMapStore } from '@/stores/map'
import LabelRule from '@/components/rule/LabelRule.vue'
import GroupRule from '@/components/rule/GroupRule.vue'
import { useConnection } from '@/composables/useAllData'
import { useChat } from '@/composables/useChat'
import { getNameByValue } from '@/utils/dictionary'

const props = defineProps<{
  data?: Strategy
}>()

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const typeList = useMapStore().getMapValuesByKey('strategy_type')
const industryList = useMapStore().getMapValuesByKey('strategy_industry')

const isUpdate = $computed(() => !!props.data?.id)
const title = $computed(() => (isUpdate ? '修改运营策略' : '新建运营策略'))

const { connectionList } = useConnection()

const formRef = $ref<FormInstance>()
const form: any = reactive({
  id: '',
  name: '',
  type: '',
  industry: '',
  update_status: '2',
  update_rule: { type: 1, info: 1 },
  status: '1',
  target: '',
  scene: '',
  tags_id: { current_logic_operate: 'and', items: [] },
  groups_id: { current_logic_operate: 'and', items: [] },
  time: [],
  connections_id: '',
})
function fetchInfo() {
  if (!props.data?.id) return
  getStrategyInfo({ id: props.data.id }).then(({ data }) => {
    const tagRule = data.tags_id ? JSON.parse(data.tags_id) : { current_logic_operate: 'and', items: [] }
    const groupRule = data.groups_id ? JSON.parse(data.groups_id) : { current_logic_operate: 'and', items: [] }
    Object.assign(form, data, {
      update_rule: { type: 1, info: 1 },
      tags_id: tagRule,
      groups_id: groupRule,
      time: data.time ? data.time.split(',') : [],
    })
  })
}

watchEffect(() => fetchInfo())

const rules = ref<FormRules>({
  name: [{ required: true, message: '请输入策略名称' }],
  type: [{ required: true, message: '请选择策略类型' }],
  industry: [{ required: true, message: '请选择行业' }],
  update_status: [{ required: true, message: '请选择更新评率' }],
})

// 提交
function handleSubmit() {
  formRef?.validate().then(() => (isUpdate ? handleUpdate() : handleCreate()))
}
// 新建
function handleCreate() {
  const params = pick({ ...form, update_rule: JSON.stringify(form.update_rule) }, [
    'name',
    'type',
    'industry',
    'update_status',
    'update_rule',
    'status',
  ])
  createStrategy(params).then(() => {
    ElMessage({ message: '创建成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
// 修改
function handleUpdate() {
  const params = pick(
    {
      ...form,
      time: form.time.join(','),
      update_rule: JSON.stringify(form.update_rule),
      tags_id: JSON.stringify(form.tags_id),
      groups_id: JSON.stringify(form.groups_id),
    },
    [
      'id',
      'name',
      'type',
      'industry',
      'update_status',
      'update_rule',
      'status',
      'target',
      'scene',
      'tags_id',
      'groups_id',
      'time',
      'connections_id',
    ]
  )
  updateStrategy(params).then(() => {
    ElMessage({ message: '修改成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}

const { post, messages, isLoading } = useChat()
watch(
  messages,
  () => {
    const lastMessage: any = messages.value[messages.value.length - 1]
    if (lastMessage && aiActive.value === 1) {
      form.target = lastMessage.content
    }
    if (lastMessage && aiActive.value === 2) {
      form.scene = lastMessage.content
    }
  },
  { deep: true }
)

const aiActive = ref(1)

function handleAIGenerate(index: number) {
  aiActive.value = index
  let content = ''
  // 商品卖点
  if (index === 1) {
    content = `我的运营策略行业是${getNameByValue(form.industry, industryList)}，策略类型为：${getNameByValue(
      form.type,
      typeList
    )}，请给出相应的策略目标`
  }
  if (index === 2) {
    content = `我的运营策略行业是${getNameByValue(form.industry, industryList)}，策略类型为：${getNameByValue(
      form.type,
      typeList
    )}，策略目标为：${form.target}，请给出适合的场景信息`
  }
  post({ role: 'user', content }, index === 3)
}
</script>

<template>
  <el-dialog :title="title" :close-on-click-modal="false" width="980px" @closed="$emit('update:modelValue', false)">
    <el-form ref="formRef" :model="form" :rules="rules" label-suffix="：" label-width="94px">
      <el-form-item label="策略名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="行业" prop="industry">
        <el-select v-model="form.industry" style="width: 100%" :disabled="isUpdate">
          <el-option v-for="item in industryList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="策略类型" prop="type">
        <el-select v-model="form.type" style="width: 100%" :disabled="isUpdate">
          <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="更新频率" prop="update_status">
        <el-radio-group v-model="form.update_status">
          <el-radio
            v-for="item in updateStatusRuleList"
            :key="item.value"
            :value="item.value"
            :disabled="item.value === '1'">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
        <div class="update-rule-wrap" v-if="form.update_status === '1'">
          <span>每</span>
          <el-select v-model="form.update_rule.type" placeholder=" " style="width: 60px">
            <el-option
              v-for="item in dateUnitList"
              :key="item.value"
              :label="item.label"
              :value="item.value"></el-option>
          </el-select>
          <template v-if="form.update_rule.type === 1">
            <span>的凌晨更新</span>
          </template>
          <template v-if="form.update_rule.type === 2">
            <span>的</span>
            <el-select v-model="form.update_rule.info" placeholder=" " style="width: 80px">
              <el-option v-for="item in weekList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
            <span>的凌晨更新</span>
          </template>
          <template v-if="form.update_rule.type === 3">
            <span>第</span>
            <el-select v-model="form.update_rule.info" placeholder=" " style="width: 60px">
              <el-option v-for="item in 6" :key="item" :label="item" :value="item"></el-option>
            </el-select>
            <span>天的凌晨更新</span>
          </template>
        </div>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" active-text="生效" active-value="1" inactive-text="失效" inactive-value="0" />
      </el-form-item>
      <template v-if="isUpdate">
        <el-tag style="margin: 20px 0">目标与场景</el-tag>
        <el-card shadow="never">
          <template #header>输入策略目标</template>
          <el-form-item prop="target" label-width="auto">
            <el-input
              type="textarea"
              v-model="form.target"
              :rows="6"
              placeholder="例如：提升新用户注册率20%，提升月活跃用户数15%，提升付费转化率5%等" />
          </el-form-item>
          <el-row justify="end">
            <el-button type="primary" @click="handleAIGenerate(1)" :loading="isLoading && aiActive === 1"
              >AI辅助梳理</el-button
            >
          </el-row>
        </el-card>
        <el-card shadow="never" style="margin-top: 20px">
          <template #header>输入策略场景</template>
          <el-form-item prop="scene" label-width="auto">
            <el-input
              type="textarea"
              v-model="form.scene"
              :rows="6"
              placeholder="例如：新用户首次访问APP第N日，用户连续N天未登录，用户将商品加入购物车但是3小时未支付。" />
          </el-form-item>
          <el-row justify="end">
            <el-button type="primary" @click="handleAIGenerate(2)" :loading="isLoading && aiActive === 2"
              >AI辅助梳理</el-button
            >
          </el-row>
        </el-card>
        <el-tag style="margin: 20px 0">目标人群</el-tag>
        <LabelRule v-model="form.tags_id" buttonText="添加标签">
          <template #header>请选择标签</template>
        </LabelRule>
        <GroupRule v-model="form.groups_id" buttonText="添加群组" style="margin-top: 20px">
          <template #header>请选择群组</template>
        </GroupRule>
        <el-tag style="margin: 20px 0">运营计划</el-tag>
        <el-form-item label="运营时间" prop="time">
          <el-date-picker v-model="form.time" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>

        <el-form-item label="运营渠道" prop="connections_id">
          <el-select v-model="form.connections_id">
            <el-option v-for="item in connectionList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <el-row justify="center">
        <el-button plain auto-insert-space @click="$emit('update:modelValue', false)">关闭</el-button>
        <el-button type="primary" auto-insert-space @click="handleSubmit">保存</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.update-rule-wrap {
  width: 100%;
  .el-select {
    margin: 0 10px;
  }
}
</style>
