<!-- 组件数据规则 -->
<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { SuccessFilled, CircleCloseFilled } from '@element-plus/icons-vue'
import { useQueryUser } from '../composables/useQueryUser'

interface Props {
  title?: string
  model?: any
  node: any
  step?: boolean
  paramsParse?: (data: any, form: any) => any
  generateParse?: (data: any, form: any) => any
  onSubmit?: (form: any) => void
}

const props = withDefaults(defineProps<Props>(), { title: '配置数据生成规则', step: false })

const formRef = ref<FormInstance>()
const form = reactive({
  user_total: undefined,
  expected_user_total: undefined,
  correct_operation_type: 1,
  correct_operation_rule: 1,
  correct_operation_method: 1,
  correct_operation_method_value: undefined,
  correct_operation_method_fail_value: undefined,
  error_operation_type: 1,
  error_operation_rule: 1,
  error_operation_method: 1,
  error_operation_method_value: undefined,
  error_operation_method_fail_value: undefined
})

// 满足答案的用户数
const expectedUserTotalText = computed(() => {
  return form.expected_user_total ?? '--'
})

// 操作正确用户数
const correctUserTotalText = computed(() => {
  if (form.correct_operation_type === 2) {
    return form.correct_operation_method === 1
      ? ((form.expected_user_total ?? 0) * (form.correct_operation_method_value ?? 0)) / 100
      : form.correct_operation_method_value
  } else {
    return form.expected_user_total
  }
})

// 操作错误用户数
const errorUserTotalText = computed(() => {
  return form.error_operation_type === 3 ? 0 : '实际判断结果计算'
})

watchEffect(() => {
  Object.assign(form, props.model, props.node.data.rule)
})

const { total, expectedTotal, prevNodeRule, prevNodeExpectedTotal, query } = useQueryUser(props.node)

watchEffect(() => {
  form.user_total = total.value
})

watch(expectedTotal, value => {
  form.expected_user_total = value
})

const stepActive = ref(0)
const stepMaxNum = ref(2)

// 上一步
function handlePrev() {
  stepActive.value--
}
// 下一步
function handleNext() {
  stepActive.value++
}
// 保存
async function handleSubmit() {
  props.onSubmit ? props.onSubmit(form) : await formRef.value?.validate().then(updateNode)
}

function updateNode() {
  if (!props.node) return
  const params = props.paramsParse ? props.paramsParse(props.node.data.teacher, form) : {}
  const generate = props.generateParse ? props.generateParse(props.node.data.teacher, form) : {}
  Object.assign(props.node.data, {
    rule: {
      ...form,
      correct_operation_user_total: correctUserTotalText.value,
      error_operation_user_total: errorUserTotalText.value
    },
    rule_params: params,
    generate: generate
  })
}

// 计算中
const isCalculating = ref(false)
// 计算
async function handleCalculate() {
  updateNode()
  isCalculating.value = true
  try {
    await query()
  } catch (error) {
    console.error(error)
  }
  isCalculating.value = false
  form.expected_user_total = expectedTotal.value
}
</script>

<template>
  <el-dialog :title="title" append-to-body width="800px" class="rule-template">
    <slot :model="form">
      <el-form ref="formRef" :model="form" label-suffix="：">
        <slot name="header">
          <el-row justify="space-between">
            <slot name="header-form-prepend" :model="form"></slot>
            <el-form-item label="组件名称">{{ node.data.name }}</el-form-item>
            <el-form-item label="组件答案"><slot name="header-answer" :model="form" /></el-form-item>
            <slot name="header-form-append" :model="form"></slot>
          </el-row>
        </slot>
        <el-tabs v-if="step" v-model="stepActive" stretch type="border-card">
          <el-tab-pane label="STEP 1：计算初始化数据量" :name="0">
            <slot name="step1">
              <!-- 触发条件 -->
              <el-row justify="center" style="padding: 40px 0">
                <el-form label-suffix="：" label-width="160px">
                  <el-form-item label="用户总数">
                    <span class="rule-num">{{ form.user_total }}</span>
                  </el-form-item>
                  <slot name="step1-append"></slot>
                  <el-form-item label="满足答案的用户总数" v-if="node.data.type === 1">
                    <span class="rule-num">{{ expectedUserTotalText }}</span>
                    <el-button type="primary" :loading="isCalculating" @click="handleCalculate">计算</el-button>
                  </el-form-item>
                  <el-form-item label="上一节点用户总数" v-else>
                    <div>
                      <p class="rule-num">正确：{{ prevNodeRule.correct_operation_user_total || prevNodeRule.expected_user_total }}</p>
                      <p class="rule-num">错误：{{ prevNodeRule.correct_operation_user_total || 0 }}</p>
                    </div>
                    <!-- <el-button type="primary" :loading="isCalculating" @click="handleCalculate">计算</el-button> -->
                  </el-form-item>
                </el-form>
              </el-row>
            </slot>
          </el-tab-pane>
          <el-tab-pane label="STEP 2：配置生成规则" :name="1">
            <slot name="step2">
              <!-- 触发条件 -->
              <template v-if="node.data.type === 1">
                <header class="rule-result-header">
                  <p>用户总数：{{ form.user_total }}</p>
                  <p>满足答案的用户总数：{{ expectedUserTotalText }}</p>
                </header>
                <section class="rule-result-body">
                  <div class="rule-result-col">
                    <p class="rule-result-tips">
                      <el-icon class="is-success"><SuccessFilled /></el-icon>操作正确，选取数据数量：
                    </p>
                    <el-form-item>
                      <el-radio-group v-model="form.correct_operation_type">
                        <el-radio :value="1">全部数据</el-radio>
                        <el-radio :value="2">部分数据</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <template v-if="form.correct_operation_type === 2">
                      <el-form-item label="选取规则">
                        <el-radio-group v-model="form.correct_operation_rule">
                          <el-radio :value="1">随机</el-radio>
                        </el-radio-group>
                      </el-form-item>
                      <el-form-item label="选取方式">
                        <el-radio-group v-model="form.correct_operation_method">
                          <el-radio :value="1">百分比</el-radio>
                          <el-radio :value="2">数值</el-radio>
                        </el-radio-group>
                      </el-form-item>
                      <el-form-item label="请输入">
                        <template v-if="form.correct_operation_method === 1">
                          <el-input-number v-model="form.correct_operation_method_value" :controls="false" :max="100" />
                          &nbsp;%
                        </template>
                        <el-input-number v-model="form.correct_operation_method_value" :controls="false" :max="form.expected_user_total" v-else />
                      </el-form-item>
                    </template>
                  </div>
                  <el-divider direction="vertical" style="height: auto" />
                  <div class="rule-result-col">
                    <p class="rule-result-tips">
                      <el-icon class="is-error"><CircleCloseFilled /></el-icon>操作错误，根据实际操作结果选取数据数量：
                    </p>
                    <el-form-item>
                      <el-radio-group v-model="form.error_operation_type">
                        <el-radio :value="1">全部数据</el-radio>
                        <el-radio :value="2">部分数据</el-radio>
                        <el-radio :value="3">不选取</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <template v-if="form.error_operation_type === 2">
                      <el-form-item label="选取规则">
                        <el-radio-group v-model="form.error_operation_rule">
                          <el-radio :value="1">随机</el-radio>
                        </el-radio-group>
                      </el-form-item>
                      <el-form-item label="选取方式">
                        <el-radio-group v-model="form.error_operation_method">
                          <el-radio :value="1">百分比</el-radio>
                          <el-radio :value="2">数值</el-radio>
                        </el-radio-group>
                      </el-form-item>
                      <el-form-item label="请输入">
                        <template v-if="form.error_operation_method === 1">
                          <el-input-number v-model="form.error_operation_method_value" :controls="false" :max="100" />
                          &nbsp;%
                        </template>
                        <el-input-number v-model="form.error_operation_method_value" :controls="false" :max="form.expected_user_total" v-else />
                      </el-form-item>
                    </template>
                  </div>
                </section>
              </template>

              <!-- 营销动作 -->
              <template v-if="node.data.type === 2">
                <header class="rule-result-header">
                  <p>用户总数：{{ form.user_total }}</p>
                  <p>上一节点用户总数：{{ prevNodeExpectedTotal }}</p>
                  <slot name="step-header-append"></slot>
                </header>
                <section class="rule-result-body">
                  <div class="rule-result-col">
                    <p class="rule-result-tips">
                      <el-icon class="is-success"><SuccessFilled /></el-icon>操作正确，选取数据数量：
                    </p>
                    <el-form-item label="选取规则">
                      <el-radio-group v-model="form.correct_operation_rule">
                        <el-radio :value="1">随机</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="选取方式">
                      <el-radio-group v-model="form.correct_operation_method">
                        <el-radio :value="1">百分比</el-radio>
                        <el-radio :value="2">数值</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <template v-if="form.correct_operation_method === 1">
                      <el-form-item label="成功">
                        <el-input-number v-model="form.correct_operation_method_value" :controls="false" :max="100" />
                        &nbsp;%
                      </el-form-item>
                      <el-form-item label="失败">
                        <el-input-number v-model="form.correct_operation_method_fail_value" :controls="false" :max="100" />
                        &nbsp;%
                      </el-form-item>
                    </template>
                    <template v-else>
                      <el-form-item label="成功">
                        <el-input-number v-model="form.correct_operation_method_value" :controls="false" />
                      </el-form-item>
                      <el-form-item label="失败">
                        <el-input-number v-model="form.correct_operation_method_fail_value" :controls="false" />
                      </el-form-item>
                    </template>
                  </div>
                  <el-divider direction="vertical" style="height: auto" />
                  <div class="rule-result-col">
                    <p class="rule-result-tips">
                      <el-icon class="is-error"><CircleCloseFilled /></el-icon>操作错误，选取数据数量：
                    </p>
                    <el-form-item label="选取规则">
                      <el-radio-group v-model="form.error_operation_rule">
                        <el-radio :value="1">随机</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="选取方式">
                      <el-radio-group v-model="form.error_operation_method">
                        <el-radio :value="1">百分比</el-radio>
                        <el-radio :value="2">数值</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <template v-if="form.error_operation_method === 1">
                      <el-form-item label="成功">
                        <el-input-number v-model="form.error_operation_method_value" :controls="false" :max="100" />
                        &nbsp;%
                      </el-form-item>
                      <el-form-item label="失败">
                        <el-input-number v-model="form.error_operation_method_fail_value" :controls="false" :max="100" />
                        &nbsp;%
                      </el-form-item>
                    </template>
                    <template v-else>
                      <el-form-item label="成功">
                        <el-input-number v-model="form.error_operation_method_value" :controls="false" />
                      </el-form-item>
                      <el-form-item label="失败">
                        <el-input-number v-model="form.error_operation_method_fail_value" :controls="false" />
                      </el-form-item>
                    </template>
                  </div>
                </section>
              </template>

              <!-- 条件判断 -->
              <template v-if="node.data.type === 3">
                <header class="rule-result-header">
                  <p>用户总数：{{ form.user_total }}</p>
                  <p v-if="node.data.type === 1">满足答案的用户总数：{{ expectedUserTotalText }}</p>
                  <p v-else>上一节点用户总数：{{ prevNodeExpectedTotal }}</p>
                </header>
                <slot name="step-body-after"></slot>
                <slot name="step2-body">
                  <section class="rule-result-body">
                    <div class="rule-result-col">
                      <p class="rule-result-tips">
                        <el-icon class="is-success"><SuccessFilled /></el-icon>操作正确，选取数据数量：
                      </p>
                      <el-form-item label="满足判断条件数据">
                        <el-radio :model-value="1" :value="1">根据实际判断结果计算</el-radio>
                      </el-form-item>
                      <el-form-item label="不满足判断条件数据">
                        <el-radio :model-value="1" :value="1">根据实际判断结果计算</el-radio>
                      </el-form-item>
                    </div>
                    <el-divider direction="vertical" style="height: auto" />
                    <div class="rule-result-col">
                      <p class="rule-result-tips">
                        <el-icon class="is-error"><CircleCloseFilled /></el-icon>操作错误，选取数据数量：
                      </p>
                      <el-form-item label="满足判断条件数据">
                        <el-radio :model-value="1" :value="1">根据实际判断结果计算</el-radio>
                      </el-form-item>
                      <el-form-item label="不满足判断条件数据">
                        <el-radio :model-value="1" :value="1">根据实际判断结果计算</el-radio>
                      </el-form-item>
                    </div>
                  </section>
                </slot>
              </template>
            </slot>
          </el-tab-pane>
          <el-tab-pane label="STEP 3：预期数据量计算" :name="2">
            <slot name="step3">
              <!-- 触发条件 -->
              <template v-if="node.data.type === 1">
                <header class="rule-result-header">
                  <p>用户总数：{{ form.user_total }}</p>
                  <p>满足答案的用户总数：{{ expectedUserTotalText }}</p>
                </header>
                <section class="rule-result-body">
                  <div class="rule-result-col">
                    <p class="rule-result-tips">
                      <el-icon class="is-success"><SuccessFilled /></el-icon>操作正确，选取数据数量：
                    </p>
                    <p class="rule-num is-center">{{ correctUserTotalText }}</p>
                  </div>
                  <el-divider direction="vertical" style="height: auto" />
                  <div class="rule-result-col">
                    <p class="rule-result-tips">
                      <el-icon class="is-error"><CircleCloseFilled /></el-icon>操作错误，根据实际操作结果选取数据数量：
                    </p>
                    <p class="rule-num is-center">{{ errorUserTotalText }}</p>
                  </div>
                </section>
              </template>

              <!-- 营销动作 -->
              <template v-if="node.data.type === 2">
                <header class="rule-result-header">
                  <p>用户总数：{{ form.user_total }}</p>
                  <p>上一节点用户总数：{{ prevNodeExpectedTotal }}</p>
                  <slot name="step-header-append"></slot>
                </header>
                <section class="rule-result-body">
                  <div class="rule-result-col">
                    <p class="rule-result-tips">
                      <el-icon class="is-success"><SuccessFilled /></el-icon>操作正确，选取数据数量：
                    </p>
                    <el-form-item label="成功"></el-form-item>
                    <el-form-item label="失败"> </el-form-item>
                  </div>
                  <el-divider direction="vertical" style="height: auto" />
                  <div class="rule-result-col">
                    <p class="rule-result-tips">
                      <el-icon class="is-error"><CircleCloseFilled /></el-icon>操作错误，选取数据数量：
                    </p>
                    <el-form-item label="成功"> </el-form-item>
                    <el-form-item label="失败"> </el-form-item>
                  </div>
                </section>
                <el-row justify="center" style="margin-top: 20px">
                  <el-button type="primary" :loading="isCalculating" @click="handleCalculate">计算</el-button>
                </el-row>
              </template>

              <!-- 条件判断 -->
              <template v-if="node.data.type === 3">
                <header class="rule-result-header">
                  <p>用户总数：{{ form.user_total }}</p>
                  <p>上一节点用户总数：{{ prevNodeExpectedTotal }}</p>
                </header>
                <slot name="step-body-after"></slot>
                <slot name="step3-body">
                  <section class="rule-result-body">
                    <div class="rule-result-col">
                      <p class="rule-result-tips">
                        <el-icon class="is-success"><SuccessFilled /></el-icon>操作正确，选取数据数量：
                      </p>
                      <el-form-item label="满足判断条件数据">{{ form.expected_user_total }}</el-form-item>
                      <el-form-item label="不满足判断条件数据">
                        {{ Math.max(prevNodeExpectedTotal - (form.expected_user_total || 0), 0) }}
                      </el-form-item>
                    </div>
                    <el-divider direction="vertical" style="height: auto" />
                    <div class="rule-result-col">
                      <p class="rule-result-tips">
                        <el-icon class="is-error"><CircleCloseFilled /></el-icon>操作错误，选取数据数量：
                      </p>
                      <el-form-item label="满足判断条件数据">
                        <el-radio :model-value="1" :value="1">根据实际判断结果计算</el-radio>
                      </el-form-item>
                      <el-form-item label="不满足判断条件数据">
                        <el-radio :model-value="1" :value="1">根据实际判断结果计算</el-radio>
                      </el-form-item>
                    </div>
                  </section>
                </slot>
                <el-row justify="center" style="margin-top: 20px">
                  <el-button type="primary" :loading="isCalculating" @click="handleCalculate">计算</el-button>
                </el-row>
              </template>
            </slot>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </slot>
    <template #footer>
      <el-row justify="center" v-if="step">
        <el-button plain auto-insert-space @click="$emit('update:modelValue', false)" v-if="stepActive === 0">关闭</el-button>
        <el-button plain auto-insert-space @click="handlePrev" v-if="stepActive >= 1">上一步</el-button>
        <el-button type="primary" auto-insert-space @click="handleNext" v-if="stepActive < stepMaxNum">下一步</el-button>
        <el-button type="primary" auto-insert-space @click="handleSubmit().then(() => $emit('update:modelValue', false))" v-if="stepActive === stepMaxNum">
          保存
        </el-button>
      </el-row>
      <el-row justify="center" v-else>
        <el-button plain auto-insert-space @click="$emit('update:modelValue', false)">关闭</el-button>
        <el-button type="primary" auto-insert-space @click="handleSubmit().then(() => $emit('update:modelValue', false))"> 保存 </el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.rule-template {
  .el-form-item {
    margin-bottom: 10px;
  }
  .rule-num {
    margin-right: 20px;
    font-size: 20px;
    font-weight: bold;
    color: var(--main-color);
  }
  .rule-result-header {
    padding: 10px 0;
    margin-bottom: 30px;
    display: flex;
    justify-content: space-around;
    color: #9a9a9a;
    border-bottom: 1px solid #dcdfe6;
  }
  .rule-result-body {
    display: flex;
    column-gap: 20px;
  }
  .rule-result-col {
    flex: 1;
    padding: 10px 0;
  }
  .rule-result-tips {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    white-space: nowrap;
    .el-icon {
      font-size: 20px;
      margin-right: 5px;
    }
  }
  .is-center {
    text-align: center;
  }
  .is-success {
    color: #81b337;
  }
  .is-error {
    color: #aa0231;
  }
  .is-answer {
    color: #81b337;
  }
  .is-operate {
    color: blue;
  }
}
</style>
