<!--
 * @description: 编辑指标规则
 * @fileName: EditRule
 * @author: 17076
 * @date: 2024/6/14-上午10:43
 * @version: V1.0.0
-->

<template>
  <cs-drawer
    :drawer-option="drawerOption"
    @onReset="handleReset"
    @onSubmit="handleSubmit"
  >
    <div slot="content">
      <el-steps :active="activeStep" align-center>
        <el-step title="指标基础信息" description="设置指标名称及原子指标项目" />
        <el-step title="指标规则" description="模型按规则分析案件指标" />
      </el-steps>
      <el-form
        v-if="activeStep === 0"
        ref="form"
        :model="ruleForm"
        :rules="rules"
        label-width="90px"
        style="margin-top: 20px"
      >
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="指标名称" prop="name">
              <el-input v-model="ruleForm['name']" placeholder="请输入指标名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="指标简称" prop="shortName">
              <el-input v-model="ruleForm['shortName']" placeholder="请输入指标简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="指标分数" prop="indexScore">
              <el-input v-model="ruleForm['indexScore']" placeholder="请输入指标分数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="指标类型" prop="indexType">
              <el-select v-model="ruleForm['indexType']" placeholder="请选择指标类型" @change="handleChange">
                <el-option v-for="item in indexTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="案件类型" prop="caseType">
              <el-select v-model="ruleForm['caseType']" placeholder="请选择案件类型" multiple>
                <el-option v-for="item in caseTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="原子指标" prop="atomicIndexList">
              <el-button type="primary" @click="handleSelectAtomic">请选择</el-button>
              <!-- <span
                v-if="ruleForm['atomicIndexList'] && ruleForm['atomicIndexList'].length > 0"
                style="margin-left: 10px; font-size: 12px; color: #0A4DF0"
              >
                {{ `已选中${ruleForm['atomicIndexList'].length}项原子指标` }}
              </span> -->
              <div v-if="ruleForm['atomicIndexList'] && ruleForm['atomicIndexList'].length > 0" class="select_list">
                <div v-for="(item,index) in ruleForm['atomicIndexList']" :key="index" class="select_list_item">
                  <span>{{ item.name }}</span>
                  <i class="el-icon-circle-close  closed" style="margin-left: 12px;" @click="delItem(index)" />
                </div>

              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="指标说明" prop="remark">
              <el-input v-model="ruleForm['remark']" type="textarea" :rows="5" placeholder="请输入指标说明" />
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-form-item label="判断逻辑" prop="judgeLogic">-->
        <!--          <template>-->
        <!--            <div class="flex-row">-->
        <!--              <el-select v-model="ruleForm['judgeLogic']" placeholder="请选择判断逻辑">-->
        <!--                <el-option-->
        <!--                  v-for="item in judgmentLogicOptions"-->
        <!--                  :key="item.value"-->
        <!--                  :label="item.label"-->
        <!--                  :value="item.value"-->
        <!--                />-->
        <!--              </el-select>-->
        <!--              <el-button type="primary" plain style="margin-left: 10px" @click="handleCustom">自定义</el-button>-->
        <!--            </div>-->
        <!--            <span style="color: #999999; font-size: 12px">支持原子指标的逻辑运算（and,or,not）,并可自定义指标关系</span>-->
        <!--          </template>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="指标规则" prop="indexRules">-->
        <!--          <el-checkbox-group v-model="ruleForm['indexRules']">-->
        <!--            <el-checkbox-->
        <!--              v-for="item in indexRulesOption"-->
        <!--              :key="item.value"-->
        <!--              :label="item.label"-->
        <!--              :true-label="1"-->
        <!--              :false-label="0"-->
        <!--            />-->
        <!--          </el-checkbox-group>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="必要证据" prop="necessaryEvidence">-->
        <!--          <el-select v-model="ruleForm['necessaryEvidence']" placeholder="请选择必要证据" multiple>-->
        <!--            <el-option v-for="item in evidenceOptions" :key="item.value" :label="item.label" :value="item.value" />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
      </el-form>
      <div v-if="activeStep === 1">
        <p>{{ `[${indexTypeName}] ${ruleForm['name']}` }}</p>
        <custom-logic ref="custom" :is-change="isChange" :atomic-index-data="ruleForm['atomicIndexList']" :judge-logic="ruleForm['judgeLogic']" />
      </div>
      <!--原子指标选择-->
      <select-atomic ref="select" @submit="handleAtomicSubmit" />
    </div>
    <div slot="footer">
      <el-button type="primary" plain style="width: 150px" @click="handleReset">重 置</el-button>
      <el-button v-if="activeStep === 0" type="primary" style="width: 150px" @click="nextStep">下一步</el-button>
      <el-button v-if="activeStep === 1" type="primary" plain style="width: 150px" @click="lastStep">上一步</el-button>
      <el-button v-if="activeStep === 1" type="primary" style="width: 150px" @click="handleSubmit">确 定</el-button>
    </div>
  </cs-drawer>
</template>

<script>
import SelectAtomic from '@/views/ruleEngine/indexRule/components/SelectAtomic.vue'
import CustomLogic from '@/views/ruleEngine/indexRule/components/CustomLogic.vue'
import { addOrUpdIndex } from '@/api/indexRule'

export default {
  name: 'EditRule',
  components: { CustomLogic, SelectAtomic },
  data() {
    return {
      drawerOption: {
        show: false,
        width: '45%',
        title: '指标配置'
      },
      // 当前激活的步骤
      activeStep: 0,
      // 案件类型数据
      caseTypeOptions: JSON.parse(sessionStorage.getItem('case_type')),
      // 指标类型数据
      indexTypeOptions: JSON.parse(sessionStorage.getItem('index_type')),
      // 指标类型名称保存
      indexTypeName: '',
      // 必要证据
      evidenceOptions: [],
      // 判断逻辑
      judgmentLogicOptions: JSON.parse(sessionStorage.getItem('judge_logic')),
      // 指标规则数据
      indexRulesOption: [
        { label: '证据判断', value: 'evidenceJudge' },
        { label: '笔录判断', value: 'recordJudge' },
        { label: '外部数据', value: 'externalData' }
      ],
      // 规则配置表单
      ruleForm: {},
      rules: {
        name: [{ required: true, message: '指标名称不能为空!', trigger: 'blur' }],
        caseType: [{ required: true, message: '案件类型不能为空!', trigger: 'blur' }],
        indexType: [{ required: true, message: '指标类型不能为空!', trigger: 'blur' }],
        indexScore: [{ required: true, message: '指标分数不能为空!', trigger: 'blur' }, {
          pattern: /^-?\d+(\.\d+)?$/,
          message: '请输入正确格式',
          trigger: 'change'
        }],
        // indexRules: [{ required: true, message: '指标规则不能为空!', trigger: 'blur' }],
        atomicIndex: [{ required: true, message: '原子指标不能为空!', trigger: 'blur' }],
        judgeLogic: [{ required: true, message: '指标说明不能为空!', trigger: 'blur' }]
      },
      // 是否是编辑
      isEdit: false,
      // 是否修改过
      isChange: false
    }
  },
  methods: {
    // 显示弹窗
    show(data, isEdit) {
      this.activeStep = 0
      this.isEdit = isEdit
      this.drawerOption.show = true
      this.isChange = false
      this.$nextTick(() => {
        const _this = this
        _this.ruleForm = isEdit ? JSON.parse(JSON.stringify(data)) : {}
        if (isEdit && _this.$baseLodash.isString(_this.ruleForm['caseType'])) {
          _this.ruleForm.caseType = _this.ruleForm.caseType.split(',')
        }
        if (_this.isEdit) {
          _this.indexTypeName = _this.ruleForm.indexTypeName
        }
      })
    },
    delItem(index) {
      this.ruleForm['atomicIndexList'].splice(index, 1)
      this.isChange = true
    },
    // 指标类型选择
    handleChange(val) {
      this.indexTypeName = this.indexTypeOptions.find(item => item.value === val).label
    },
    // 选择原子指标
    handleSelectAtomic() {
      this.$refs.select.show(this.ruleForm['atomicIndexList'])
    },
    // 原子指标选择
    handleAtomicSubmit(data) {
      this.$refs.form.clearValidate('atomicIndexList')
      this.$set(this.ruleForm, 'atomicIndexList', data)
      this.isChange = true
    },
    // 重置
    handleReset() {
      this.$refs.form.resetFields()
      this.$refs.form.clearValidate()
    },
    // 下一步
    nextStep() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.activeStep = 1
        }
      })
    },
    // 上一步
    lastStep() {
      this.activeStep = 0
    },
    // 确定
    async handleSubmit() {
      // 拿到对应原子指标逻辑
      const logicData = this.$refs.custom.validate()
      if (logicData) {
        this.$set(this.ruleForm, 'judgeLogic', JSON.stringify(logicData))
      }
      if (this.$baseLodash.isArray(this.ruleForm['caseType'])) {
        this.ruleForm['caseType'] = this.ruleForm['caseType'].join(',')
      }
      const { code, msg } = await addOrUpdIndex(this.ruleForm)
      code === 200 ? (this.isEdit ? this.$baseMessage.success(msg || '编辑成功!') : this.$baseMessage.success(msg || '新增成功!')) : (this.isEdit ? this.$baseMessage.error(msg || '新增失败!') : this.$baseMessage.error(msg || '新增失败!'))
      this.drawerOption.show = false
      this.$emit('reloadData')
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep {
  .el-select {
    width: 100%;
  }
}
.select_list {
  display: flex;
  flex-direction: column;
  .select_list_item {
    display: flex;
    align-items: center;
    .closed {
      cursor: pointer;
    }
  }
}
</style>
