<template>
  <BaseTable
    showIndex
    tableName="ROLE_DISCIPLINE_CONFIG"
    ref="tableRef"
    :actionList="actionList"
    hide-pagination
    fullHeight
  >
    <template #leftOptions>
      <el-button icon="plus" @click="openDialog('add')" type="primary"> 新增 </el-button>
    </template>
    <template #disciplineNames="{ row }">
      {{ row.disciplineNames.join('，') }}
    </template>
    <template #simulationTypeName="{ row }">
      {{ row.simulationTypeName.join('，') }}
    </template>
  </BaseTable>
  <Dialog
    v-model="dialogVisible"
    :diaTitle="isEditDialog ? '编辑' : '新增'"
    :width="500"
    :height="500"
    show-confirm-button
    show-cancel-button
    show-footer
  >
    <div class="content">
      <el-form :model="diaForm" label-width="auto" ref="formRef" :rules="rules">
        <el-form-item label="角色名称" prop="role">
          <el-select v-model="diaForm.role" :disabled="isEditDialog" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleCode"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仿真类型" prop="simulationType">
          <el-select v-model="diaForm.simulationType" placeholder="请选择">
            <el-option
              v-for="item in SIMULATION_TYPE.A"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="查看学科" prop="discipline">
          <el-select
            v-model="diaForm.discipline"
            :disabled="!diaForm.simulationType"
            multiple
            placeholder="请先选择仿真类型"
          >
            <el-option
              v-for="item in disciplineList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmFun">确定</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import BaseTable from '@/components/common/table/baseTable.vue';
import Dialog from '@/components/common/dialog/index.vue';
import { ref, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import {
  addSystemParamConfigureApi,
  querySystemParamConfigureApi,
  updateSystemParamConfigureApi,
} from '@/api/system/systemData';
import { roleListRolesApi } from '@/api/system/role';
import { getUserTenantId } from '@/utils/user';
import { useDict } from '@/utils/useDict';
// import { getDisciplineByRole } from '@/utils/roleDiscipline';

const { SIMULATION_TYPE } = useDict('SIMULATION_TYPE');

// 角色列表
const roleList = ref<any>([]);
const getRoleList = async () => {
  const params = {
    tenantId: getUserTenantId(),
    current: 1,
    size: 100,
  };
  const res: any = await roleListRolesApi(params);
  if (res.code === 200) {
    roleList.value = res.data.data || [];
  }
};
// 动态的字典
const disciplineList = ref<any>([]);
const diaForm = ref({
  role: '',
  simulationType: '',
  discipline: [],
});
watch(
  () => diaForm.value.simulationType,
  (val) => {
    if (val && val.length) {
      disciplineList.value = [];
      const arr = [val];
      arr.forEach((item: any) => {
        const dictResult = useDict(item);
        disciplineList.value = disciplineList.value.concat(dictResult[item]?.value.A || []);
      });
      // 过滤出不在 disciplineList.value中的数据
      diaForm.value.discipline = diaForm.value.discipline.filter((item: any) => {
        return disciplineList.value.some((discipline: any) => discipline.value === item);
      });
    } else {
      disciplineList.value = [];
      diaForm.value.discipline = [];
    }
  }
);
// 表单校验
const formRef = ref();
const rules = {
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  simulationType: [{ required: true, message: '请选择仿真类型', trigger: 'change' }],
  discipline: [{ required: true, message: '请选择查看学科', trigger: 'change' }],
};

const isEditDialog = ref(false);
const dialogVisible = ref(false);
const actionList = ref<any>([
  {
    title: '编辑',
    type: 'primary',
    click: (row: any) => {
      openDialog('edit', row);
    },
  },
  {
    title: '删除',
    type: 'danger',
    needConfirm: true,
    confirmTip: '确认删除？',
    click: async (row: any) => {
      deleteConfigure(row);
    },
  },
]);

// 打开弹窗
const openDialog = (type: string, row?: any) => {
  isEditDialog.value = type === 'edit';
  dialogVisible.value = true;
  formRef.value?.clearValidate();
  if (type === 'edit' && row) {
    diaForm.value.role = row.role;
    diaForm.value.simulationType = row.simulationType;
    diaForm.value.discipline = row.discipline;
  } else {
    diaForm.value.role = '';
    diaForm.value.simulationType = '';
    diaForm.value.discipline = [];
  }
};

const tableRef = ref();
const formatconfig = () => {
  const obj = {
    ...diaForm.value,
    roleName:
      roleList.value.find((item: any) => item.roleCode === diaForm.value.role)?.roleName || '',
    simulationTypeName: [diaForm.value.simulationType].map((item: any) => {
      const entries = Object.entries(SIMULATION_TYPE.value.O);
      const res = entries.find(([k, value]) => k === item) || [];
      return res[1];
    }),
    disciplineNames: diaForm.value.discipline.map((item: any) => {
      const obj = disciplineList.value.find((discipline: any) => discipline.value === item);
      return obj?.label || '';
    }),
  };
  return obj;
};
// 删除
const deleteConfigure = async (row: any) => {
  // 从tableData.value中找到非当前改动的项
  const otherData = tableData.value
    .filter((item: any) => item.role !== row.role)
    .map((item: any) => JSON.stringify(item));
  const params = {
    paramName: 'ROLE_DISCIPLINE',
    values: [...otherData],
  };
  const res: any = await updateSystemParamConfigureApi(params);
  if (res.code === 200) {
    ElMessage.success('操作成功');
    getTableData();
    dialogVisible.value = false;
  }
};
// 更新
const updateConfig = async () => {
  // 从tableData.value中找到非当前改动的项
  const otherData = tableData.value
    .filter((item: any) => item.role !== diaForm.value.role)
    .map((item: any) => JSON.stringify(item));
  // 当前改动的项
  const obj = formatconfig();
  // 更新参数
  const params = {
    paramName: 'ROLE_DISCIPLINE',
    values: [JSON.stringify(obj), ...otherData],
  };
  const res: any = await updateSystemParamConfigureApi(params);
  if (res.code === 200) {
    ElMessage.success('操作成功');
    getTableData();
    dialogVisible.value = false;
  }
};
// 新建
const addConfig = async () => {
  const obj = formatconfig();
  const params = {
    paramName: 'ROLE_DISCIPLINE',
    values: [JSON.stringify(obj)],
  };
  const res: any = await addSystemParamConfigureApi(params);
  // const res: any = await updateSystemParamConfigureApi(params);
  if (res.code === 200) {
    ElMessage.success('操作成功');
    getTableData();
    dialogVisible.value = false;
  }
};
// 点击保存
const confirmFun = async () => {
  if (!formRef.value) return;
  await formRef.value.validate((valid: boolean) => {
    if (valid) {
      if (tableData.value.length) {
        updateConfig();
      } else {
        addConfig();
      }
    }
  });
};
// 表格数据
const tableTotal = ref<any>(0);
const tableData = ref<any>([]);
const getTableData = async () => {
  const params = {
    paramName: 'ROLE_DISCIPLINE',
  };
  querySystemParamConfigureApi(params).then((res: any) => {
    if (res.code === 200) {
      // 转换表格数据
      const list = res.data.values.map((item: any) => JSON.parse(item));
      tableData.value = list || [];
      tableRef.value.setDataFun(list);
      localStorage.setItem('ROLE_DISCIPLINE', JSON.stringify(res.data.values));
      // 记录总数
      tableTotal.value = list.length;
      // 设置角色不可选
      roleList.value.forEach((item: any) => {
        item.disabled = list.some((item2: any) => item2.role === item.roleCode);
      });
    }
  });
};

watch(
  () => dialogVisible.value,
  (val) => {
    if (!val) {
      diaForm.value.role = '';
      diaForm.value.simulationType = '';
      diaForm.value.discipline = [];
      formRef.value?.clearValidate();
    }
  }
);
// const testDisciplines = () => {
//   const adminDisciplines = getDisciplineByRole('ROLE_ADMIN, PMO');
// };
// testDisciplines();

onMounted(async () => {
  await getRoleList();
  getTableData();
});
</script>
