import request, { tenantRequest } from '@/utils/request'
import {
  add,
  update,
  del,
  submit,
  resolve,
  reject,
  messageSend,
  addStatusScope,
  addOrg,
  canDel
} from './base'

export function getPrograms (query) {
  const { pageNum: currentPage, pageSize: pageCount, ...params } = query
  return tenantRequest({
    url: '/item/listByPage',
    method: 'POST',
    data: addStatusScope({
      currentPage, pageCount,
      ...params
    })
  }).then(({ data, totalCount }) => {
    data.forEach(program => {
      program.del = canDel(program)
    })
    return { data, totalCount }
  })
}

export function addProgram (data) {
  return add({
    url: '/item/add',
    method: 'POST',
    data: addOrg(data)
  }, tenantRequest)
}

export function deleteProgram ({ id, name }) {
  return del({
    url: '/item/delete',
    method: 'DELETE',
    params: { id }
  }, name)
}

export function updateProgram (data) {
  const { id, duration, itemJsonStr, base64 } = data
  const formData = new FormData()
  const result = /^data:(.+);base64,(.+)$/.exec(base64)
  if (result) {
    const binaryString = atob(result[2])
    const length = binaryString.length
    const mine = new Uint8Array(length)
    for (let i = 0; i < length; i++) {
      mine[i] = binaryString.charCodeAt(i)
    }
    formData.append('file', new Blob([mine], { type: result[1] }))
  }
  formData.append('id', id)
  formData.append('duration', duration)
  formData.append('itemJsonStr', itemJsonStr)
  return request({
    url: '/item/update',
    method: 'POST',
    data: formData,
    timeout: 0,
    custom: true
  }).then(({ data }) => data)
}

export function updateProgramName (data) {
  return update({
    url: '/item/updateItemName',
    method: 'POST',
    data
  })
}

export function getProgram (id, options) {
  return request({
    url: `/item/getById/${id}`,
    method: 'GET',
    ...options
  })
}

export function submitProgram ({ id, name }) {
  return submit({
    url: '/item/submit',
    method: 'GET',
    params: { id }
  }, name)
}

export function resolveProgram ({ id, name }) {
  return resolve({
    url: '/item/reviewed',
    method: 'GET',
    params: { id }
  }, name)
}

export function rejectProgram ({ id, name }, reason) {
  return reject({
    url: '/item/reject',
    method: 'GET',
    params: { id },
    data: { reason }
  }, name)
}

export function copyProgram ({ id }, name) {
  return messageSend({
    url: '/item/copy',
    method: 'POST',
    data: addOrg({ id, name })
  }, '复制')
}
