<script setup lang="tsx">
import { onMounted, reactive, ref, unref, watch } from 'vue'
import {
  delProduct,
  getProduct,
  getProductCategory,
  postProductStatus,
  postProductAudit
} from '@/api/goods'
import { getStoreList } from '@/api/store'
import { useI18n } from '@/hooks/web/useI18n'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import { BaseButton } from '@/components/Button'
import { goodsSearch } from '@/api/goods/types'
import {
  ElMessageBox,
  ElSwitch,
  ElDivider,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElMessage,
  ElText,
  // ElTabs,
  // ElTabPane
} from 'element-plus'
import type { Action } from 'element-plus'
import { TableImage } from '@/components/tableImage'
import BatchSet from './components/BatchSet.vue'
import { useSearch } from '@/hooks/web/useSearch'
import Icon from '@/components/Icon/src/Icon.vue'
import { useRouter } from 'vue-router'
const { push } = useRouter()
const { searchRegister, 
  // searchMethods
 } = useSearch()
// const { setSchema, setValues, getFormData } = searchMethods
const { t } = useI18n()
// tab切换查询参数
const tabsConfig = reactive({
  up: {
    title: '出售中商品',
    total: 0,
    search: { is_show: '1', is_del: '0', is_verify: '1' }
  }, //出售中商品
  dom: {
    title: '仓库中商品',
    total: 0,
    search: { is_show: '0', is_del: '0', is_verify: '1' }
  }, //仓库中商品
  examine: {
    title: '待审核商品',
    total: 0,
    search: { is_show: 'all', is_del: '0', is_verify: '0' }
  }, //待审核商品
  trash: {
    title: '商品回收站',
    total: 0,
    search: { is_show: 'all', is_del: '1', is_verify: 'all' }
  }, //商品回收站
  all: {
    title: '高级查询',
    total: 0,
    search: { is_show: 'all', is_del: 'all', is_verify: 'all' }
  } //高级查询
})
const currentPage = ref(1)
const pageSize = ref(10)
const dataList = ref<any[]>([])
const loading = ref(false)

onMounted(async () => {
  getStoreLists()
  try {
    getTabNumber('examine') //待审核商品数量
    getTabNumber('dom') //仓鼠中商品数量
    getTabNumber('trash') //商品回收站
    getList()
    getStroe()
  } catch (error) {
    console.error('Failed to fetch data:', error)
    // 可以在这里添加更详细的错误处理逻辑，例如显示错误信息给用户
  }
})
const getList = async () => {
  try {
    loading.value = true
    // 提取 unref 操作以减少冗余
    const page = unref(currentPage) || 1
    const limit = unref(pageSize) || 10
    const searchParamsValue = unref(searchParams)
    const { data } = await getProduct({
      page,
      limit,
      ...searchParamsValue
    })
    // 处理边界条件
    if (data && data.list && data.count !== undefined) {
      dataList.value = data.list.map((item) => {
        item.is_show_bol = Boolean(item.is_show)
        return item
      })
      tabsConfig[activeName.value].total = data.count
    } else {
      // 处理数据为空的情况
      dataList.value = []
      tabsConfig[activeName.value].total = 0
    }
  } catch (error) {
    // 异常处理
    console.error('获取产品列表失败:', error)
    // 可以在这里添加错误提示或其他处理逻辑
  } finally {
    loading.value = false
    // 确保无论成功与否，都会将加载状态设置为 false
  }
}
const getStroe = () => {
  getStoreList({
    page: 1,
    limit: 100
  }).then((res) => {
    console.log(res, '1123123')
  })
}

const getTabNumber = async (name) => {
  const search = tabsConfig[name].search
  try {
    const { data } = await getProduct(search)
    // 处理边界条件
    if (data && data.list && data.count !== undefined) {
      tabsConfig[name].total = data.count
    } else {
      // 处理数据为空的情况
      tabsConfig[name].total = 0
    }
  } catch (error) {
    // 异常处理
    console.error('获取产品列表失败:', error)
    // 可以在这里添加错误提示或其他处理逻辑
  } finally {
    loading.value = false
    // 确保无论成功与否，都会将加载状态设置为 false
  }
}
const storeOpt = ref([])
const getStoreLists = async () => {
  const res = await getStoreList({ page: 1, limit: 100, store: 1 })
 storeOpt.value = res.data.list.map((item) => {
    return {
      value: item.id,
      label: item.name
    }
  })
}
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'store_name',
    label: '商品名称',
    component: 'Input',
    componentProps: {
      placeholder: '请填写商品名称'
    }
  },
  {
    field: 'store_id',
    label: '门店',
    component: 'Select',
    componentProps: {
      placeholder: '请选择要搜索的门店',
      options: storeOpt
    },
    // optionApi: async () => {
    //   const { data } = await getStoreList({ page: 1, limit: 100 })
    //   return data.list.map((item) => {
    //     return {
    //       value: item.id,
    //       label: item.name
    //     }
    //   })
    // }
  },
  {
    field: 'is_verify',
    label: '审核状态',
    hidden: true,
    component: 'Select',
    value: 'all',
    componentProps: {
      placeholder: '全部',
      options: [
        {
          value: 'all',
          label: '全部'
        },
        {
          value: '-2',
          label: '强制下架'
        },
        {
          value: '-1',
          label: '未通过'
        },
        {
          value: '0',
          label: '待审核'
        },
        {
          value: '1',
          label: '通过'
        }
      ]
    }
  },
  {
    field: 'is_show',
    label: '上下架',
    hidden: true,

    component: 'Select',
    value: 'all',
    componentProps: {
      placeholder: '全部',
      options: [
        {
          value: 'all',
          label: '全部'
        },
        {
          value: '1',
          label: '上架'
        },
        {
          value: '0',
          label: '未上架'
        }
      ]
    }
  },
  {
    field: 'is_del',
    label: '是否删除',
    hidden: true,
    component: 'Select',
    value: 'all',
    componentProps: {
      placeholder: '全部',
      options: [
        {
          value: 'all',
          label: '全部'
        },
        {
          value: '0',
          label: '未删除'
        },
        {
          value: '1',
          label: '已删除'
        }
      ]
    }
  },
  {
    field: 'cate_ids',
    label: '商品分类',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择商品分类',
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          getProductCategory({ page: 1, limit: 100, pid: node.value || 0 }).then((res) => {
            console.log(res)
            const nodes = res.data.list.map((item) => {
              return {
                value: item.id,
                label: item.cate_name,
                // leaf: !item.hasChildren
                leaf: item.children.length == 0
              }
            })
            resolve(nodes)
          })
        }
      }
    }
  }
])

const searchParams = ref<goodsSearch>({
  name: '',
  cate_ids: '',
  store_id: '',
  is_show: '1',
  is_del: '0',
  is_verify: '1'
})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const action = async (type: string, id?: number) => {
  push(`/goods/edit/${type}/${id || 0}`)
}
const delPr = async (id: number, is_del: 0 | 1) => {
  let title = '移除'
  if (is_del == 0) {
    title = '恢复'
  }
  ElMessageBox.confirm(`是否${title}商品？`, {
    confirmButtonText: `${title}`,
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await delProduct(id, is_del)
      getList()

      ElMessage({
        showClose: true,
        message: `${title}成功`,
        type: 'success'
      })
    })
    .catch(() => {})
}

const selectChange = (res) => {
  selectList.value = res
}
const selectList = ref<any[]>([])
const dialogSet = ref(false)
// const allSet = () => {
//   dialogSet.value = true
// }
watch(currentPage, (val) => {
  if (val) {
    // console.log(val)
    currentPage.value = val
    getList()
  }
})
const changeStatus = async (val: any, id: number) => {
  console.log(val, id, 'val')
  try {
    const res = await postProductStatus(id, val)
    if (res) {
      ElMessage.success('设置成功')
    }
  } catch (error) {
    console.log(error)
  } finally {
    getList()
  }
  console.log()
}
const activeName = ref('up')

// const tabsClick = async (res) => {
//   if (!res || !res.paneName) {
//     console.error('Invalid res or paneName')
//     return
//   }
//   try {
//     const schemaConfig = res.paneName === 'all' ? false : true
//     setSchema([
//       { field: 'is_verify', path: 'hidden', value: schemaConfig },
//       { field: 'is_del', path: 'hidden', value: schemaConfig },
//       { field: 'is_show', path: 'hidden', value: schemaConfig }
//     ])

//     if (tabsConfig[res.paneName].search) {
//       await setValues(tabsConfig[res.paneName].search)
//     } else {
//       console.warn(`Unknown paneName: ${res.paneName}`)
//     }
//     const data = await getFormData()
//     setSearchParams(data)
//   } catch (error) {
//     console.error('Error in handleClick:', error)
//   }
// }
const auditMessageBox = (id: number) => {
  ElMessageBox.confirm('请选择审核结果', '审核', {
    distinguishCancelAndClose: true,
    confirmButtonText: '通过',
    cancelButtonText: '未通过'
  })
    .then(() => {
      audit(id, 1, '')
    })
    .catch((action: Action) => {
      if (action == 'cancel') {
        ElMessageBox.prompt('请输入拒绝理由', '提示', {
          inputPlaceholder: '输入正确的拒绝理由以便修改'
        }).then((res) => {
          audit(id, -1, res.value)
          console.log(res)
        })
      }
    })
}

const audit = async (id, is_verify, refusal) => {
  try {
    const res = await postProductAudit({
      id,
      refusal,
      is_verify
    })
    if (res && res.status == 200) {
      let title = '审核通过'
      if (is_verify == -1) {
        title = '已拒绝'
      }
      ElMessage.success(title)
      getList()
    }
  } catch (error) {
    console.log(error)
  }
}
const showStore = (id:number) => {
  let store : { label: string ,value: number} = storeOpt.value.find((item: any) => item.value == id) || {label: '',value: 0}
  if (store) {
    return store.label
  }
}
</script>

<template>
  <ContentWrap>
    <!-- <ElTabs v-model="activeName" @tab-click="tabsClick">
      <ElTabPane
        v-for="(item, index) in tabsConfig"
        :key="index"
        :label="`${item.title}${item.total > 0 ? `(${item.total})` : ''}`"
        :name="index"
        >
      </ElTabPane>
    </ElTabs> -->
    <div class="max-w-1000px">
      <Search
        :schema="searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
        @register="searchRegister"
        buttonPosition="right"
      />
    </div>
    <div class="mb-10px">
      <BaseButton type="primary" @click="action('add')">{{ t('exampleDemo.add') }}</BaseButton>
      <!-- <BaseButton @click="allSet" :disabled="selectList.length == 0">批量设置</BaseButton> -->
    </div>
    <ElTable @selection-change="selectChange" v-loading="loading" node-key="id" :data="dataList">
      <ElTableColumn type="selection" prop="selection" />
      <ElTableColumn prop="id" headerAlign="center" align="center" label="ID" width="70" />
      <ElTableColumn prop="avatar" headerAlign="center" align="center" label="商品图片" width="80">
        <template #default="{ row }">
          <TableImage :src="row.image" alt="商品图片" />
        </template>
      </ElTableColumn>
      <ElTableColumn prop="store_name" label="商品名称" minWidth="180" />
      <ElTableColumn prop="store_id" label="门店" minWidth="180">
        <template #default="{ row }">
          <div>{{showStore(row.store_id)}}</div>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="price" label="商品售价" minWidth="80" />
      <ElTableColumn prop="stock" label="库存" minWidth="80" />
      <ElTableColumn prop="sales" label="销量" minWidth="80" />
      <ElTableColumn prop="is_show" label="上下架" minWidth="80">
        <template #default="{ row }">
          <ElSwitch
            active-text="上架"
            inactive-text="下架"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
            v-model="row.is_show"
            @change="(val) => changeStatus(val, row.id)"
          />
        </template>
      </ElTableColumn>
      <ElTableColumn v-if="activeName == 'all'" prop="is_verify" label="审核状态" minWidth="80">
        <template #default="{ row }">
          <ElText v-if="row.is_verify == 1" type="success">已通过</ElText>
          <ElText v-if="row.is_verify == 0" type="primary">待审核</ElText>
          <ElText v-if="row.is_verify == -1" type="danger">已拒绝</ElText>
        </template>
      </ElTableColumn>
      <ElTableColumn v-if="activeName == 'all'" prop="price" label="删除状态" minWidth="80">
        <template #default="{ row }">
          <ElText v-if="row.is_del == 1" type="danger">已删除</ElText>
          <ElText v-if="row.is_del == 0" type="primary">未删除</ElText>
        </template>
      </ElTableColumn>
      <ElTableColumn
        prop="action"
        label="操作"
        headerAlign="center"
        align="center"
        width="190"
        :showOverflowTooltip="false"
        fixed="right"
      >
        <template #default="{ row }">
          <BaseButton link size="small" type="primary" @click="action('edit', row.id)">
            编辑
          </BaseButton>
          <ElDivider direction="vertical" />
          <BaseButton
            v-if="activeName == 'examine'"
            link
            size="small"
            type="primary"
            @click="auditMessageBox(row.id)"
          >
            审核
          </BaseButton>
          <ElDivider v-if="activeName == 'examine'" direction="vertical" />
          <ElDropdown>
            <BaseButton link size="small" type="info">
              <Icon icon="vi-ep:more-filled" />
            </BaseButton>
            <template #dropdown
              ><ElDropdownMenu>
                <ElDropdownItem v-if="activeName != 'trash'" @click="delPr(row.id, 1)"
                  >移到回收站
                </ElDropdownItem>
                <ElDropdownItem v-if="activeName == 'trash'" @click="delPr(row.id, 0)"
                  >恢复商品
                </ElDropdownItem>
              </ElDropdownMenu>
            </template>
          </ElDropdown>
        </template>
      </ElTableColumn>
    </ElTable>
    <ElPagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      layout="sizes, prev, pager, next, jumper, ->, total"
      :page-sizes="[10, 20, 30, 40, 50, 100]"
      class="mt-10px"
      :total="tabsConfig[activeName].total"
    />
  </ContentWrap>

  <BatchSet
    :where="searchParams"
    v-model="dialogSet"
    :select-list="selectList"
    @confirm="getList()"
  />
</template>
<style lang="less">
.example-showcase .el-dropdown-link {
  display: flex;
  color: var(--el-color-primary);
  cursor: pointer;
  align-items: center;
}
</style>
