<template>
    <!-- 分配角色的弹窗  -->
    <el-dialog
      :key="Math.random()"
      :title="addRoleDialog.title"
      width="80%"
      v-model="addRoleDialog.visible"
      @opened="addRoleDialogOpened"
      destroy-on-close
      @closed="addRoleDialogClose"
    >
      <div class="vue-element-page-wrap" ref="tableContainer">
        <el-row class="page-search" justify="space-between" align="middle">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="" prop="params.text">
                  <CustomInput
                    v-model:params="queryParams.params.text"
                    placeholder="名称/编码"
                    clearable
                    @keyUpEvent="handleQuery"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="page-search-btns">
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </div>
        </el-row>

        <div class="vue-element-page-table">
          <div class="page-table-operate">
            <span>更新时间：{{currentTime}}</span>
            <div class="page-table-operateBtns">
              <el-popover :persistent="false" placement="right" popper-class="config-table-wrap" trigger="click">
                <template #reference>
                  <el-button class="operateBtns-setting">
                    <svg-icon icon-class="table_title" width="16px" height="16px"/>
                  </el-button>
                </template>
                <ConfigTable :list="column" @updateList="updateList"/>
              </el-popover>
            </div>
          </div>
          <el-table
            border
            ref="allRoleTableRef"
            :data="allRoleList"
            highlight-current-row
            row-key="dataId"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="40"
              align="center"
              :selectable="checkSelectable"
            />
            <template
              v-for="(col,index) in column"
              :key="index"
            >
              <el-table-column
                v-if="!col.hide"
                :label="col.header"
                show-overflow-tooltip
              >
                <template #default="scope">
              <span v-if="col.field === 'status'">
                <span v-if="scope.row[col.field]" class="table-status-active">启用</span>
                <span v-else class="table-status-inActive">禁用</span>
              </span>
                  <span v-else>{{ scope.row[col.field] }}</span>
                </template>
              </el-table-column>
            </template>
            <template v-slot:empty>
              <svg-icon icon-class="noData" width="160px" height="160px"/>
            </template>
          </el-table>
          <pagination
            v-if="total>0"
            :total="total"
            v-model:pageNumTo="queryParams.pageNum"
            v-model:pageSizeTo="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="saveLinkRole">确定</el-button>
        </span>
      </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import {reactive, ref, onMounted, toRefs, getCurrentInstance, watch, computed, nextTick} from 'vue';
import { ElForm, ElMessageBox,ElTable  } from 'element-plus';
import {
  enableRoleList, saveLinkRoleData,
} from '@/api/userGroup';

const props = defineProps({
  selectedRoles: {
    type: Array as any,
  },
  addRoleDialog: {
    type: Object
  },
  selectGroup: {
    type: Object
  },
});

const queryFormRef = ref(ElForm);
const { proxy }: any = getCurrentInstance();
const allRoleTableRef = ref<InstanceType<typeof ElTable>>()

const state = reactive({
  currentTime:'',
  queryParams: {
    params: {
      text:''
    },
    pageNum: 1,
    pageSize: 10
  },
  total: 0,
  column: [] as any,
  allRoleList: [] as any,
  multiSelection: [] as any
})
const {
  currentTime,
  queryParams,
  column,
  total,
  allRoleList,
  multiSelection
} = toRefs(state);
const emit = defineEmits(['updateVisible']);
onMounted(() => {
  state.column = [
    { header: '角色编码',field:'code',hide: false },
    { header: '角色名称',field:'name',hide: false },
    { header: '备注',field:'remark',hide: false },
  ]
  handleQuery();
});
// 更新列
function updateList(col: any) {
  state.column = col;
}
function handleQuery() {
  enableRoleList(state.queryParams)
    .then((res:any)=>{
      state.allRoleList = res.data.list;
      state.total = res.data.total;
      showCurrentTime();
    })
    .catch(() => {});
}
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}
function showCurrentTime() {
  let date = new Date()
  state.currentTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ":" +
    (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ":" + (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
}
// 处理回显数据
function checkSelectable(row:any,index: any) {
  let flag = true;
  for(let i=0;i<props.selectedRoles.length;i++) {
    if(row.dataId === props.selectedRoles[i].dataId) {
      flag = false;
      break;
    }
  }
  return flag;
}
// 分配的角色弹框打开后
function addRoleDialogOpened() {
  state.allRoleList.forEach((item:any,index: number)=>{
    props.selectedRoles.forEach((child:any)=>{
      if(item.dataId == child.dataId) {
        console.log('被选中的',state.allRoleList[index]);
        allRoleTableRef.value!.toggleRowSelection(state.allRoleList[index], true)
      }
    })
  })
}
const handleSelectionChange = (val: any) => {
  state.multiSelection = val;
}
function saveLinkRole() {
  let sourceIds:any = [];
  let relIds:any = [];
  props.selectGroup!.forEach((item:any)=>{
    sourceIds.push(item.dataId)
  });
  state.multiSelection.forEach((item:any)=>{
    relIds.push(item.dataId);
  })

  let params = {
    data:{
      sourceIds:sourceIds,
      relIds: relIds
    }
  }
  saveLinkRoleData(params).then(() => {
    proxy.$ElMessage.success('分配成功');
    addRoleDialogClose();
  });
}
function addRoleDialogClose() {
  emit('updateVisible');
}
</script>
<style scoped lang="scss">

</style>
