<template>
  <div class="user" >
    <div style="position: relative;margin-right: 5px">
      <div class="user3Item" :style="{ display: !collapsed ? '' : 'none' }">
        <n-tree
          :data="nodes"
          :default-expanded-keys="['level1', 'level2-3','level2-2','level2-1']"
          block-line
        />
      </div>
      <div class="user3ItemIndex"  :style="{left:!collapsed?'235px':0}" @click="()=>(collapsed = !collapsed)">
         <div :class="[!collapsed ? 'user3ItemIndexCollapsedTop' : 'user3ItemIndexCollapsedTopHidden']"></div>
         <div :class="[!collapsed ? 'user3ItemIndexCollapsedButton' : 'user3ItemIndexCollapsedButtonHidden']"></div>
      </div>
    </div>
    <div>
      <div class="userItem">
        <TablePro ref="tableRef"  :request-api="reqApi" :search-form-options="searchFormOptions" :columns="columns" :single-line="false" :isPageTable="true" :max-height="520">
          <template #headerExtra>
            <n-button strong secondary type="primary" @click="addOrUpdateUser"> 添加用户 </n-button>
          </template>
        </TablePro>
      </div>
    </div>

  </div>
</template>
<script setup lang="tsx">
  import { NButton, useModal, useMessage, NPopconfirm, type FormInst, type FormItemRule } from 'naive-ui'
  import { TablePro, type TableProProps, FormPro, type FormItemOptions, type TableProInst } from '@/components'
  import api from '@/axios'
  import { reactive, ref, useTemplateRef } from 'vue'
  import userInfo, { type userInterface } from './index'
  import { enumSelectNodes } from '@/utils/emnus.ts'
  import { adminUserId } from '@/config/constant.ts'
  type TableType = TableProProps<any, any>
  const tableRef = useTemplateRef<TableProInst>('tableRef')
  const modal = useModal()
  const message = useMessage()

  const collapsed = ref(false);

  const nodes = ref([
    {
      label: '顶级（一级）',
      key: 'level1',
      children: [
        {
          label: '事业部1（二级）',
          key: 'level2-1',
          children: [
            {
              label: '医院（三级）',
              key: 'level2-1-1'
            },
            {
              label: '学校（三级）',
              key: 'level2-1-2'
            },
            {
              label: '小学（三级）',
              key: 'level2-1-3'
            }
          ]
        },
        {
          label: '事业部2（二级）',
          key: 'level2-2',
          children: [
            {
              label: '医院（三级）',
              key: 'level2-2-1'
            },
            {
              label: '学校（三级）',
              key: 'level2-2-2'
            },
            {
              label: '小学（三级）',
              key: 'level2-2-3'
            }
          ]
        },
        {
          label: '事业部3（二级）',
          key: 'level2-3',
          children: [
            {
              label: '医院（三级）',
              key: 'level2-3-1'
            },
            {
              label: '学校（三级）',
              key: 'level2-3-2'
            },
            {
              label: '小学（三级）',
              key: 'level2-3-3'
            }
          ]
        },
        {
          label: '技术部（二级）',
          key: 'level2-4',
          children: [
            {
              label: '医院（三级）',
              key: 'level2-4-1'
            },
            {
              label: '学校（三级）',
              key: 'level2-4-2'
            },
            {
              label: '小学（三级）',
              key: 'level2-4-3'
            }
          ]
        },
        {
          label: '研发部（二级）',
          key: 'level2-5',
          children: [
            {
              label: '医院（三级）',
              key: 'level2-5-1'
            },
            {
              label: '学校（三级）',
              key: 'level2-5-2'
            },
            {
              label: '小学（三级）',
              key: 'level2-1-3'
            }
          ]
        }
      ]
    }
  ])
  const reqApi: TableType['requestApi'] = (params) => {
    return new Promise((resolve) => {
      resolve({
        code: 200,
        data: {
          current: "1",
          // @ts-ignore
          pages: "2",
          records: userInfo,
          size: "5",
          total: "12"
        },
        message: "操作成功！"
      });
    });
    // return api.post('/management/user/pager', params)
  }

  const form = ref<FormInst | null>(null)

  const searchFormOptions = reactive<TableType['searchFormOptions']>({
    name: {
      type: 'input',
      label: '用户名',
    },
  })

  const userDefaultValue: userInterface = {
    // snowFlakeId: "",
    avatar: '',
    name: '',
    sex: '',
    phoneNumber: '',
    status: 'enable',
    authClient: [],
    deptIds: [],
    roleIds: [],
  }

  const userValue = ref<userInterface>({
    ...userDefaultValue,
  })

  const resetModelValue = () => {
    userValue.value = { ...userDefaultValue }
    title.value = '添加用户'
  }
  const formOptionsUser = reactive<FormItemOptions<userInterface>>({
    // 头像
    avatar: {
      type: 'custom',
      label: '头像',
      customRender: (val) => {
        return (
          <div>
            <n-avatar
              round
              size="large"
              src={val.avatar}
            />
          </div>
        );
      }
    },
    name: {
      type: 'input',
      label: '用户名',
      required: true,
    },

    sex: {
      type: 'radioGroup',
      label: '性别',
      required: true,
      options: [
        {
          label :"男",
          value:"man"
        },
        {
          value:'woman',
          label:'女'
        }
      ], //man 、 woman
    },
    phoneNumber: {
      type: 'input',
      label: '手机号',
      required: true,
    },
    status: {
      type: 'radioGroup',
      label: '账号状态',
      required: true,
      options: [
        {
          value:'disable',
          label:'禁用'
        },
        {
          value:'enable',
          label:'启用'
        }
      ], //enable 、 disable
    },
    deptIds: {
      type: 'treeSelect',
      label: '所属部门',
      options: [
        {
          value:'技术部',
          label:'技术部'
        },
        {
          value:'食堂部',
          label:'食堂部'
        }
      ],
      componentsProps: {
        multiple: true,
      },
    },
    roleIds: {
      type: 'select',
      label: '角色',
      options: [
        {
          value:'普通员工',
          label:'普通员工'
        },
        {
          value:'超级管理员',
          label:'超级管理员'
        }
      ],
      componentsProps: {
        multiple: true,
      },
    },
  })

  const modalRef = ref()
  const title = ref('添加用户')
  const addOrUpdateUser = () => {
    modalRef.value = modal.create({
      title: title.value,
      preset: 'card',
      style: {
        width: '400px',
      },
      content: () => (
        <>
          <FormPro labelWidth='100' ref={form}  v-model:value={userValue.value} form-item-options={formOptionsUser} />
        </>
      ),
      footer: () => (
        <div
          style={{
            display: 'flex',
            justifyContent: 'flex-end',
          }}
        >
          <n-button
            loading={loading.value}
            style={{ marginRight: '10px' }}
            type='primary'
            onClick={() => {
              addUserOrUpdate()
            }}
          >
            确认
          </n-button>
          <n-button
            onClick={() => {
              modalRef.value.destroy()
              resetModelValue()
            }}
          >
            取消
          </n-button>
        </div>
      ),
      onAfterLeave: () => {
        resetModelValue()
      },
    })
  }
  function extractValues(data: any[]) {
    return data.map((item: { value: any }) => item.value)
  }

  // 新增按钮调接口
  const addUserOrUpdate = async (params?: any) => {
    form.value?.validate().then(async () => {
          return 12132
    })
  }
  const loading = ref<boolean>(false)
  const columns = ref<TableType['columns']>([
    {
      key: 'name',
      title: '用户名',
      width: 150,
    },
    {
      key: 'phoneNumber',
      title: '手机号',
      width: 150,
      render: ({ phoneNumber }) => {
        return <span>{phoneNumber}</span>
      },
    },
    {
      key: 'lastLoginTime',
      title: '上次登录',
      width: 150,
    },
    {
      key: 'sex',
      title: '性别',
      width: 150,
      render: ({ sex }) => {
        return  <n-tag type="success">
          {sex === 'man'?'男':'女'}
        </n-tag>
      },
    },
    {
      key: 'status',
      title: '状态',
      width: 150,
      render: ({ status }) => {
        return  <n-tag type={status === 'enable'?'success':'error'}>
          {status === 'enable'?'启用':'禁用'}
        </n-tag>
      },
    },
    {
      key: '',
      title: '操作',
      width: 150,
      render: (value) => {
        return <div style={{ display: 'flex' }}>
          <n-button
            strong
            secondary
            style={{ marginLeft: '10px' }}
            type='warning'
            onClick={() => {
              title.value = `${value.name} 修改`
              userValue.value.snowFlakeId = value.snowFlakeId
              userValue.value.avatar = value.avatar
              userValue.value.name = value.name
              userValue.value.sex = value.sex
              userValue.value.status = value.status
              userValue.value.phoneNumber = value.phoneNumber
              // userValue.value.deptIds = extractValues(value.deptList)
              // userValue.value.roleIds = extractValues(value.roleList)
              // userValue.value.authClient = extractValues(value.authClient)

              modalRef.value = modal.create({
                title: title.value,
                preset: 'card',
                style: {
                  width: '400px',
                },
                content: () => (
                  <>
                    <FormPro labelWidth='100' ref={form} v-model:value={userValue.value} form-item-options={formOptionsUser} />
                  </>
                ),
                footer: () => (
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'flex-end',
                    }}
                  >
                    <n-button
                      loading={loading.value}
                      style={{ marginRight: '10px' }}
                      type='primary'
                      onClick={() => {
                        addUserOrUpdate(value.snowFlakeId)
                      }}
                    >
                      确认
                    </n-button>
                    <n-button
                      onClick={() => {
                        modalRef.value.destroy()
                        resetModelValue()
                      }}
                    >
                      取消
                    </n-button>
                  </div>
                ),
                onAfterLeave: () => {
                  resetModelValue()
                },
              })
            }}
          >
            编辑
          </n-button>

          <NPopconfirm
            onPositiveClick={async () => {
            }}
            onNegativeClick={() => {
            }}
            showIcon={false}
          >
            {{
              trigger: () => (
                <n-button
                  strong
                  secondary
                  style={{ marginLeft: "10px" }}
                  type="error"
                >
                  删除
                </n-button>
              ),
              default: () => "确认要除么？"
            }}
          </NPopconfirm>
        </div>
      },
    },
  ])
</script>
<style scoped lang="scss">
  .user{
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
    .userItem {
      width: 100%;
      height: 83vh;
      background: var(--bg-color);
      margin-bottom: 10px;
      box-shadow: 0 1px 2px 0 rgba(0, 0, 0, .05);
      padding: 10px 15px;
      color:var(--text-color);
      .homeItemIndex{
        margin-bottom: 10px;
        line-height: 1.6;
        border-left: 5px solid #5FB878;
        border-radius: 0 2px 2px 0;
        padding-left: 10px;
        .homeSpan{
          display: inline-block;
          padding: 0 6px;
          font-size: 12px;
          text-align: center;
          background-color: #FF5722;
          color: #fff;
          border-radius: 2px
        }
      }
    }
    .user3Item{
      height: 84vh;
      width: 200px;
      position: relative;
      margin-bottom: 15px;
      border-radius: 2px;
      background: var(--bg-color);
      box-shadow: 0 1px 2px 0 rgba(0, 0, 0, .05);
      padding: 10px 15px;
      color:var(--text-color);
      overflow-y: auto

    }
    .user3ItemIndex{
      position: absolute;
      text-align: center;
      height: 75px;
      line-height: 34px;
      width: 50px;
      z-index: 1;
      visibility: visible;
      overflow: hidden;
      cursor: pointer;
      top: calc(50% - 72px);
      left: 200px;
      transition: all .2s, background 0s;
      .user3ItemIndexCollapsedTop{
        position: absolute;
        left: 5px;
        transition: transform .3s cubic-bezier(.4,0,.2,1), background-color .3s cubic-bezier(.4,0,.2,1), width .3s cubic-bezier(.4,0,.2,1);
        width: 4px;
        height: 38px;
        border-radius: 2px;
        background-color: #bfbfbf
      }
      .user3ItemIndexCollapsedTopHidden{
        position: absolute;
        left: 5px;
        transition: transform .3s cubic-bezier(.4,0,.2,1), background-color .3s cubic-bezier(.4,0,.2,1), width .3s cubic-bezier(.4,0,.2,1);
        width: 4px;
        height: 38px;
        border-radius: 2px;
        background-color: #bfbfbf
      }
      .user3ItemIndexCollapsedButton{
        position: absolute;
        left: 5px;
        top: 34px;
        transition: transform .3s cubic-bezier(.4,0,.2,1), background-color .3s cubic-bezier(.4,0,.2,1), width .3s cubic-bezier(.4,0,.2,1);
        width: 4px;
        height: 38px;
        border-radius: 2px;
        background-color: #bfbfbf;
      }
      .user3ItemIndexCollapsedButtonHidden{
        position: absolute;
        left: 5px;
        top: 34px;
        transition: transform .3s cubic-bezier(.4,0,.2,1), background-color .3s cubic-bezier(.4,0,.2,1), width .3s cubic-bezier(.4,0,.2,1);
        width: 4px;
        height: 38px;
        border-radius: 2px;
        background-color: #bfbfbf;
      }
    }
    .user3ItemIndex:hover .user3ItemIndexCollapsedTop{
      background: #d9d9d9;
      transform: rotate(15deg);
      width: 4px;
    }
    .user3ItemIndex:hover .user3ItemIndexCollapsedTopHidden{
      background: #d9d9d9;
      transform: rotate(-15deg);
      width: 4px;
      height: 38px;
    }
    .user3ItemIndex:hover .user3ItemIndexCollapsedButton{
      background: #d9d9d9;
      transform: rotate(-15deg);
      width: 4px;
    }
    .user3ItemIndex:hover .user3ItemIndexCollapsedButtonHidden{
      background: #d9d9d9;
      transform: rotate(15deg);
      width: 4px;
      height: 38px;
    }
  }

</style>
