import Mock from 'mockjs'
import { MockMethod } from 'vite-plugin-mock'
const data = Mock.mock({
  'data|10': [
    {
      id: '@id',
      userCode: '@integer(1000, 7060)',
      userName: '@cname',
      address: '@city(true)',
      phone: '@phone',
      sex: '@sex'
    }
  ]
}).data
const mockMethodSeven: MockMethod[] = [
  {
    url: '/mock/api/edit/table/query',
    method: 'get',
    timeout: 1000,
    response: ({ query }: { query: any }) => ({
      code: '0',
      data: filterData(query.userName, query.userCode)
    })
  },
  {
    url: '/mock/api/edit/table/save',
    method: 'post',
    timeout: 1000,
    response: ({ body }: { body: any }) => {
      if (Array.isArray(body)) {
        data.splice(0)
        body.forEach((item, index) => {
          delete item.isEdit
          data[index] = { ...item, id: Mock.Random.id() }
        })
      } else {
        delete body.isEdit
        if (body.id) {
          const index = data.findIndex((f: any) => f.id === body.id)
          data[index] = body
          return
        }
        data.unshift({ ...body, id: Mock.Random.id() })
      }
    }
  },
  {
    url: '/mock/api/edit/table/delete',
    method: 'post',
    timeout: 1000,
    response: ({ body }: { body: any }) => {
      const { id } = body
      const index = data.findIndex((i: any) => i.id === id)
      data.splice(index, 1)
      return {
        code: '0'
      }
    }
  }
]
function filterData(userName: string, userCode: string) {
  return data.filter((f: any) => f.userName.includes(userName ?? '') && f.userCode.toString().includes(userCode ?? ''))
}
export default mockMethodSeven
