<template>
  <div class="operator-role">
    <el-dialog v-bind="$attrs" :before-close="cancelDialog" :append-to-body="true" :destroy-on-close="true" :close-on-click-modal="false" :close-on-press-escape="false" :lock-scroll="false" class="role-dialog">
      <el-form ref="operatorRoleRef" :model="state.form" :rules="state.rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="操作员角色" prop="grouplist">
              <el-select v-model="state.form.grouplist" multiple placeholder="请选择操作员角色" style="width: 100%">
                <el-option v-for="(item, index) in roleList" :key="`role-select-${index}`" :label="item.title" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDialog">确 定</el-button>
          <el-button @click="cancelDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import useSystemManageStore from '@store/modules/systemManage'
import { filterObject, getMergeValue } from '@/utils/index'

const systemManageStore = useSystemManageStore()
const { proxy } = getCurrentInstance()
const mitter = proxy.mitter
const operatorRoleRef = ref(null)

const props = defineProps({
  keys: {
    type: Object,
  },
})

watchEffect(async () => {
  if (props.keys.account) {
    getDataView(props.keys.account)
  }
})

const roleList = inject('roleList')

const state = reactive({
  form: {
    account: '',
    grouplist: '',
    popedom: '',
  },
  rules: {},
})

const getDataView = async (account) => {
  const result = await systemManageStore.operatorviewDataview({ account })
  let filters = filterObject(result, Object.keys(state.form))
  if (result.grouplist) {
    filters.grouplist = filters.grouplist.split(',').map((val) => {
      return parseInt(val)
    })
  }
  state.form = filters
}

const submitDialog = async () => {
  if (!state.form.grouplist.length) {
    proxy.$modal.msgError('未选择任何角色！')
    return
  }
  //根据角色list，计算出权限列表
  const newPopedom = getMergeValue(state.form.grouplist, roleList.value, 'popedom')
  state.form.account = props.keys.account
  state.form.popedom = newPopedom
  state.form.grouplist = state.form.grouplist.join(',')

  await systemManageStore.sysuserUp(state.form)
  proxy.$modal.msgSuccess('修改成功！')
  mitter.emit('onEditFinish', { refresh: true })
}
const cancelDialog = () => {
  mitter.emit('onEditFinish', { refresh: false })
  operatorRoleRef.value.resetFields()
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
