<!--
 * @Author: 半生瓜 1515706227@qq.com
 * @Date: 2024-05-06 19:31:40
 * @LastEditors: 半生瓜 1515706227@qq.com
 * @LastEditTime: 2024-05-28 10:02:32
 * @FilePath: \vue-element-plus-admin-mini\src\views\zy\Menu12.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import {
  ElInput,
  ElButton,
  ElRadio,
  ElRadioButton,
  ElMessageBox,
  ElMessage,
  FormItemRule
} from 'element-plus'
import { ref } from 'vue'
import { encrypt, decrypt, randomString, RsaencryptedData } from '@/utils/aes.js'
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn, TableSlotDefault } from '@/components/Table'
import { getUser, saveUser, deleteUser, getUserDetail } from '@/api/user'
import { getRoleAll } from '@/api/role'
import { reactive, unref, onMounted } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { Dialog } from '@/components/Dialog'
import { Form, FormSchema, RadioOption } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { BaseButton } from '@/components/Button'
import { getRsaKey } from '@/api/login'
import { cloneDeep } from 'lodash-es'
const { required, noSpaceOrSpecialChars, validateMobile } = useValidator()

defineOptions({
  name: 'TemplateManage'
})

const rules = reactive<{
  [key: string]: FormItemRule[]
}>({
  password: [
    {
      validator: (rule, value, callback) =>
        noSpaceOrSpecialChars(value, callback, '不包含中文、空格、特殊字符')
    }
  ],
  userCode: [
    {
      validator: (rule, value, callback) => validateMobile(value, callback, '请输入正确手机号')
    }
  ]
})

//  加密
const encryptedData = function (publicKey, data) {
  // 新建JSEncrypt对象
  let encryptor = new JSEncrypt()
  // 设置公钥
  encryptor.setPublicKey(publicKey)
  // 加密数据
  return encryptor.encrypt(data)
}

const isedit = ref('编辑用户')
//角色列表
const rolelists = reactive([] as { label: any; value: any }[])
onMounted(async () => {
  const res = await getRoleAll()
  res.data.map((item) => {
    let a1 = {
      label: item.roleName,
      value: String(item.roleId)
    }
    rolelists.push(a1)
  })
  console.log('jkjkjkjk', rolelists)
})

let schema = reactive<FormSchema[]>([
  {
    field: 'userCode',
    label: '账号',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: '请输入8位数字',
      disabled: isedit.value === '添加用户' ? false : true
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'displayName',
    label: '用户名',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: '请输入2-8中文字符'
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'password',
    label: '密码',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: '请输入8~16位包含数字、大小写字母，不包含空格，特殊字符'
    },
    formItemProps: {}
  },
  // {
  //   field: 'authorizationCode',
  //   label: '授权码',
  //   component: 'Input',
  //   colProps: {
  //     span: 24
  //   },
  //   componentProps: {
  //     style: {
  //       width: '100%'
  //     },
  //     placeholder: '请输入授权码'
  //   },
  //   formItemProps: {
  //     rules: [required()]
  //   }
  // },
  {
    field: 'hasManage',
    label: '是否进入后台',
    component: 'RadioGroup',
    colProps: {
      span: 24
    },
    formItemProps: {
      rules: [required()]
    },
    componentProps: {
      options: [
        {
          // disabled: true,
          label: '是',
          value: true
        },
        {
          label: '否',
          value: false
        }
      ]
    }
  },
  {
    field: 'roleIds',
    label: '选择角色',
    component: 'RadioGroup',
    formItemProps: {
      rules: [required()]
    },
    componentProps: {
      options: rolelists,
      slots: {
        default: (options: RadioOption[]) => {
          return options?.map((v) => {
            return <ElRadio style="width: 100px;" label={v.label} value={v.value} />
          })
        }
      }
    }
  }
])
const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods
// 添加yonghu
const signIn = async () => {
  const formRef = await getElFormExpose()
  const formData = await getFormData()

  await formRef?.validate(async (isValid) => {
    if (isValid) {
      rolelists.map((item) => {
        if (item.label == formData.roleIds) {
          formData.roleIds = item.value
        }
      })

      formData.roleIds = [formData.roleIds]
      const res2 = await getRsaKey()
      let nweformData = cloneDeep(formData)
      if (nweformData.password) {
        nweformData.password = encryptedData(res2.data, formData.password)
      }

      nweformData.userCode = encryptedData(res2.data, formData.userCode)
      // nweformData.authorizationCode = encryptedData(res2.data, formData.authorizationCode)
      let res = await saveUser(nweformData)
      if (res) {
        dialogVisible.value = false
        if (isedit.value == '添加用户') {
          ElMessage.success('添加成功')
        } else {
          ElMessage.success('编辑成功')
        }
        refresh()
      } else {
        rolelists.map((item) => {
          if (item.value == formData.roleIds) {
            formData.roleIds = item.label
          }
        })
      }
    }
  })
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState

    const res2 = await getRsaKey()
    let key2 = randomString()
    let key = encryptedData(res2.data, key2)
    console.log('kkaakakakaka', key)
    const res = await getUser({
      page: unref(currentPage),
      pageSize: unref(pageSize),
      userCode: unref(userCode),
      displayName: unref(displayName),
      key
    })

    res.data.content.map((item) => {
      item.userCode = decrypt(item.userCode, key2)
    })
    return {
      list: res.data.content,
      total: res.data.totalElements
    }
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { refresh, getElTableExpose } = tableMethods
const { t } = useI18n()

const columns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection'
  },
  {
    field: 'displayName',
    label: '用户名'
  },
  {
    field: 'userCode',
    label: '账号'
  },
  {
    field: 'roleNames',
    label: '角色'
  },
  {
    field: 'updateTime',
    label: '更新时间'
  },
  {
    field: 'roleNames',
    label: t('tableDemo.action'),
    slots: {
      default: (data) => {
        return (
          <>
            <ElButton type="primary" onClick={() => editUser(data)}>
              {t('tableDemo.edit')}
            </ElButton>
            <ElButton type="danger" onClick={() => handerdeleteUser(data)}>
              {t('tableDemo.delete')}
            </ElButton>
          </>
        )
      }
    }
  }
])

//编辑
const editUser = async (data) => {
  isedit.value = '编辑用户'

  schema = reactive<FormSchema[]>([
    {
      field: 'userCode',
      label: '账号',
      component: 'Input',
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '100%'
        },
        placeholder: '请输入电话号码',
        disabled: isedit.value === '添加用户' ? false : true
      },
      formItemProps: {
        rules: [required()]
      }
    },
    {
      field: 'displayName',
      label: '用户名',
      component: 'Input',
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '100%'
        },
        placeholder: '请输入2-8中文字符'
      },
      formItemProps: {
        rules: [required()]
      }
    },
    {
      field: 'password',
      label: '密码',
      component: 'Input',
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '100%'
        },
        placeholder: '请输入8~16位包含数字、大小写字母，不包含空格，特殊字符'
      },
      formItemProps: {}
    },
    // {
    //   field: 'authorizationCode',
    //   label: '授权码',
    //   component: 'Input',
    //   colProps: {
    //     span: 24
    //   },
    //   componentProps: {
    //     style: {
    //       width: '100%'
    //     },
    //     placeholder: '请输入授权码'
    //   },
    //   formItemProps: {
    //     rules: [required()]
    //   }
    // },
    {
      field: 'hasManage',
      label: '是否进入后台',
      component: 'RadioGroup',
      colProps: {
        span: 24
      },
      formItemProps: {
        rules: [required()]
      },
      componentProps: {
        options: [
          {
            // disabled: true,
            label: '是',
            value: true
          },
          {
            label: '否',
            value: false
          }
        ]
      }
    },
    {
      field: 'roleIds',
      label: '选择角色',
      component: 'RadioGroup',
      formItemProps: {
        rules: [required()]
      },
      componentProps: {
        options: rolelists,
        slots: {
          default: (options: RadioOption[]) => {
            return options?.map((v) => {
              return <ElRadio style="width: 100px;" label={v.label} value={v.value} />
            })
          }
        }
      }
    }
  ])

  const res2 = await getRsaKey()
  let key2 = randomString()
  let key = encryptedData(res2.data, key2)
  let arr = {
    userId: data.row.userId,
    key
  }

  let res = await getUserDetail(arr)
  res.data.userCode = decrypt(res.data.userCode, key2)
  // res.data.authorizationCode = decrypt(res.data.authorizationCode, key2)
  if (res) {
    dialogVisible.value = true
    const formRef = await getElFormExpose()
    const formData = await getFormData()
    console.log('shanchu', formData)
    console.log('shanchu22', formRef)
    formData.userCode = res.data.userCode
    formData.displayName = res.data.displayName
    formData.hasManage = res.data.hasManage
    // formData.authorizationCode = res.data.authorizationCode
    formData.roleIds = res.data.roleInfoList[0].roleName
    formData.userId = res.data.userId
  }
  console.log('22eddd', res)
}
//删除
const handerdeleteUser = async (data) => {
  ElMessageBox.confirm('确定删除该数据?')
    .then(async () => {
      console.log('shanchu', data)
      let arr = {
        userIds: [data.row.userId]
      }
      const res = await deleteUser(arr)

      if (res.code == 200) {
        ElMessage.success('删除成功')
      }
      refresh()
    })
    .catch(() => {
      // catch error
    })
}

//多选删除
const getSelections = async () => {
  const elTableRef = await getElTableExpose()
  const selections = elTableRef?.getSelectionRows()

  let arr = {
    userIds: []
  }
  if (selections) {
    arr.userIds = selections.map((item) => {
      return item.userId
    })
  }
  if (arr.userIds.length !== 0) {
    ElMessageBox.confirm('确定删除所选数据?')
      .then(async () => {
        const res = await deleteUser(arr)
        if (res.code == 200) {
          ElMessage.success('删除成功')
        }
        refresh()
      })
      .catch(() => {
        // catch error
      })
  } else {
    ElMessage.warning('请选择数据')
  }
}

const userCode = ref('')
const displayName = ref('')

const dialogVisible = ref(false)

//搜索
const handersearch = function () {
  tableState.currentPage.value = 1
  refresh()
}
const tianjia = async () => {
  isedit.value = '添加用户'
  schema = reactive<FormSchema[]>([
    {
      field: 'userCode',
      label: '账号',
      component: 'Input',
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '100%'
        },
        placeholder: '请输入电话号码',
        disabled: isedit.value === '添加用户' ? false : true
      },
      formItemProps: {
        rules: [required()]
      }
    },
    {
      field: 'displayName',
      label: '用户名',
      component: 'Input',
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '100%'
        },
        placeholder: '请输入2-8中文字符'
      },
      formItemProps: {
        rules: [required()]
      }
    },
    {
      field: 'password',
      label: '密码',
      component: 'Input',
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '100%'
        },
        placeholder: '请输入8~16位包含数字、大小写字母，不包含空格，特殊字符'
      },
      formItemProps: {
        rules: [required()]
      }
    },
    // {
    //   field: 'authorizationCode',
    //   label: '授权码',
    //   component: 'Input',
    //   colProps: {
    //     span: 24
    //   },
    //   componentProps: {
    //     style: {
    //       width: '100%'
    //     },
    //     placeholder: '请输入授权码'
    //   },
    //   formItemProps: {
    //     rules: [required()]
    //   }
    // },
    {
      field: 'hasManage',
      label: '是否进入后台',
      component: 'RadioGroup',
      colProps: {
        span: 24
      },
      formItemProps: {
        rules: [required()]
      },
      componentProps: {
        options: [
          {
            // disabled: true,
            label: '是',
            value: true
          },
          {
            label: '否',
            value: false
          }
        ]
      }
    },
    {
      field: 'roleIds',
      label: '选择角色',
      component: 'RadioGroup',
      formItemProps: {
        rules: [required()]
      },
      componentProps: {
        options: rolelists,
        slots: {
          default: (options: RadioOption[]) => {
            return options?.map((v) => {
              return <ElRadio style="width: 100px;" label={v.label} value={v.value} />
            })
          }
        }
      }
    }
  ])

  dialogVisible.value = true
}
</script>

<template>
  <ContentWrap>
    <div style="margin-bottom: 10px">
      <span style="color: #606266"> 账号：</span>
      <el-input
        v-model="userCode"
        style="width: 200px; height: 43px; margin: 7px"
        placeholder="请输入账号"
      />
      <span style="color: #606266"> 用户名：</span>
      <el-input
        v-model="displayName"
        style="width: 200px; height: 43px; margin: 7px"
        placeholder="请输入用户名"
      />
      <ElButton type="primary" size="large" @click="handersearch" :icon="Search">搜索</ElButton>
      <ElButton type="success" size="large" @click="tianjia" :icon="Edit">添加</ElButton>
      <ElButton type="danger" size="large" @click="getSelections" :icon="Delete">删除</ElButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :data="dataList"
      row-key="id"
      headerAlign="center"
      align="center"
      :loading="loading"
      sortable
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" maxHeight="250px" width="35rem" :title="isedit">
    <Form label-position="left" :rules="rules" :schema="schema" @register="formRegister" />

    <template #footer>
      <div style="width: 100%; display: flex; justify-content: center">
        <BaseButton
          style="font-size: 1rem; height: 2.2rem; margin: auto"
          type="primary"
          class="w-[15%]"
          @click="signIn"
        >
          确定
        </BaseButton>
      </div>
    </template>
  </Dialog>
</template>
