<script setup>
import { apiRiskLevelRelationShip,apiRiskLevelProduct } from '@/api/riskLevel'

const show = defineModel('show', { type: Boolean, default: false })

const props = defineProps({
  editData: {
    type: [Object, null],
    default: null
  }
})
const emits=defineEmits(['success'])

watch(
  ()=>show.value,
  (n)=>{
    if(n&&props.editData){
      formState.riskLevel=props.editData.riskLevel
    }
    if(n){
      getProductRiskLevelOpts()
    }
  }
)


// 产品风险等级选项
let productLevelOpts=[]
async function getProductRiskLevelOpts() {
  const res = await apiRiskLevelRelationShip.productRiskLevelOpts()
  if (res.Ret === 200) {
    const arr = res.Data.List || []
    productLevelOpts=arr.map(item=>{
      return {
        ...item,
        value:item.RiskName
      }
    })
  }
}

const formRef=ref(null)
const formRules = {
  riskLevel: [
    { required: true, message: '请选择产品风险等级', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const regex = /^R\d+$/;
        if (!regex.test(value)) {
          callback(new Error('输入的值必须是 R 加数字，并且不能包含空格'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
}
const formState = reactive({
  riskLevel: ''
})

function querySearch(queryString, cb) {
  const validLevels = productLevelOpts; // 可用的选项
  cb(validLevels)
}

async function handleSave() {
  await formRef.value.validate()
  const params={
    Id:props.editData.id,
    RiskLevel:formState.riskLevel
  }
  const res=await apiRiskLevelProduct.setRiskLevel(params)
  if(res.Ret!==200) return
  ElMessage.success('设置成功');
  show.value=false
  emits('success')
}

</script>

<template>
  <el-dialog
    v-model="show"
    width="500"
    title="设置风险等级 "
    draggable
  >
    <el-form
      ref="formRef"
      :model="formState"
      :rules="formRules"
      class="form-box"
      label-width="80px"
      hide-required-asterisk
    >
      <el-form-item prop="permission" label="品种">
        <span>{{props.editData.parentLabel}}</span>
      </el-form-item>
      <el-form-item prop="riskLevel" label="风险等级">
        <el-autocomplete
          v-model="formState.riskLevel"
          :fetch-suggestions="querySearch"
          placeholder="请选择产品风险等级"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="footer-wrap">
        <el-button type="primary" plain size="large" @click="show = false"
          >取消</el-button
        >
        <el-button type="primary" size="large" @click="handleSave"
          >保存</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>