<template>
  <div class="user-page flex-column card h-100 overflow-hidden">
    <div class="header-filter-form">
      <ElForm :model="searchForm" inline>
        <ElFormItem label="客户识别码" prop="sku">
          <ElInput
            v-model="searchForm.sku"
            placeholder="请输入客户识别码"
            clearable
            style="width: 200px"
          />
        </ElFormItem>
        <ElFormItem label="客户标识" prop="userMark">
          <ElInput
            v-model="searchForm.userMark"
            placeholder="请输入客户标识"
            clearable
            style="width: 200px"
          />
        </ElFormItem>
        <ElFormItem>
          <ElButton type="primary" @click="search">查询</ElButton>
        </ElFormItem>
        <ElFormItem>
          <ElButton @click="resetSearchForm">重置</ElButton>
        </ElFormItem>
        <ElFormItem>
          <ElButton type="success" @click="addUser">绑定客户</ElButton>
        </ElFormItem>
      </ElForm>
    </div>
    <div class="user-content flex-1 flex-column overflow-hidden">
      <div class="user-list flex-1 overflow-hidden">
        <ElTable
          :data="tableData"
          default-expand-all
          style="width: 100%; height: 100%"
        >
          <ElTableColumn
            type="index"
            header-align="center"
            align="center"
            label="序号"
            width="55"
          />
          <ElTableColumn
            prop="sku"
            header-align="center"
            align="center"
            label="客户识别码"
          />
          <ElTableColumn
            prop="userMark"
            header-align="center"
            align="center"
            label="客户标识"
          />
          <ElTableColumn
            label="操作"
            width="130"
            header-align="center"
            align="center"
          >
            <template #default="scope">
              <el-icon
                size="24"
                title="解除绑定"
                color="#f56c6c"
                style="cursor: pointer; vertical-align: middle"
                @click="editUser(scope.row)"
              >
                <Delete />
              </el-icon>
            </template>
          </ElTableColumn>
        </ElTable>
      </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="!relId ? '绑定客户' : '解绑客户'"
    width="600px"
    :close-on-click-modal="false"
    @opened="onOpenedUserForm"
  >
    <div class="dialog-form">
      <ElForm
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        label-width="120px"
      >
        <ElFormItem label="客户识别码：" prop="sku">
          <ElInput
            v-if="!relId"
            v-model="editForm.sku"
            placeholder="请输入客户识别码"
            clearable
          >
            <template #append>
              <el-button :icon="Search" @click="getSkuByInfo"></el-button>
            </template>
          </ElInput>
          <span v-else style="font-weight: bold">{{ editForm.sku }}</span>
        </ElFormItem>
        <ElFormItem label="客户标识：" prop="userMark">
          <span style="font-weight: bold">{{ editForm.userMark }}</span>
        </ElFormItem>
      </ElForm>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false"> 取消 </ElButton>
        <ElButton type="primary" @click="save">确定</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { getBySkuApi, addRelApi, removeRelApi, getRelList } from '@/api/auth'
import { customData, customSearchForm } from '@/types/api/user'
import usePageList from '@/utils/hooks/usePageList'
import { useValue } from '@/utils/hooks/useValue'
import { Delete, Search } from '@element-plus/icons-vue'
import type { FormRules } from 'element-plus'
import { reactive, ref } from 'vue'
const [searchForm, resetSearchForm] = useValue<customSearchForm>({})
const [editForm, resetEditForm] = useValue<customSearchForm>({
  sku: '',
  userMark: '',
  id: '',
})
const {
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) =>
    getRelList(searchForm.value, page, pageSize).then((res) => res.data),
})
const dialogVisible = ref(false)
const editFormRef = ref()
// const selection = ref<customData[]>([])
const rules = reactive<FormRules<customSearchForm>>({
  sku: [
    {
      required: true,
      message: '请输入客户识别码',
    },
  ],
})
const getSkuByInfo = async () => {
  if (!editForm.value.sku) {
    return ElMessage({
      message: '请输入sku',
      type: 'warning',
      offset: window.innerHeight / 2,
    })
  }
  try {
    const res = await getBySkuApi(editForm.value.sku)
    if (res.code == 200) {
      editForm.value.userMark = res.data?.userMark || ''
      editForm.value.id = res.data?.id || ''
    }
  } catch (e) {
    // showError(e)
  }
}
const relId = ref<number | undefined>(undefined)
const addUser = () => {
  relId.value = undefined
  dialogVisible.value = true
  resetEditForm()
}
const editUser = async (item: customData) => {
  relId.value = item.relId
  editForm.value.sku = item.sku
  editForm.value.userMark = item.userMark
  dialogVisible.value = true
}
const save = async () => {
  try {
    await editFormRef.value.validate()
  } catch {
    return
  }
  try {
    if (!relId.value) {
      if (!editForm.value.id) {
        return ElMessage({
          message: '请根据SKU查询对应的客户标识',
          type: 'warning',
          offset: window.innerHeight / 2,
        })
      }
      await addRelApi(editForm.value.id)
    } else {
      await removeRelApi(relId.value)
    }
    ElMessage({
      message: '保存成功',
      type: 'success',
      offset: window.innerHeight / 2,
    })
    dialogVisible.value = false
    search()
  } catch (e) {
    return
  }
}
const onOpenedUserForm = async () => {
  editFormRef.value?.clearValidate()
}

// const handleSelectionChange = (s: customData[]) => {
//   selection.value = s
// }
</script>

<style lang="scss" scoped>
.header-filter-form {
  margin-bottom: 20px;

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