<script setup lang="ts">
import type { UserAttrRule, RuleAttr } from '@/types'
import { UserFilled, Plus, CloseBold } from '@element-plus/icons-vue'
import { useUserAttr } from '@/composables/useAllData'
import { stringOperatorList, numberOperatorList, dateOperatorList } from '@/utils/dictionary'
import { searchMetaMemberAttrs } from '@/api/base'

// const userAttrRule = ref(inject('userAttrRule') as UserAttrRule)
const userAttrRule = defineModel<UserAttrRule>({ default: { current_logic_operate: 'and', items: [] } })

const { userAttrList } = useUserAttr()

// 获取逻辑运算符名称
function getLogicalName(value: 'and' | 'or') {
  return value === 'or' ? '或' : '且'
}

// 获取运算符列表
function getOperatorList(type: string) {
  if (type === '1') return stringOperatorList
  if (type === '2' || type === '3') return numberOperatorList
  if (type === '4' || type === '5') return dateOperatorList
  return stringOperatorList
}

// 切换逻辑运算符
function toggleOperate(rule: UserAttrRule) {
  rule.current_logic_operate = rule.current_logic_operate === 'or' ? 'and' : 'or'
}

// 添加条件
function handleAdd(items: RuleAttr[]) {
  items.push({ attr_id: '', attr: '', attr_name: '', attr_type: '', operate: '', operate_name: '', value: '' })
}

// 删除
function handleRemove(items: RuleAttr[], index: number) {
  items.splice(index, 1)
}

// 属性改变
function handleAttrChange(value: string, item: RuleAttr) {
  const found = userAttrList.value.find(item => item.id === value)
  item.attr = found?.english_name || ''
  item.attr_name = found?.name || ''
  item.attr_type = found?.type || ''
  // 清空条件数据
  item.operate = ''
  item.operate_name = ''
  item.value = ''
  remoteMethod(item)
}

// 条件改变
function handleOperateChange(value: string, item: RuleAttr) {
  const found = getOperatorList(item.attr_type).find(item => item.value === value)
  item.operate_name = found?.label || ''
  item.value = ''
  // 区间
  if (value === 'range') {
    item.value = { start: undefined, end: undefined }
  }
}

function querySearch(item: RuleAttr, search: string, cb: (arg: any) => void) {
  if (item.attr_id) {
    searchMetaMemberAttrs({ search, member_meta_id: item.attr_id, per_page: 100 }).then(res => {
      cb(res.data.list)
    })
  } else {
    cb([])
  }
}

const options = ref<{ label: string; value: string }[]>([])
const loading = ref(false)
function remoteMethod(item: RuleAttr, search: string = '') {
  options.value = []
  if (item.attr_id) {
    loading.value = true
    searchMetaMemberAttrs({ search, member_meta_id: item.attr_id, per_page: 100 }).then(res => {
      options.value = res.data.list.map((item: any) => {
        return { label: item.attr_value, value: item.attr_value }
      })
    })
    loading.value = false
  }
}
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <el-button circle color="#006df1" :icon="UserFilled"></el-button>
      用户属性满足以下条件
    </template>
    <div class="rule" v-if="userAttrRule.items.length">
      <div class="rule-operator">
        <span @click="toggleOperate(userAttrRule)">{{ getLogicalName(userAttrRule.current_logic_operate) }}</span>
      </div>
      <div class="rule-list">
        <el-row justify="space-between" class="rule-item" v-for="(item, index) in userAttrRule.items" :key="index">
          <div style="display: flex">
            <el-form-item>
              <el-select v-model="item.attr_id" @change="value => handleAttrChange(value, item)">
                <el-option v-for="option in userAttrList" :key="option.id" :label="option.name" :value="option.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="item.operate" @change="value => handleOperateChange(value, item)">
                <el-option
                  v-for="option in getOperatorList(item.attr_type)"
                  :key="option.value"
                  :label="option.alias || option.label"
                  :value="option.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="!['null', 'not null'].includes(item.operate)">
              <!-- 数字区间 -->
              <template v-if="['2', '3'].includes(item.attr_type) && item.operate === 'range'">
                <el-input-number step-strictly :controls="false" :min="0" v-model="item.value.start" />
                <el-input-number step-strictly :controls="false" :min="0" v-model="item.value.end" />
              </template>
              <!-- 日期区间 -->
              <template v-else-if="item.attr_type === '4' && item.operate === 'range'">
                <el-date-picker v-model="item.value.start" type="date" value-format="YYYY-MM-DD" />
                <el-date-picker v-model="item.value.end" type="date" value-format="YYYY-MM-DD" />
              </template>
              <!-- 时间区间 -->
              <template v-else-if="item.attr_type === '5' && item.operate === 'range'">
                <el-date-picker v-model="item.value.start" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width: 180px" />
                <el-date-picker v-model="item.value.end" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width: 180px" />
              </template>
              <template v-else-if="item.attr_type === '4' && (item.operate === 'after' || item.operate === 'before')">
                <el-date-picker v-model="item.value" type="date" value-format="YYYY-MM-DD" />
              </template>
              <template v-else-if="item.attr_type === '5' && (item.operate === 'after' || item.operate === 'before')">
                <el-date-picker v-model="item.value" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" style="width: 180px" />
              </template>
              <template v-else>
                <el-select
                  v-model="item.value"
                  filterable
                  remote
                  allow-create
                  :multiple="['in', 'not in'].includes(item.operate)"
                  :remote-method="(query:string) => remoteMethod(item, query)"
                  :loading="loading"
                  style="width: 320px"
                  v-if="['in', 'not in'].includes(item.operate)">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-autocomplete
                  v-model="item.value"
                  value-key="attr_value"
                  :fetch-suggestions="(query, cb) => querySearch(item, query, cb)"
                  style="width: 320px"
                  v-else />
              </template>
            </el-form-item>
          </div>
          <el-button text :icon="CloseBold" @click="handleRemove(userAttrRule.items, index)"></el-button>
        </el-row>
      </div>
    </div>
    <el-button text :icon="Plus" @click="handleAdd(userAttrRule.items)">添加属性</el-button>
  </el-card>
</template>

<style src="@/assets/styles/rule.scss"></style>
