import Mock from 'mockjs'
import { MockMethod } from 'vite-plugin-mock'
import city from './city.json'

interface TypicalSevenTable {
  id: string
  jobTitle: string
  jobCode: string
  personName: string
  personCode: string
  lastModified: string
}
interface CacheData {
  [key: string]: TypicalSevenTable[]
}

const mockData = function () {
  return Mock.mock({
    'data|10-30': [
      {
        id: '@id',
        jobTitle: function () {
          const job = Mock.Random.randomJob()
          this.jobCode = job.code
          return job.name
        },
        jobCode: '',
        personCode: '@integer(1000, 7060)',
        personName: '@cname',
        lastModified: '@datetime("2024-MM-dd hh:mm:ss")'
      }
    ]
  }).data
}
const cacheData: CacheData = {}

const mockMethodSeven: MockMethod[] = [
  {
    url: '/mock/api/seven/tree',
    method: 'get',
    timeout: 1000,
    response: () => {
      return {
        code: '0',
        data: city
      }
    }
  },
  {
    url: '/mock/api/seven/delete',
    method: 'get',
    timeout: 1000,
    response: ({ query }: { query: any }) => {
      const { areaCode } = query
      const id = query['id[]']
      const data = cacheData[areaCode] ?? []
      cacheData[areaCode] = data.filter((item) => !id.includes(item.id))
      return {
        code: '0',
        data: 1
      }
    }
  },
  {
    url: '/mock/api/seven/query',
    method: 'get',
    timeout: 1000,
    response: ({ query }: { query: any }) => {
      const { jobCode, areaCode, pageIndex, pageSize } = query

      if (!cacheData[areaCode]) {
        cacheData[areaCode] = mockData()
      }
      let filterData = cacheData[areaCode]
      if (jobCode) {
        filterData = filterData.filter((item) => {
          return item.jobCode == jobCode
        })
      }
      const _pageSize = Number(pageSize) ?? 20
      const total = filterData.length
      const pages = Math.ceil(total / _pageSize)
      const offset = (pageIndex - 1) * _pageSize
      const list = filterData.slice(offset, offset + _pageSize)

      return {
        code: '0',
        data: {
          pageNum: Number(pageIndex),
          pageSize: Number(pageSize) ?? 20,
          size: list.length,
          pages: pages,
          total: total,
          list: list
        }
      }
    }
  }
]

export default mockMethodSeven
