<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-row>
              <el-form-item label="规则名称" prop="rulesName">
                <el-input v-model="queryParams.rulesName" placeholder="请输入规则名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="规则描述" prop="description">
                <el-input v-model="queryParams.description" placeholder="请输入规则描述" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="规则状态" prop="state">
                <el-select v-model="queryParams.state" placeholder="请输入规则状态">
                  <el-option v-for="dict in rule_mian_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="决策类型" prop="decisionType">
                <el-select v-model="queryParams.decisionType" placeholder="请输入决策类型">
                  <el-option v-for="dict in rule_decision_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-form-item style="margin-left: 20px">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['rule:main:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="mainList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="规则名称" align="center" prop="rulesName" />
        <el-table-column label="规则描述" align="center" prop="description" />
        <el-table-column label="决策类型" align="center" prop="decisionType">
          <template #default="scope">
            <dict-tag :options="rule_decision_type" :value="scope.row.decisionType" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="state" >
          <template #default="scope">
            <dict-tag :options="rule_mian_state" :value="scope.row.state" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['rule:main:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="调整入参" placement="top">
              <el-button v-hasPermi="['rule:parameter:addParameter']" link type="primary" icon="BottomRight" @click="handleOpenParms(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="决策维护" placement="top">
              <el-button v-hasPermi="['rule:parameter:toDecisionTree']" link type="primary" icon="Position" @click="toDecisionTree(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除规则" placement="top">
              <el-button v-hasPermi="['rule:parameter:deleteTree']" link type="primary" icon="Delete" @click="DeleteTree(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="规则送审" placement="top">
              <el-button v-hasPermi="['rule:parameter:toAudit']" link type="primary" icon="Check" @click="toAudit(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改规则信息主体对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="900px" append-to-body>
      <el-card shadow="never">
        <el-form ref="mainFormRef" :model="form" :rules="rules" :inline="true" label-width="80px">
          <el-form-item label="规则名称" prop="rulesName">
            <el-input v-model="form.rulesName" placeholder="请输入规则名称" maxlength="30" show-word-limit />
          </el-form-item>
          <el-form-item label="决策类型" prop="decisionType">
            <el-select v-model="form.decisionType" placeholder="请输入决策类型">
              <el-option v-for="dict in rule_decision_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="规则描述" prop="description">
            <el-input v-model="form.description" type="textarea" :rows="4" style="width: 580px" placeholder="请输入内容" maxlength="100" show-word-limit/>
          </el-form-item>
        </el-form>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 补充入参对话框 -->
    <el-dialog v-model="parmsDialog.visible" :title="parmsDialog.title" width="900px" append-to-body>
      <el-card shadow="never">
        <el-table v-loading="parmsloading" :data="parmsList">
          <el-table-column label="参数" align="center" prop="fieldName">
            <template #default="scope">
              <el-input v-model="scope.row.fieldName" placeholder="请输入参数" maxlength="20" show-word-limit />
            </template>
          </el-table-column>
          <el-table-column label="参数类型" align="center" prop="fieldType" >
            <template #default="scope">
              <el-select v-model="scope.row.fieldType" placeholder="请输入参数类型">
                <el-option v-for="dict in rule_parms_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="参数解释" align="center" prop="fieldDescription">
            <template #default="scope">
              <el-input v-model="scope.row.fieldDescription" placeholder="请输入参数解释" maxlength="100" show-word-limit/>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="success" icon="Plus" @click="addRow" />
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitParmsForm">确 定</el-button>
          <el-button @click="cancelParms">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Main" lang="ts">
import {
  listMain,
  getMain,
  addMain,
  updateMain,
  getParms,
  addParms,
  deleteRule,
  ruleToAudit
} from '@/api/rule/definition';
import { MainVO, MainQuery, MainForm } from '@/api/rule/definition/mian_types';
import { InputParameterVO } from '@/api/rule/definition/parms_types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { rule_mian_state } = toRefs<any>(proxy?.useDict('rule_mian_state'));
const { rule_decision_type } = toRefs<any>(proxy?.useDict('rule_decision_type'));
const { rule_parms_type } = toRefs<any>(proxy?.useDict('rule_parms_type'));


const mainList = ref<MainVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const mainFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const ruleId = ref<string | number>('');

const parmsDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const parmsloading = ref(false);
const parmsList = ref<InputParameterVO[]>([]);

const initFormData: MainForm = {
  rulesId: undefined,
  rulesName: undefined,
  description: undefined,
  inputParameter: undefined,
  decisionType: undefined,
  decisionTree: undefined,
  rulesEntityId: undefined,
  state: undefined
};
const data = reactive<PageData<MainForm, MainQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    rulesName: undefined,
    description: undefined,
    inputParameter: undefined,
    decisionType: undefined,
    decisionTree: undefined,
    rulesEntityId: undefined,
    state: '0',
    params: {}
  },
  rules: {
    rulesName: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }],
    description: [{ required: true, message: '规则描述不能为空', trigger: 'blur' }],
    decisionType: [{ required: true, message: '决策类型不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);


/** 查询规则信息主体列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMain(queryParams.value);
  mainList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  mainFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: MainVO[]) => {
  ids.value = selection.map((item) => item.rulesId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 规则删除 */
const DeleteTree = async (row: MainVO) => {
  await proxy?.$modal.confirm('确定要删除此规则？');
  loading.value = true;
  const res = await deleteRule(row);
  if (res.code == 200) {
    proxy?.$modal.msgSuccess('操作成功');
    await getList();
  } else {
    proxy?.$modal.msgError('操作失败');
  }
  loading.value = false;
};

/** 规则送审 */
const toAudit = async (row: MainVO) => {
  await proxy?.$modal.confirm('确定要送审此规则？');
  loading.value = true;
  try {
    const res = await ruleToAudit(row);
    if (res.code == 200) {
      proxy?.$modal.msgSuccess('操作成功');
      await getList();
    } else {
      proxy?.$modal.msgError('操作失败');
    }
  } catch (e) {
  } finally {
    loading.value = false;
  }
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加规则信息主体';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: MainVO) => {
  reset();
  const _rulesId = row?.rulesId || ids.value[0];
  const res = await getMain(_rulesId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改规则信息主体';
};

/** 参数维护 */
const handleOpenParms = async (row?: MainVO) => {
  const _rulesId = row?.rulesId || ids.value[0];
  ruleId.value = _rulesId;
  const res = await getParms(_rulesId);
  parmsloading.value = true;
  parmsDialog.visible = true;
  parmsDialog.title = '规则参数';
  parmsList.value = res.data;
  parmsloading.value = false;
};

/** 取消按钮 */
const cancelParms = () => {
  parmsDialog.visible = false;
  ruleId.value = '';
};

/** 提交按钮 */
const submitForm = () => {
  mainFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.rulesId) {
        await updateMain(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addMain(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 参数维护提交按钮 */
const submitParmsForm = async () => {
  const res = await addParms(ruleId.value, parmsList.value);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess('操作成功');
    cancelParms();
  } else {
    proxy?.$modal.msgError('操作失败');
  }
};

const addRow = () => {
  const newRow = {};
  parmsList.value.push(newRow);
};

const toDecisionTree = async (row?: MainVO) => {
  const _rulesId = row?.rulesId || ids.value[0];
  const res = await getParms(_rulesId);
  if (res.data.length == 0) {
    proxy?.$modal.msgError('请先做请求参数维护');
    return;
  }
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/rule/definition/def`,
    query: {
      rulesId: _rulesId,
      showSaveFlag: 'true'
    }
  });
};

onMounted(() => {
  getList();
});
</script>

