<template>
  <div class="page">
    <BaseTableHeader class="mb-10" title="我的产品" :show-search="true" @reset="reset" @search="search">
      <template #topBarSlot>
        <router-link to="/product/add">
          <a-button type="primary">新增产品</a-button>
        </router-link>
      </template>
      <template #searchFormSlot>
        <a-form layout="vertical" class="grid grid-cols-3 gap-col-100">
          <a-form-item label="产品英文名">
            <a-input placeholder="请输入" v-model:value="searchParams.merchandiseEnglishName" size="large" />
          </a-form-item>
          <a-form-item label="所属品牌">
            <a-select placeholder="请选择" v-model:value="searchParams.affiliationBrandCode" size="large" allowClear>
              <a-select-option :value="item.billNo" v-for="item in brandList" :key="item.id">{{ item.brandName }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="审核状态">
            <a-select placeholder="请选择" v-model:value="searchParams.checkState" size="large" allowClear>
              <a-select-option :value="item.value" v-for="item in commonStore.dict[DICT_CODE.PRODUCT_CHECK_STATUS]" :key="item.value">{{
                item.text
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="产品分类">
            <!-- <a-select placeholder="请选择" v-model:value="searchParams.category" size="large" allowClear>
              <a-select-option :value="item.key" v-for="item in commonStore.category" :key="item.key">{{
                  item.title
                }}</a-select-option>
            </a-select> -->
            <a-cascader
              size="large"
              change-on-select
              placeholder="请选择"
              v-model:value="searchParams.categoryArr"
              :options="options"
              expand-trigger="hover"
              :fieldNames="{ label: 'title', value: 'key' }"
            />
          </a-form-item>
          <a-form-item label="上架状态">
            <a-select placeholder="请选择" v-model:value="searchParams.state" size="large" allowClear>
              <a-select-option :value="item.value" v-for="item in commonStore.dict[DICT_CODE.PRODUCT_STATUS]" :key="item.value">{{
                item.text
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="创建时间">
            <BaseRangePicker
              v-model:start="searchParams.createTime_begin"
              v-model:end="searchParams.createTime_end"
              size="large"
              class="w-full"
            ></BaseRangePicker>
          </a-form-item>
        </a-form>
      </template>
    </BaseTableHeader>

    <div class="px-25 py-30 bg-white rounded-4">
      <a-table
        class="theme-table"
        :columns="columns"
        :row-key="(record) => record.id"
        :data-source="list"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, value, record }">
          <template v-if="column.dataIndex === 'billNo'">
            <router-link class="c-primary underline" :to="{ path: '/product/detail', query: { id: record.id } }">{{ value }}</router-link>
          </template>
          <template v-if="column.dataIndex === 'masterImage'">
            <a-image :src="value" width="52px" height="52px" class="object-contain" fallback=""> </a-image>
          </template>
          <!-- <template v-if="column.dataIndex === 'affiliationBrandName'">
            <router-link class="c-primary underline" :to="{ path: '/brand/detail', query: { id: record.affiliationBrandCode } }">{{ value }}</router-link>
          </template> -->
          <template v-if="column.dataIndex === 'checkState'">
            <!-- {{ enumsMap(value, commonStore.dict[DICT_CODE.BRAND_CHECK_STATUS]) }} -->
            <span v-if="record.checkState === 'A01'" class="c-success">{{ record.checkState_dictText }}</span>
            <span v-if="record.checkState === 'A02'" class="c-danger">{{ record.checkState_dictText }}</span>
            <span v-if="record.checkState === 'A03'" class="c-warning">{{ record.checkState_dictText }}</span>
          </template>
          <template v-if="column.dataIndex === 'state'">
            <a-switch
              :checked="value"
              @click="onToggleStatus(record)"
              :disabled="record.checkState !== 'A01'"
              checked-children="开"
              checkedValue="A01"
              un-checked-children="关"
              unCheckedValue="A02"
            />
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <router-link class="c-primary" :to="{ path: '/product/edit', query: { id: record.id } }">编辑</router-link>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { message, Modal } from 'ant-design-vue'

import { computed } from 'vue'
import type { TableProps } from 'ant-design-vue'
import type { ProductSearchParams } from 'Types/api'
import { apiProductList, apiProductDelete, apiToggleStatus } from '@/api/product'
import { apiBrandList } from '@/api/brand'
import { usePagination } from 'vue-request'
import useCommonStore from '@/store/modules/common'
import { DICT_CODE } from '@/utils/const'
import { getProductCategoryApi } from 'API/common'

const commonStore = useCommonStore()
commonStore.getDict(DICT_CODE.PRODUCT_CHECK_STATUS)
commonStore.getDict(DICT_CODE.BRAND_CLASS)
commonStore.getDict(DICT_CODE.PRODUCT_STATUS)
const searchParams = reactive<ProductSearchParams>({
  merchandiseEnglishName: '',
  affiliationBrandCode: null,
  category: '',
  categoryArr: [],
  state: null,
  checkState: null,
  createTime_begin: '',
  createTime_end: '',
  // affiliationBrandName: 'xx',
})
const columns = [
  {
    title: '产品ID',
    dataIndex: 'billNo',
  },
  {
    title: '产品图片',
    dataIndex: 'masterImage',
  },
  {
    title: '产品英文名',
    dataIndex: 'merchandiseEnglishName',
  },
  {
    title: '分类',
    dataIndex: 'categoryText',
  },
  {
    title: '所属品牌',
    dataIndex: 'affiliationBrandName',
  },
  {
    title: '出厂价',
    dataIndex: 'sellPrice',
  },
  {
    title: '审核状态',
    dataIndex: 'checkState',
  },
  {
    title: '上架状态',
    dataIndex: 'state',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: 80,
  },
]

const { data, run, loading, current, pageSize } = usePagination(apiProductList, {
  defaultParams: [searchParams],
  pagination: {
    currentKey: 'pageNo',
    pageSizeKey: 'pageSize',
  },
})

const pagination = computed(() => ({
  total: data.value?.data.result.total || 0,
  current: current.value,
  pageSize: pageSize.value,
}))

const list = computed(() => {
  return data.value?.data.result.records || []
})
const brandList = ref<Array<BrandItem>>()
const options = ref([])

onMounted(() => {
  apiBrandList({ pageNo: 1, pageSize: 9999 }).then((res) => {
    // console.log(res.data.result.records)
    brandList.value = res.data.result.records
  })
})
const getCategoryList = async () => {
  const res = await getProductCategoryApi({ pid: 0 })
  if (res.data.success) {
    options.value = res.data.result || []
  }
}
getCategoryList()
const handleTableChange: TableProps['onChange'] = (pag: { pageSize: number; current: number }, filters: any, sorter: any) => {
  run({
    pageSize: pag.pageSize,
    pageNo: pag.current,
    ...searchParams,
    category: searchParams.categoryArr[searchParams.categoryArr.length - 1],
    // sortField: sorter.field,
    // sortOrder: sorter.order,
    // ...filters,
  })
}

const onDelete = (id: number) => {
  apiProductDelete({ id }).then(() => {
    message.success('删除成功')
  })
}
const onToggleStatus = (item) => {
  const ON = 'A01'
  const OFF = 'A02'

  const doToggle = () => {
    apiToggleStatus({ id: item.id, state: item.state === ON ? OFF : ON }).then((res) => {
      if (res.data.code === 200) {
        if (item.state === ON) {
          message.success('已下架')
        } else {
          message.success('已上架')
        }
        reload()
      }
    })
  }
  console.log(item)
  if (item.state === ON) {
    Modal.confirm({
      title: '提示',
      centered: true,
      // icon: createVNode(ExclamationCircleOutlined),
      content: '确定下架？',
      onOk() {
        doToggle()
      },
    })
  } else {
    doToggle()
  }
}

const search = () => {
  console.log('searchParams', searchParams)
  let category = null
  if (searchParams.categoryArr) {
    category = searchParams.categoryArr[searchParams.categoryArr.length - 1]
  }
  run({
    pageNo: 1,
    pageSize: pagination.value.pageSize,
    ...searchParams,
    category,
  })
}

const reload = () => {
  let category = null
  if (searchParams.categoryArr) {
    category = searchParams.categoryArr[searchParams.categoryArr.length - 1]
  }
  run({
    pageNo: current.value,
    pageSize: pagination.value.pageSize,
    ...searchParams,
    category,
  })
}

const reset = () => {
  Object.keys(searchParams).forEach((key) => {
    if (searchParams[key] instanceof Array) {
      searchParams[key] = []
    } else {
      searchParams[key] = ''
    }
  })
  let category = null
  if (searchParams.categoryArr) {
    category = searchParams.categoryArr[searchParams.categoryArr.length - 1]
  }
  run({
    pageNo: 1,
    pageSize: pagination.value.pageSize,
    ...searchParams,
    category,
  })
}
</script>
<style scoped></style>
