<template>
  <d2-container>
    <template #header>
      <div class="search-bar">
        <el-form :inline="true" size="mini">
          <el-form-item :label="$t(key('name'))">
            <el-input
              v-model="search.name"
              :placeholder="$t(key('enter_name'))"
              clearable
              style="width:200px"
              @keyup.enter.native="onSearch"
            />
          </el-form-item>
          <el-form-item :label="$t(key('status'))">
            <el-select
              v-model="search.status"
              :placeholder="$t(key('select_status'))"
              clearable
              style="width:150px"
            >
              <el-option :value="'1'" :label="$t(key('enabled'))" />
              <el-option :value="'0'" :label="$t(key('disabled'))" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="onSearch">
              {{ $t(key('search')) }}
            </el-button>
            <el-button icon="el-icon-refresh" @click="onReset">
              {{ $t(key('reset')) }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>

    <page-table
      ref="pageTable"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :toolbar-buttons="toolbarButtons"
      :row-buttons="rowButtons"
      :pagination="pagination"
      :table-attrs="{ selectable: row => row.system === 0 }"
      auto-height
      @page-change="onPageChange"
      @selection-change="onSelect"
    >
      <template #col-status="{ row }">
        <span v-if="row.status === 1" style="color: #67c23a;">
          <i class="el-icon-circle-check" />
          {{ $t(key('enabled')) }}
        </span>
        <span v-else style="color: #909399;">
          <i class="el-icon-circle-close" />
          {{ $t(key('disabled')) }}
        </span>
      </template>
    </page-table>

    <page-dialog-form
      ref="dialogForm"
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      width="35%"
      :form-cols="formCols"
      :form-data="formData"
      :rules="rules"
      label-width="100px"
      :submitting="submitting"
      :confirm-text="key('confirm')"
      :cancel-text="key('cancel')"
      @submit="onDialogSubmit"
      @close="onDialogClose"
    />

    <role-perm-drawer
      :visible.sync="permVisible"
      :role="permRole"
      :title="key('assign_permissions')"
      :confirm-text="key('confirm')"
      :cancel-text="key('cancel')"
      width="360px"
      @saved="fetchData"
    />
  </d2-container>
</template>

<script>
import { useTableColumns } from '@/composables/useTableColumns'
import { useTableButtons } from '@/composables/useTableButtons'
import { i18nMixin } from '@/composables/useI18n'
import { confirmMixin } from '@/composables/useConfirmHandle'
import {
  getRoleList,
  createRole,
  editRole,
  deleteRole,
  updateRoleStatus
} from '@/api/system-administration/role'
import PageTable from '@/components/page-table'
import PageDialogForm from '@/components/page-dialog-form'
import RolePermDrawer from './components/PermDrawer/index.vue'

export default {
  name: 'system-administration-role',
  components: { PageTable, PageDialogForm, RolePermDrawer },
  mixins: [i18nMixin('page.system_administration.user_management.role'), confirmMixin],
  data () {
    return {
      loading: false,
      submitting: false,
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogTitle: '',
      editId: '',
      handleType: 'create',
      search: { name: '', status: '' },
      pagination: { current: 1, size: 10, total: 0 },
      formData: { name: '', description: '', status: '1' },
      rules: {
        name: [
          { required: true, message: this.key('enter_name'), trigger: 'blur' },
          { min: 1, max: 100, message: this.key('length_limit'), trigger: 'blur' }
        ]
      },
      columns: [],
      toolbarButtons: [],
      rowButtons: [],
      formCols: [
        [
          {
            type: 'input',
            prop: 'name',
            label: this.key('name'),
            placeholder: this.key('enter_name'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'input',
            inputType: 'textarea',
            prop: 'description',
            autosize: { minRows: 2, maxRows: 6 },
            label: this.key('description'),
            placeholder: this.key('enter_description'),
            clearable: true,
            style: { width: '90%' }
          }
        ],
        [
          {
            type: 'select',
            prop: 'status',
            label: this.key('status'),
            clearable: false,
            style: { width: '90%' },
            options: [
              { value: '1', label: this.$t(this.key('enabled')) },
              { value: '0', label: this.$t(this.key('disabled')) }
            ]
          }
        ]
      ],
      permVisible: false,
      permRole: {}
    }
  },
  created () {
    this.columns = useTableColumns([
      { prop: 'sort', label: this.key('index'), width: 80 },
      { prop: 'name', label: this.key('name'), minWidth: 120 },
      { prop: 'status', label: this.key('status'), slot: 'status', width: 100 },
      { prop: 'description', label: this.key('description') },
      { prop: '_actions', label: this.key('actions'), width: 220, fixed: 'right' }
    ])
    const btns = useTableButtons({
      toolbar: [
        {
          key: 'add',
          label: this.key('add'),
          icon: 'el-icon-plus',
          type: 'primary',
          auth: '/system_settings/user_management/role/create',
          onClick: this.openAdd
        },
        {
          key: 'enable',
          label: this.key('enabled'),
          icon: 'el-icon-check',
          type: 'success',
          auth: '/system_settings/user_management/role/enable',
          onClick: () => this.batchUpdateStatus(1)
        },
        {
          key: 'disable',
          label: this.key('disabled'),
          icon: 'el-icon-close',
          type: 'warning',
          auth: '/system_settings/user_management/role/disable',
          onClick: () => this.batchUpdateStatus(0)
        }
      ],
      row: [
        {
          key: 'edit',
          label: this.key('edit'),
          icon: 'el-icon-edit',
          auth: '/system_settings/user_management/role/edit',
          visible: row => row.system !== 1,
          onClick: this.openEdit
        },
        {
          key: 'assign',
          label: this.key('assign_permissions'),
          icon: 'el-icon-edit-outline',
          auth: '/system_settings/user_management/role/role_give',
          visible: row => row.system !== 1,
          onClick: this.openPermDialog
        },
        {
          key: 'delete',
          label: this.key('delete'),
          icon: 'el-icon-delete',
          color: 'danger',
          auth: '/system_settings/user_management/role/delete',
          visible: row => row.system !== 1,
          onClick: this.handleDelete
        }
      ]
    }, this.$permission)
    this.toolbarButtons = btns.toolbarButtons
    this.rowButtons = btns.rowButtons
    this.fetchData()
  },
  methods: {
    async fetchData () {
      this.loading = true
      try {
        const res = await getRoleList({
          ...this.search,
          page_no: this.pagination.current,
          page_size: this.pagination.size
        })
        const list = Array.isArray(res) ? res : (res.data || [])
        const total = Array.isArray(res) ? res.length : (res.count || 0)
        this.tableData = list
        this.pagination.total = total
      } finally {
        this.loading = false
      }
    },
    onSearch () {
      this.pagination.current = 1
      this.fetchData()
    },
    onReset () {
      this.search = { name: '', status: '' }
      this.pagination.current = 1
      this.fetchData()
    },
    onPageChange (page) {
      this.pagination.current = page.current
      this.pagination.size = page.size
      this.fetchData()
    },
    onSelect (rows) {
      this.selectedRows = rows
    },
    resetForm () {
      this.formData = { name: '', description: '', status: '1' }
      this.editId = ''
    },
    openAdd () {
      this.handleType = 'create'
      this.dialogTitle = this.key('add_title')
      this.$nextTick(() => {
        this.$refs.dialogForm && this.$refs.dialogForm.reset()
        this.resetForm()
        this.dialogVisible = true
      })
    },
    openEdit (row) {
      this.handleType = 'edit'
      this.dialogTitle = this.key('edit_title')
      this.editId = row.id
      this.formData = {
        name: row.name,
        description: row.description || '',
        status: String(row.status)
      }
      this.dialogVisible = true
    },
    async onDialogSubmit () {
      this.submitting = true
      try {
        if (this.handleType === 'create') {
          await createRole(this.formData)
        } else {
          await editRole({ ...this.formData, id: this.editId })
        }
        this.$message.success(this.$t(this.key('operation_success')))
        this.dialogVisible = false
        this.fetchData()
      } finally {
        this.submitting = false
      }
    },
    onDialogClose () {
      this.resetForm()
    },
    async batchUpdateStatus (status) {
      const rows = this.selectedRows.filter(row => row.system === 0)
      if (rows.length === 0) {
        this.$message.warning(this.$t(this.key('select_rows_first')))
        return
      }
      try {
        await updateRoleStatus({
          id: rows.map(row => row.id),
          status
        })
        this.$message.success(this.$t(this.key('operation_success')))
        this.fetchData()
      } catch {
        // 拦截器已处理
      }
    },
    async handleDelete (row) {
      const cancelled = await this.$confirmAction(
        {
          message: this.key('confirm_delete'),
          title: this.key('tip')
        },
        () => deleteRole({ id: [row.id] })
      )
      if (cancelled) return
      this.$message.success(this.$t(this.key('operation_success')))
      this.pagination.current = Math.min(
        this.pagination.current,
        Math.ceil((this.pagination.total - 1) / this.pagination.size) || 1
      )
      this.fetchData()
    },
    async openPermDialog (row) {
      this.permRole = row
      this.permVisible = true
    }
  }
}
</script>

<style scoped>
.search-bar {
  padding: 10px 0;
}
/deep/ .el-form-item--mini.el-form-item {
  margin-bottom: 4px;
}
</style>
