<template>
  <div class="external-auth-page flex-column card h-100 overflow-hidden">
    <div class="header-filter-form">
      <ElForm v-enter-submit="search" :inline="true">
        <ElFormItem label="账号类型">
          <ElSelect
            v-model="searchForm.type"
            clearable
            style="width: 180px"
            placeholder="请选择"
          >
            <ElOption
              v-for="(item, index) in accountTypes"
              :key="index"
              :label="item"
              :value="item"
            ></ElOption>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="">
          <ElButton type="primary" @click="search"> 查询 </ElButton>
        </ElFormItem>

        <ElFormItem>
          <ElButton type="success" @click="addDialog"> 新增 </ElButton>
        </ElFormItem>
        <ElFormItem>
          <ElButton type="danger" @click="deleteSection(null)"> 删除 </ElButton>
        </ElFormItem>
      </ElForm>
    </div>
    <div class="external-auth-content flex-1 flex-column overflow-hidden">
      <div class="external-auth-list flex-1 overflow-hidden">
        <tableView
          :selectionable="true"
          :paginated-data="tableData"
          :columns="tableColumns"
          @selection-change="handleSelectionChange"
        ></tableView>
      </div>
      <ElPagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[100, 200, 300, 400, 500]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: 10px auto 0; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></ElPagination>
    </div>
  </div>
  <ElDialog
    v-model="dialogVisible"
    :title="!!editId ? '新增' : '编辑'"
    :close-on-click-modal="false"
    width="600px"
    @opened="handleOpened"
  >
    <ElForm
      ref="editFormRef"
      label-position="right"
      label-width="110px"
      :model="editForm"
    >
      <ElFormItem
        label="账号类型"
        prop="type"
        :rules="[{ required: true, message: '请选择账号类型' }]"
      >
        <ElSelect
          v-model="editForm.type"
          style="width: 100%"
          placeholder="请选择"
          clearable
        >
          <ElOption
            v-for="(item, index) in accountTypes"
            :key="index"
            :label="item"
            :value="item"
          ></ElOption>
        </ElSelect>
      </ElFormItem>
      <ElFormItem
        label="账号"
        prop="account"
        :rules="[{ required: true, message: '请输入账号' }]"
      >
        <ElInput
          v-model="editForm.account"
          clearable
          placeholder="请输入"
        ></ElInput>
      </ElFormItem>
      <ElFormItem label="是否默认" prop="defaultType">
        <ElRadioGroup v-model="editForm.defaultType" clearable>
          <ElRadio :label="true">是</ElRadio>
          <ElRadio :label="false">否</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem
        v-if="editForm.type === 'RIIN' && editForm.type"
        label="授权操作指引"
      >
        <el-image
          style="width: 100px; height: 100px"
          src="https://jomalls-test.oss-cn-hangzhou.aliyuncs.com/riin-demo.png"
          :zoom-rate="1.2"
          :max-scale="7"
          :min-scale="0.2"
          :preview-src-list="[
            'https://jomalls-test.oss-cn-hangzhou.aliyuncs.com/riin-demo.png',
          ]"
          show-progress
          :initial-index="4"
        />
      </ElFormItem>
      <ElFormItem
        v-if="editForm.type !== 'RIIN' && editForm.type"
        label="appKey"
        prop="appKey"
        :rules="[{ required: true, message: '请输入appKey' }]"
      >
        <ElInput
          v-model="editForm.appKey"
          clearable
          placeholder="请输入"
        ></ElInput>
      </ElFormItem>
      <ElFormItem
        v-if="editForm.type === 'RIIN' && editForm.type"
        label="appSecret"
        prop="appSecret"
        :rules="[{ required: true, message: '请输入appSecret' }]"
      >
        <ElInput
          v-model="editForm.appSecret"
          clearable
          placeholder="请输入"
        ></ElInput>
      </ElFormItem>
      <ElFormItem
        v-if="editForm.type !== 'RIIN' && editForm.type"
        label="token"
        prop="token"
        :rules="[{ required: true, message: '请输入token' }]"
      >
        <ElInput
          v-model="editForm.token"
          clearable
          placeholder="请输入"
        ></ElInput>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false"> 取消 </ElButton>
        <ElButton type="primary" @click="submit"> 确认 </ElButton>
      </div>
    </template>
  </ElDialog>
</template>
<script setup lang="tsx">
import { computed, ref, onMounted } from 'vue'
import TableView from '@/components/TableView.vue'
import usePageList from '@/utils/hooks/usePageList'
import { useValue } from '@/utils/hooks/useValue'
import {
  getExternalAuthorisationListApi,
  loadAccountTypesApi,
  addExternalAuthorisationApi,
  getExternalAuthorisationByIdApi,
  deleteExternalAuthorisationApi,
} from '@/api/externalAuth'
import { ExternalAuthListData } from '@/types/api/externalAuth'
import { Delete, Edit } from '@element-plus/icons-vue'
const accountTypes = ref<string[]>([])
const searchForm = ref({
  type: '',
})
const dialogVisible = ref(false)
const editId = ref<null | number>(null)
const [editForm, resetEditForm] = useValue<ExternalAuthListData>({
  type: '',
  defaultType: false,
  appKey: '',
  appSecret: '',
  token: '',
  account: '',
})
const tableColumns = computed(() => {
  return [
    {
      label: '账号',
      prop: 'account',
      align: 'center',
    },
    {
      label: '账号类型',
      prop: 'type',
      align: 'left',
    },
    {
      label: '是否默认',
      prop: 'defaultType',
      width: 100,
      align: 'center',
      render: (item: ExternalAuthListData) => (
        <el-checkbox
          true-value={true}
          false-value={false}
          modelValue={item.defaultType}
          disabled
        ></el-checkbox>
      ),
    },
    {
      label: 'appKey',
      prop: 'appKey',
      align: 'left',
    },
    { label: 'appSecret', prop: 'appSecret', align: 'left' },
    { label: 'token', prop: 'token', align: 'left' },
    { label: 'refreshToken', prop: 'refreshToken', align: 'left' },
    {
      label: 'refreshToken 过期时间',
      prop: 'refreshTokenFailureTime',
    },
    {
      label: '相关操作',
      width: 100,
      fixed: 'right',
      align: 'center',
      render: (item: ExternalAuthListData) => (
        <div>
          {
            <span style="margin-right: 10px" title="编辑">
              <el-icon
                size="24"
                title="编辑"
                color="#EF6C00"
                style="cursor: pointer"
                onClick={() => editDialog(item)}
              >
                <Edit />
              </el-icon>
            </span>
          }

          {
            <span title="删除">
              <el-icon
                size="24"
                title="删除"
                color="#f56c6c"
                style="cursor: pointer"
                onClick={() => deleteSection(item)}
              >
                <Delete />
              </el-icon>
            </span>
          }
        </div>
      ),
    },
  ]
})
const {
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) =>
    getExternalAuthorisationListApi(searchForm.value, page, pageSize).then(
      (res) => res.data,
    ),
})
const loadAccountTypes = async () => {
  try {
    const res = await loadAccountTypesApi()
    if (res.code !== 200) return
    accountTypes.value = res.data
  } catch (e) {
    console.error(e)
  }
}
const addDialog = () => {
  editId.value = null
  dialogVisible.value = true
  resetEditForm()
}
const editDialog = async (item: ExternalAuthListData) => {
  editId.value = item.id || null
  try {
    const res = await getExternalAuthorisationByIdApi(item.id || null)
    if (res.code !== 200) return
    editForm.value = res.data
    dialogVisible.value = true
  } catch (e) {
    console.error(e)
  }
}
const editFormRef = ref()
const deleteSection = async (item: ExternalAuthListData | null) => {
  if (!item) {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请选择要删除的账号')
      return
    }
  }
  const ids = item ? [item.id] : selectedRows.value.map((item) => item.id)
  try {
    await ElMessageBox.confirm('确定删除所选账号吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const res = await deleteExternalAuthorisationApi(ids.join(','))
    if (res.code !== 200) return
    ElMessage.success('删除成功')
    search()
  } catch (e) {
    console.error(e)
  }
}
const submit = async () => {
  try {
    await editFormRef.value.validate()
  } catch {
    return
  }
  const url = editId.value
    ? 'factory/baseExternalAccount/update'
    : 'factory/baseExternalAccount/add'
  try {
    const res = await addExternalAuthorisationApi(url, editForm.value)
    if (res.code !== 200) return
    dialogVisible.value = false
    search()
  } catch (e) {
    console.error(e)
  }
}
const handleOpened = () => {
  editFormRef.value.clearValidate()
}
const selectedRows = ref<ExternalAuthListData[]>([])
const handleSelectionChange = (val: ExternalAuthListData[]) => {
  selectedRows.value = val
}
onMounted(() => {
  loadAccountTypes()
})
</script>
<style lang="scss" scoped>
.header-filter-form {
  margin-bottom: 20px;

  :deep(.el-form-item) {
    margin-right: 14px;
    margin-bottom: 10px;
  }
}
.dialog-footer {
  text-align: center;
}
</style>
