<script setup lang="ts">
import { editReviewRule, getReviewRule, saveReviewRule, testRule } from '@/api/review'
import router from '@/router'
import { ElMessage } from 'element-plus'
import { debounce } from 'lodash-es'
import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'

const { query } = useRoute()

const disabledForm = ref(false)

const title = computed(() => {
  switch (query?.type) {
    case 'add':
      initFormData()
      return '新建'
    case 'edit':
      getRule()
      return '编辑'
    case 'view':
      getRule()
      disabledForm.value = true
      return '查看'
  }
})

const initFormData = () => {
  formData.value.review_plan_name = query?.reviewName
  formData.value.review_plan_id = query?.reviewId
}

const getRule = async () => {
  const data = await getReviewRule((query?.id as string))
  formData.value = data?.data
  initFormData();
  ruleId.value = query?.id as string;
}

const ruleId = ref<string>('')
const formDataRef: any = ref(null)
const formData: any = ref({
  name: '',
  risk_level: 0,
  review_plan_id: '',
  review_plan_name: '',
  content: ''
})
const saveLoading = ref<boolean>(false)

const saveRule = debounce(async () => {
  try {
    saveLoading.value = true;
    await formDataRef.value.validate()
    if (query?.type === 'add') {
      const { data } = await saveReviewRule(formData.value);
      ruleId.value = data?.id;
    }
    if (query?.type === 'edit') {
      await editReviewRule(ruleId.value, formData.value);
    }
    ElMessage.success('保存成功')
  } finally {
    saveLoading.value = false;
  }
}, 500)
const validationFormRef: any = ref(null)
const validationForm: any = ref({
  content: '',
  risk_level: null,
  originalText: '',
  revisionText: '',
  basisText: ''
})
const validateLoading = ref<boolean>(false)
const showValidateResult = ref<boolean>(false)
const validateContent = async () => {
  await formDataRef.value.validate()
  await validationFormRef.value.validate()
  try {
    validateLoading.value = true
    const result = await testRule(formData.value.content, validationForm.value.content)
    validationForm.value.risk_level = result.data?.risk_level
    validationForm.value.originalText = result.data?.content
    validationForm.value.revisionText = result.data?.suggestion
    validationForm.value.basisText = result.data?.basis
    showValidateResult.value = true
  } finally {
    validateLoading.value = false
  }
}
</script>

<template>
  <div class="rule-view">
    <div class="flex rule-view-header">
      <el-space>
        <el-icon class="pointer" @click="router.go(-1)">
          <ArrowLeftBold />
        </el-icon>
        {{ title }}规则
      </el-space>
    </div>
    <div class="rule-view-container flex">
      <div class="rule-view-container-left" v-loading="saveLoading">
        <el-form
          class="rule-view-container-left-content"
          :model="formData"
          ref="formDataRef"
          label-position="top"
          :disabled="disabledForm"
        >
          <el-form-item
            label="规则名称"
            prop="name"
            :rules="[{ required: true, message: '请输入规则名称', trigger: 'blur' }]"
          >
            <el-input
              v-model="formData.name"
              show-word-limit
              maxlength="100"
              placeholder="请输入规则名称"
            />
          </el-form-item>

          <el-form-item
            label="风险等级"
            prop="risk_level"
            :rules="[{ required: true, message: '请选择风险等级', trigger: 'blur' }]"
          >
            <el-switch v-model="formData.risk_level" :active-value="1" :inactive-value="0" />
            &nbsp;&nbsp;高风险
          </el-form-item>
          <el-form-item label="所属审核方案">
            <el-input v-model="formData.review_plan_name" disabled />
          </el-form-item>
          <el-form-item
            label="规则详情"
            prop="content"
            :rules="[{ required: true, message: '请输入规则详情', trigger: 'blur' }]"
          >
            <el-input
              v-model="formData.content"
              type="textarea"
              :rows="8"
              show-word-limit
              maxlength="1000"
              placeholder="请输入规则详情"
            />
          </el-form-item>
        </el-form>
        <div class="rule-view-container-left-footer">
          <el-button type="primary" @click="saveRule" :loading="saveLoading" :disabled="disabledForm">保存</el-button>
        </div>
      </div>
      <div class="rule-view-container-right" v-loading="validateLoading">
        <el-form
          class="rule-view-container-right-content"
          :model="validationForm"
          ref="validationFormRef"
          label-position="top"
          :disabled="disabledForm"
        >
          <el-form-item
            label="验证内容"
            prop="content"
            :rules="[{ required: true, message: '请输入验证内容', trigger: 'blur' }]"
          >
            <el-input
              v-model="validationForm.content"
              type="textarea"
              :rows="8"
              show-word-limit
              maxlength="1000"
              placeholder="请输入验证内容"
            />
          </el-form-item>
          <div class="validation-status" v-if="showValidateResult">
            <div class="risk-no"  v-if="validationForm.revisionText === ''">
              <el-icon style="margin-right: 4px">
                <Check />
              </el-icon>
              内容无风险
            </div>
            <div class="risk-yes" v-else>
              <div class="text-section original-text">
                <p class="title">合同原文</p>
                <p>{{ validationForm.originalText }}</p>
              </div>

              <div class="text-section revision">
                <p class="title">修订建议</p>
                <p>{{ validationForm.revisionText }}</p>
              </div>

              <div class="text-section basis">
                <p class="title">审查依据</p>
                <p>{{ validationForm.basisText }}</p>
              </div>
              <el-tag
                v-if="validationForm.risk_level === 1"
                type="danger"
                size="small"
                class="pointer"
                style="font-size: 10px; height: 20px"
                >高风险</el-tag
              >
            </div>
            <div class="close pointer" @click="showValidateResult = false">
              <el-icon><Remove /></el-icon>
            </div>
          </div>
        </el-form>
        <div class="rule-view-container-right-footer">
          <el-button type="primary" @click="validateContent" :loading="validateLoading" :disabled="!formData.content || !validationForm.content || disabledForm"
            >开始验证</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.rule-view {
  height: calc(100% - 80px);

  .flex {
    display: flex;
  }

  &-header {
    margin-bottom: 30px;
  }

  &-container {
    height: 100%;

    &-left,
    &-right {
      flex: 1;
      display: flex;
      flex-direction: column;

      &-content {
        flex: 1;
      }

      &-footer {
        text-align: right;
      }
    }

    &-left {
      padding-right: 40px;
      border-right: 2px solid rgba(0, 0, 0, 0.08);
    }

    &-right {
      padding-left: 40px;

      &-content {
        .validation-status {
          padding: 1px;
          border-radius: 8px;
          background: radial-gradient(
            circle,
            rgba(48, 103, 239, 1),
            rgba(140, 81, 242, 1),
            rgba(48, 103, 239, 1),
            rgba(173, 211, 249, 1)
          );
          position: relative;

          .risk-no {
            background: #fff;
            border-radius: 8px;
            font-weight: 500;
            font-size: 14px;
            color: #3067ef;
            z-index: 102;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
          }

          .risk-yes {
            padding: 12px 10px;
            background: #fff;
            border-radius: 8px;

            .text-section {
              margin-bottom: 10px;
              font-weight: 500;
              font-size: 12px;
              line-height: 22px;

              .title {
                font-weight: bold;
                color: #191919 !important;
              }

              &.original-text,
              &.basis {
                color: #797979;
              }

              &.revision p {
                color: #e24141;
              }
            }
          }

          .close {
            position: absolute;
            right: 10px;
            top: 10px;
          }
        }
      }
    }
  }
}
</style>
