<script setup lang="tsx">
import { reactive, ref, unref,onMounted } from 'vue'
import {
  getUserRole,
  addUserRole,
  putUserRole,
  delUserRole,
  putUserRoleStatus
} from '@/api/system/department'
import { AddAdmins } from '@/api/system/department/types'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElMessage, ElMessageBox, ElSwitch, ElTag, ElDivider } from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { getRoleListApi } from '@/api/system/role'
const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getUserRole({
      ...searchParams.value,
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10
    })
    return {
      list:
        res.data.list.map((ee) => {
          ee.isStatus = ee.status === 1 ? true : false
          ee.roles = ee.roles.split(',')
          return ee
        }) || [],
      total: res.data.count || 0
    }
  }
})
const { dataList, loading, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: 'ID',
    width: 80
  },
  {
    field: 'account',
    label: '账号',
    width: 100
  },
  {
    field: 'phone',
    label: '电话',
    width: 120
  },
  {
    field: 'real_name',
    label: '姓名',
    width: 120
  },
  {
    field: 'roles',
    label: '权限',
    minWidth: 80,
    slots: {
      default: (data: any) => {
        return (
          <>
            {data.row.roles.map((item) => (
              <ElTag class={'mr-2'}>{item}</ElTag>
            ))}
          </>
        )
      }
    }
  },
  {
    field: '_add_time',
    label: '创建时间',
    width: 160
  },
  {
    field: 'status',
    label: t('menu.status'),
    align: 'center',
    headerAlign: 'center',
    width: 80,
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElSwitch
              inlinePrompt
              activeText="启用"
              inactiveText="禁用"
              v-model={data.row.isStatus}
              onChange={() => putUserStatus(data.row)}
            ></ElSwitch>
          </>
        )
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 160,
    fixed: 'right',
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton link size="small" type="primary" onClick={() => action(row, 'edit')}>
              {t('exampleDemo.edit')}
            </BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton link size="small" type="success" onClick={() => action(row, 'detail')}>
              {t('exampleDemo.detail')}
            </BaseButton>
            <ElDivider direction="vertical" />
            <BaseButton link size="small" type="danger" onClick={() => delAction(row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'status',
    label: t('menu.status'),
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '全部',
          value: ''
        },
        {
          label: t('userDemo.disable'),
          value: 0
        },
        {
          label: t('userDemo.enable'),
          value: 1
        }
      ]
    }
  },
  {
    field: 'type',
    label: '',
    value: 1,
  },
  {
    field: 'name',
    label: '搜索',
    component: 'Input',
    value: '',
    componentProps: {
      placeholder: '请输入姓名或者账号'
    }
  }
])

const searchParams = ref<{ status: number | string; name?: string;type: number }>({ status: '', name: '',type: 1 })
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentRow = ref()
const actionType = ref('')
const writeRef = ref<ComponentRef<typeof Write>>()
const saveLoading = ref(false)
const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  let roles = [] as any[]
  if (row.roles) {
    row.roles.forEach(element => {
      roleList.value.forEach((element1: any) => {
        if (element == element1.label) {
          roles.push(element1.value)
        }
      });
    });
  }
  console.log(roles,'roles');
  
  currentRow.value = {
    id: row.id,
    account: row.account, //账号
    real_name: row.real_name, //名字
    pwd: '',
    conf_pwd: '',
    phone: row.phone, //手机号
    roles: roles, //角色数组
    status: row.status === 1 ? true : false ,//是否启用
    is_all: row.status === 1 ? true : false,
    configure_id: row.configure_id
  }
  dialogVisible.value = true
}

const putUserStatus = (row: any) => {
  putUserRoleStatus({ id: row.id, status: row.status === 1 ? 0 : 1 }).then(() => {
    getList()
  })
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const delAction = async (row: any) => {
  ElMessageBox.confirm('删除后无法恢复，是否删除?', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await delUserRole({ id: row.id })
      await getList()

      ElMessage({
        showClose: true,
        message: '删除',
        type: 'success'
      })
    })
    .catch(() => {})
}
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const data: AddAdmins = {
      id: formData.id || '',
      account: formData.account, //账号
      pwd: formData.pwd, //密码
      conf_pwd: formData.conf_pwd, //确认密码
      real_name: formData.real_name, //名字
      phone: formData.phone, //手机号
      roles: formData.roles, //角色数组
      status: formData.status ? 1 : 0 ,//是否启用
      is_all: formData.is_all ? 1 : 0,
      configure_id: formData.configure_id
    }
    try {
      let res: any = {}
      if (actionType.value === 'edit') {
        res = await putUserRole(data)
      } else if (actionType.value === '') {
        res = await addUserRole(data)
      }
      if (res?.status == 200) {
        ElMessage({
          showClose: true,
          message: '保存成功',
          type: 'success'
        })
        getList()
        dialogVisible.value = false
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
    }
  }
}
const roleList = ref([])
onMounted(async () => { 
  const re = await getRoleListApi({ page: 1, limit: 9999 })
  roleList.value = re.data.list.map((res) => {
    return {
      label: res.role_name,
      value: res.id
    }
  })
})
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      stripe
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :pagination="{
        total
      }"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="60%">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />

    <Detail v-if="actionType === 'detail'" :current-row="currentRow" />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
