import Mock from 'mockjs'
import { MockMethod } from 'vite-plugin-mock'
const codeData = Mock.mock({
  'data|15-20': [
    {
      id: '@id',
      shipName: '@shipNames',
      shipCode: '@integer(10000, 10100)',
      areaCode: '@integer(1000, 2010)'
    }
  ]
}).data
const data = [
  ...Mock.mock({
    'data|150-200': [
      {
        id: '@id',
        shipId: `@pick("${codeData.map((v: any) => v.id).join('","')}")`,
        userName: '@cname',
        userCode: '@integer(1000, 2000)'
      }
    ]
  }).data
]

const mockMethodNine: MockMethod[] = [
  {
    url: '/mock/api/nine/code',
    method: 'get',
    timeout: 1000,
    response: () => {
      return {
        code: '0',
        data: codeData
      }
    }
  },
  {
    url: '/mock/api/nine/user',
    method: 'get',
    timeout: 1000,
    response: ({ query }: { query: any }) => {
      const id = query.shipId || codeData[0]?.id
      const shipName = codeData.find((f: any) => f.id === id).shipName
      return {
        code: '0',
        data: data.filter(({ shipId }) => shipId === id).map((v) => ({ ...v, shipName }))
      }
    }
  },
  {
    url: '/mock/api/nine/code/save',
    method: 'post',
    timeout: 1000,
    response: ({ body }: { body: any }) => {
      updateData(codeData, body)
      return {
        code: '0'
      }
    }
  },
  {
    url: '/mock/api/nine/code/del',
    method: 'post',
    timeout: 1000,
    response: ({ body }: { body: any }) => {
      deleteData(codeData, body.id)
      return {
        code: '0'
      }
    }
  },
  {
    url: '/mock/api/nine/user/save',
    method: 'post',
    timeout: 1000,
    response: ({ body }: { body: any }) => {
      updateData(data, body)
      return {
        code: '0'
      }
    }
  },
  {
    url: '/mock/api/nine/user/del',
    method: 'post',
    timeout: 1000,
    response: ({ body }: { body: any }) => {
      console.log(body)
      deleteData(data, body.id)
      return {
        code: '0'
      }
    }
  }
]
function deleteData(data: any[], id: string) {
  const ids: string[] = [id]
  console.log(ids)
  ids.forEach((i) => {
    const index = data.findIndex((d) => d.id === i)
    data.splice(index, 1)
  })
}
function updateData(data: any[], params: any) {
  let index = data.length
  if (params.id) {
    index = data.findIndex((f) => f.id === params.id)
  }
  data[index] = params
}

export default mockMethodNine
