<!-- 角色管理 -->
<template>
  <div class="detail_container">
    <div class="bg-breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item> 系统管理 </el-breadcrumb-item>
        <el-breadcrumb-item> 角色管理 </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main_container">
      <bg-filter-group 
        @search="changeSearch" 
        v-model="filter.search" 
        placeholder="请输入角色名称"
      >
        <template v-slot:left_action>
          <div class="apaas_button">
            <el-button class="register_btn" type="primary" @click="register">
              <bg-icon style="font-size: 12px; color: #fff; margin-right: 8px" icon="#bg-ic-add"></bg-icon>
                新建
            </el-button>
            <el-button class="register_btn" type="primary" @click="deleteRows">
                批量删除
            </el-button>
            <div class="select_text">
              <span>已选择</span>
              <span class="num">{{selection.length}}</span>
              <span>项</span>
              <span class="can_click_text" @click="clearRoleSelection">清空</span>
            </div>
          </div>
        </template>
      </bg-filter-group>
      <div class="table_container">
        <div class="table bg-scroll">
          <bg-table 
            ref="Bgtable" 
            :headers="headers" 
            :rows="tableRows" 
            :select="true" 
            :stripe="true" 
            canEdit
            canEditFlag='state' 
            @selectAc="selectRows"
          >
            <template v-slot:state="{ row }">
              <bg-switch 
                @click="changeUseRow(row)" 
                :labels="['否','是']" 
                :values="[0,1]" 
                v-model="row.state" 
                :disabled="row.role_type == 1"
              />
            </template>
            <template v-slot:created_time="{ row }">
              {{ row.created_time.split("+")[0].replace("T", " ").replace("Z", " ") }}
            </template>
            <template v-slot:action="{ row }">
              <bg-table-btn class="can_click_text" :click="()=>{edit_row(row)}" :disabled="row.state == 1 || row.role_type == 1">
                编辑
              </bg-table-btn>
              <bg-table-btn class="can_click_text" :click="()=>{distribute_user(row)}" :disabled="row.cant_allot == 1">
                分配用户
              </bg-table-btn>
              <bg-table-btn class="can_click_text" :click="()=>{delete_row(row)}" :disabled="row.state == 1 || row.role_type == 1">
                删除
              </bg-table-btn>
            </template>
          </bg-table>
        </div>
        <bg-pagination
          :page="filter.page"
          :size="filter.limit"
          :total="tableTotal"
          @change-page="changePage"
          @change-size="changeSize"
        >
        </bg-pagination>
      </div>
    </div>
    <!-- 删除弹窗 -->
    <el-dialog
      custom-class="dialog_box"
      title="提示"
      v-model="delDialog"
      width="400px"
      :before-close="
        () => {
          delDialog = false;
        }
      "
    >
      <div>确定要删除选中的数据吗？</div>
      <template v-slot:footer>
        <div class="apaas_button">
          <el-button type="default" @click="delDialog = false">取 消</el-button>
          <el-button type="primary" @click="deleteData">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分配用户 -->
    <el-dialog
      custom-class="distribute_dialog"
      title="分配用户"
      v-model="distributeDialog"
      width="1062px"
      :before-close="
        () => {
          distributeDialog = false;
        }
      "
    >
      <div class="distribute_box">
        <div class="topFilter">
          <div class="left">
            <span>已选择</span>
            <span class="num">{{userSelection.length}}</span>
            <span>项</span>
            <span class="can_click_text" @click="clearUserSelection">清空</span>
          </div>
          <div class="right">
            <el-select
              v-model="userFilter.is_admin"
              placeholder="请选择"
              style="width: 200px"
            >
              <el-option
                v-for="(item, index) in userTypeList"
                :key="'pushOptions' + index"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-cascader
              v-model="userFilter.organization_id"
              :options="orgList"
              placeholder="请选择组织"
              :props="{ expandTrigger: 'hover', label: 'name', value: 'id', emitPath: false, checkStrictly: true, children: 'Child'}"
              :clearable="true"
              collapse-tags
              style="width: 200px"
            >
              <template #default="{ data }">
                <span>{{ data.name }}</span>
              </template>
            </el-cascader>
            <el-input
              v-model="userFilter.search"
              placeholder="请输入内容"
              style="width: 200px"
              :prefix-icon="Search"
            />
            <el-button type="primary" @click="searchAction">查询</el-button>
            <el-button type="default" @click="clearAction">重置</el-button>
          </div>
        </div>
        <div class="table_box">
          <div class="user_table bg-scroll">
            <bg-table 
              ref="userTable" 
              :headers="userHeaders" 
              :rows="userRows" 
              :select="true" 
              :stripe="true"
              @selectAc="selectUserRows"
            >
              <template v-slot:is_admin="{ row }">
                {{ ["","业务系统账号","组织管理员账号","平台用户账号"][row.is_admin] }}
              </template>
            </bg-table>
          </div>
          <bg-pagination
            :page="userFilter.page"
            :size="userFilter.limit"
            :total="total"
            @change-page="changeUserPage"
            @change-size="changeUserSize"
          >
          </bg-pagination>
        </div>
      </div>
      <template v-slot:footer>
        <div class="apaas_button">
          <el-button type="default" @click="distributeDialog = false">取 消</el-button>
          <el-button type="primary" @click="distribute">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { reactive, toRefs, ref, onBeforeMount, nextTick } from 'vue'
import axios from '../../../../request/http.js'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()
const Bgtable = ref(null)
const userTable = ref(null)
const state = reactive({
  filter: {
    page: 1,
    limit: 10,
    search: "",
  }, 
  headers: [
    {
      label: "角色名",
      prop: "role_name",
      width: 220
    },
    {
      label: "创建人",
      prop: "created_by",
      
      width: 220
    },
    {
      label: "创建时间",
      prop: "created_time",
      width: 276
    },
    {
      label: "账号数",
      prop: "user_count",
    },
    {
      label: "描述",
      prop: "role_desc",
      minWidth: 346
    },
    {
      label: "是否启用",
      prop: "state",
      width: 95
    },
    {
      label: "操作",
      prop: "action",
      width: 220,
      fixed: "right",
    },
  ],
  tableRows: [],
  tableTotal: 0,
  actionRow: {},
  selection: [],
  delDialog: false,
  delType: 1, // 删除类型  1-单条删除 2-批量删除
})
const userState = reactive({
  userFilter: {
    is_admin: "",
    organization_id: "",
    search: "",
    limit: 10,
    page: 1,
  },
  userTypeList: [
    {
      name: "全部类型",
      value: ""
    },
    {
      name: "组织管理员账号",
      value: 2
    },
    {
      name: "平台用户账号",
      value: 3
    },
  ],
  orgList: [],
  userHeaders: [
    {
      label: "帐号",
      prop: "system_account",
    },
    {
      label: "类型",
      prop: "is_admin",
    },
    {
      label: "用户手机号",
      prop: "contact_phone",
    },
    {
      label: "所属组织",
      prop: "organization_name",
    },
  ],
  userRows: [],
  total: 0,
  userSelection: [],
  distributeDialog: false, // 分配用户弹窗
})
const getRoleRows = () => {
  let params = {...state.filter}
  console.log(params)
  axios
    .get(`/apaas/system/v5/role/list`,{params})
    .then((res) => {
      if (res.data.code == 200) {
        state.tableRows = res.data.data || []
        state.tableTotal = res.data.total
      }else {
        ElMessage.error(re.data.msg)
      }
    })
} // 获取角色列表

const getOrgList = () => {
  axios
    .get(`/apaas/system/v5/org/tree`)
    .then((res) => {
      if (res.data.code == 200) {
        console.log(res.data.data)
        userState.orgList = res.data.data || []
      }else {
        ElMessage.error(res.data.msg)
      }
    })
} // 获取组织列表
const changePage = (val) => {
  state.filter.page = val
  getRoleRows()
} // 改变页码

const changeSize = (val) => {
  state.filter.limit = val
  changePage(1)
} // 改变每页条数

const changeSearch = (val) => {
  state.filter.search = val
  changePage(1)
} // 表格关键字筛选

const changeUseRow = (row) => {
  axios
    .post(`/apaas/system/v5/role/state/${row.id}/${row.state}`)
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg)
        changePage(1)
      }else {
        ElMessage.error(res.data.msg)
      }
    })
} // 更改启用禁用状态

const selectRows = (data) => {
  state.selection = data.selection
} // 表格多选

const clearRoleSelection = () => {
  Bgtable.value.clearTable()
}

const register = () => {
  console.log("新建角色")
  router.push("/system/role/add")
} // 新建角色

const edit_row = (row) => {
  console.log(row,"编辑角色")
  router.push({
    path: "/system/role/edit",
    query: {
      id: row.id
    }
  })
} // 编辑角色

const distribute_user = (row) => {
  clearAction(1)
  userState.distributeDialog = true
  state.actionRow = row
  getUserList()
} // 分配角色按钮

const getUserList = () => {
  nextTick(() => {
    clearUserSelection()
  })
  let params = {
    limit: userState.userFilter.limit,
    page: userState.userFilter.page,
    search: userState.userFilter.search,
    organization_id: userState.userFilter.organization_id,
    is_admin: userState.userFilter.is_admin,
    role_id: state.actionRow.id,
  }
  axios
    .get(`/apaas/system/v5/role/allotment/list`,{params})
    .then((res) => {
      if (res.data.code == 200) {
        console.log(res.data.data)
        userState.userRows = res.data.data || []
        userState.total = res.data.total
        nextTick(() => {
          userState.userRows.forEach(e => {
            if(e.is_bind == 1) {
              userTable.value.toggleRowSelection(e,true)
            }
          })
        })
      }else {
        ElMessage.error(res.data.msg)
      }
    })
}
const changeUserPage = (val) => {
  userState.userFilter.page = val
  getUserList()
}

const changeUserSize = (val) => {
  userState.userFilter.limit = val
  changeUserPage(1)
}

const searchAction = () => {
  console.log(userState.userFilter)
  changeUserPage(1)
}

const clearAction = (type) => {
  userState.userFilter = {
    is_admin: "",
    organization_id: "",
    search: "",
    limit: 10,
    page: 1,
  }
  if (type != 1) {
    changeUserPage(1)
  }
}

const clearUserSelection = () => {
  userTable.value.clearTable()
}

const selectUserRows = (data) => {
  userState.userSelection = data.selection
}

const distribute = () => {
  let user_ids = []
  userState.userSelection.forEach(e => {
    user_ids.push(e.id)
  })
  let params = {
    id: state.actionRow.id,
    user_ids: user_ids
  }
  axios
    .post(`/apaas/system/v5/role/allotment/user`,params)
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg)
        userState.distributeDialog = false
        changePage(1)
      }else {
        ElMessage.error(res.data.msg)
      }
    })
  
}

const delete_row = (row) => {
  state.actionRow = row
  state.delType = 1
  state.delDialog = true
} // 删除角色

const deleteRows = () => {
  if (state.selection.length == 0) {
    ElMessage.error("请先选择要删除的数据")
  }else {
    state.delType = 2
    state.delDialog = true
  }
} // 批量删除按钮

const deleteData = () => {
  let ids = []
  if (state.delType == 1) {
    ids.push(state.actionRow.id)
  }else {
    state.selection.forEach(e => {
      ids.push(e.id)
    })
  }
  let params = {
    ids: [...ids]
  }
  axios
    .delete(`/apaas/system/v5/role/delete`,{data: {ids:[...ids]}})
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg)
        state.delDialog = false
        changePage(1)
      }else {
        ElMessage.error(res.data.msg)
      }
    })
}
onBeforeMount(() => {
  getRoleRows()
  getOrgList()
})
    
const {
  filter,
  headers,
  tableRows,
  tableTotal,
  delDialog,
  selection,
} = toRefs(state)

const {
  userFilter,
  userTypeList,
  orgList,
  userHeaders,
  userRows,
  total,
  userSelection,
  distributeDialog,
} =toRefs(userState)
</script>

<style lang="scss" scoped>
.detail_container {
  width: 100%;
  padding: 0 24px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  .main_container {
    flex-grow: 1;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: stretch;
    background-color: #fff;
    box-shadow: 0px 1px 4px 0px rgba(0,7,101,0.15);
    border-radius: 6px;
    margin: 0 0 16px;
    position: relative;
    height: calc(100% - 62px);
    .table_container {
      height: calc(100% - 70px);
      padding: 0 16px;
      .table {
        max-height: calc(100% - 64px);
      }
    }
    .select_text {
      display: inline-block;
      margin-left: 40px;
      font-size: 14px;
      color: #404a62;
      .num {
        color: #202531;
        font-weight: 700;
        margin: 0 3px;
      }
      .can_click_text {
        margin-left: 24px;
      }
    }
  }
  .distribute_dialog {
    .distribute_box {
      width: 100%;
      height: 626px;
      .topFilter {
        height: 68px;
        padding: 16px;
        border-bottom: 1px solid #e6e9ef;
        display: flex;
        text-align: left;
        font-size: 14px;
        align-items: center;
        .left {
          width: 240px;
          padding-left: 15px;
          color: #404a62;
          .num {
            color: #202531;
            font-weight: 700;
            margin: 0 3px;
          }
          .can_click_text {
            margin-left: 24px;
          }
        }
        .right {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .el-button {
            margin: 0;
            width: 64px;
          }
        }
      }
      .table_box {
        padding: 10px 16px;
        height: calc(100% - 68px);
        .user_table {
          max-height: calc(100% - 48px);
        }
      }
    }
  }
}
</style>
<style>
.distribute_dialog .el-dialog__footer {
  padding: 16px!important;    
}
.distribute_dialog .el-dialog__body {
  padding: 0px!important;    
}
.distribute_dialog {
  margin-top: 130px!important;    
}
</style>