<script setup lang="tsx">
import { ContentWrap } from '../../../components/ContentWrap'
import { useI18n } from '../../../hooks/web/useI18n'
import { Table } from '../../../components/Table'
import { ref, unref, nextTick, watch, reactive, toRaw } from 'vue'
import { ElTree, ElMessage, ElMessageBox } from 'element-plus'
import { getDeptTree } from '../../../api/system-config/department'
import type {
  DepartmentItem,
  DepartmentUserItem
} from '../../../api/system-config/department/types'
import { useTable } from '../../../hooks/web/useTable'
import { Search } from '../../../components/Search'
import Write from './components/Write.vue'
import { Dialog } from '../../../components/Dialog'
import { CrudSchema, useCrudSchemas } from '../../../hooks/web/useCrudSchemas'
import { BaseButton } from '../../../components/Button'
import {
  addUser,
  delUser,
  delUsers,
  getUserList,
  queryUser,
  updateUser
} from '../../../api/system-config/user'
import { useRouter } from 'vue-router'
import { useBtnAuth } from '../../../hooks/web/useBtnAuth'

const { t } = useI18n()

const router = useRouter()

const btns = useBtnAuth(router.currentRoute.value?.fullPath)
const directivesArgs = { btns }

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getUserList({
      userName: unref(searchParams)?.userName,
      deptId: unref(currentNodeKey),
      current: unref(currentPage),
      size: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: Number(res.data.totalCount) || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('userDemo.index'),
    fixed: true,
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },
  {
    field: 'userName',
    label: '姓名',
    fixed: true
  },
  {
    field: 'userNo',
    label: '账号',
    table: {
      // minWidth: 150
    },
    fixed: true
  },
  // {
  //   field: 'sex',
  //   label: '性别',
  //   form: {
  //     component: 'Select',
  //     componentProps: {
  //       options: [
  //         {
  //           label: '女',
  //           value: '0'
  //         },
  //         {
  //           label: '男',
  //           value: '1'
  //         }
  //       ]
  //     }
  //   },
  //   search: {
  //     hidden: true
  //   },
  //   slots: {
  //     default: (data) => {
  //       console.log(data)
  //       return (
  //         <>
  //           <div>{data.row.sex === '1' ? '男' : '女'}</div>
  //         </>
  //       )
  //     }
  //   }
  // },
  {
    field: 'phone',
    label: '手机号',
    table: {
      // minWidth: 150
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'email',
    label: '邮箱',
    table: {
      // minWidth: 180
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'address',
    label: '联系地址',
    search: {
      hidden: true
    },
    table: {
      // width: 200
      hidden: true
    }
  },
  // {
  //   field: 'birthday',
  //   label: '出生年月',
  //   search: {
  //     hidden: true
  //   }
  // },
  {
    field: 'idCard',
    label: '身份证号',
    table: {
      // width: 200
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  // {
  //   field: 'age',
  //   label: '年龄',
  //   search: {
  //     hidden: true
  //   }
  // },
  // {
  //   field: 'remark',
  //   label: '备注',
  //   search: {
  //     hidden: true
  //   }
  // },
  {
    field: 'deptIds',
    label: t('userDemo.department'),
    detail: {
      hidden: true
      // slots: {
      //   default: (data: DepartmentUserItem) => {
      //     return <>{data.department.departmentName}</>
      //   }
      // }
    },
    search: {
      hidden: true
    },
    form: {
      component: 'TreeSelect',
      // 解决初始化时 触发验证的问题
      value: [],
      componentProps: {
        nodeKey: 'id',
        props: {
          label: 'name'
        },
        multiple: true,
        showCheckbox: true,
        checkStrictly: true
      },
      colProps: {
        span: 24
      },
      optionApi: async () => {
        const res = await getDeptTree({})
        return res.data
      }
    },
    table: {
      hidden: true
    }
  },
  // {
  //   field: 'role',
  //   label: t('userDemo.role'),
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     component: 'Select',
  //     value: [],
  //     componentProps: {
  //       multiple: true,
  //       collapseTags: true,
  //       maxCollapseTags: 1
  //     },
  //     optionApi: async () => {
  //       const res = await getRoleListApi()
  //       return res.data?.list?.map((v) => ({
  //         label: v.roleName,
  //         value: v.id
  //       }))
  //     }
  //   }
  // },
  // {
  //   field: 'email',
  //   label: t('userDemo.email'),
  //   form: {
  //     component: 'Input'
  //   },
  //   search: {
  //     hidden: true
  //   }
  // },
  // {
  //   field: 'createTime',
  //   label: t('userDemo.createTime'),
  //   form: {
  //     component: 'Input'
  //   },
  //   search: {
  //     hidden: true
  //   }
  // },
  {
    field: 'action',
    label: t('userDemo.action'),
    fixed: 'right',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 200,
      slots: {
        default: (data: any) => {
          const row = data.row as DepartmentUserItem
          return (
            <>
              <BaseButton
                v-hasPermi={['edit', directivesArgs]}
                size="small"
                type="primary"
                onClick={() => action(row, 'edit')}
              >
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton size="small" type="success" onClick={() => action(row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              <BaseButton
                size="small"
                v-hasPermi={['del', directivesArgs]}
                type="danger"
                onClick={() => delData(row)}
              >
                {t('exampleDemo.del')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref<any>({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}

const resetSearchParams = (params) => {
  currentPage.value = 1
  searchParams.value = params
  currentNodeKey.value = ''
  getList()
}

const treeEl = ref<typeof ElTree>()

const currentNodeKey = ref('')
const departmentList = ref<DepartmentItem[]>([])
const defaultExpandedKeys = ref()
const fetchDepartment = async () => {
  const res = await getDeptTree({})
  departmentList.value = res.data
  if (res.data.length) {
    defaultExpandedKeys.value = res.data.map((i) => i.id)
  }
  // currentNodeKey.value = (res.data[0] && res.data[0]?.children && res.data[0].children[0].id) || ''
  await nextTick()
  // unref(treeEl)?.setCurrentKey(currentNodeKey.value)
}
fetchDepartment()

const currentDepartment = ref('')
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

// const currentChange = (data: DepartmentItem) => {
//   // if (data.children) return
//   console.log(toRaw(data))
//   currentNodeKey.value = toRaw(data).id
//   currentPage.value = 1
//   getList()
// }

const nodeClick = (data) => {
  currentNodeKey.value = toRaw(data).id
  currentPage.value = 1
  getList()
}

const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data?.name.includes(value)
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<DepartmentUserItem>()
const actionType = ref('')

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

const delLoading = ref(false)

const delData = async (row) => {
  ElMessageBox.confirm('确认删除？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await delUser({ userId: toRaw(row)?.userId })
    getList()
  })
}

const selectUsers = ref<any>([])

const allDelData = async () => {
  if (!selectUsers.value.length) {
    ElMessage.warning('请选择要删除的人员')
    return
  }
  ElMessageBox.confirm('确认删除？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await delUsers({ userIds: selectUsers.value })
    getList()
  })
}

const action = async (row, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  const res = await queryUser({ userId: row?.userId })
  currentRow.value = { ...res.data, department: unref(treeEl)?.getCurrentNode() || {} }
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)
// 人员勾选
const handleSelect = (selection) => {
  if (selection.length) {
    selectUsers.value = selection.map((i) => i.userId)
  } else selectUsers.value = []
}

const save = async () => {
  const write = unref(writeRef)
  let formData = await write?.submit()
  if (!formData) return
  formData = {
    ...formData,
    deptIds: toRaw(formData?.deptIds)
  }
  console.log(toRaw(formData))
  if (formData) {
    saveLoading.value = true

    let res
    if (actionType.value === 'edit') {
      res = await updateUser(formData)
    } else {
      res = await addUser(formData)
    }
    saveLoading.value = false

    const { success } = res
    if (success) {
      dialogVisible.value = false
      getList()
    }
  }
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px h-100% !overflow-y-auto">
      <div class="flex justify-center items-center">
        <div class="flex-1">{{ t('userDemo.departmentList') }}</div>
        <el-input
          v-model="currentDepartment"
          class="flex-[2]"
          :placeholder="t('userDemo.searchDepartment')"
          clearable
        />
      </div>
      <el-divider />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        :expand-on-click-node="false"
        :default-expanded-keys="defaultExpandedKeys"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'name'
        }"
        :filter-node-method="filterNode"
        @node-click="nodeClick"
      >
        <!--        @current-change="currentChange"-->
        <template #default="{ data }">
          <div :title="data.name" class="whitespace-nowrap overflow-ellipsis overflow-hidden">
            {{ data.name }}
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="resetSearchParams"
        @search="setSearchParams"
      />

      <div class="mb-10px">
        <BaseButton type="primary" v-hasPermi:[directivesArgs]="'add'" @click="AddAction"
          >{{ t('exampleDemo.add') }}
        </BaseButton>
        <BaseButton
          :loading="delLoading"
          type="danger"
          v-hasPermi:[directivesArgs]="'del'"
          @click="allDelData"
        >
          {{ t('exampleDemo.del') }}
        </BaseButton>
      </div>
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        @selection-change="handleSelect"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <Write
        :disabled="actionType === 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
      />

      <!--      <Detail-->
      <!--        v-if="actionType === 'detail'"-->
      <!--        :detail-schema="allSchemas.detailSchema"-->
      <!--        :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>
  </div>
</template>
