import { fetch, apis } from '@/utils/request';
import moment from 'moment';

export function initForm(form, data) {
  if (!data) return;

  const formData = { ...data }
  // 交房时间
  if (data.receivedDate) {
    formData.receivedDate = moment(data.receivedDate)
  }

  // 主图 - 多个
  if (data.buildingImg) {
    formData.avatarImage = data.buildingImg.map((x) => x.url)
  }

  // 封面 - 一个
  if (data.buildingListImg) {
    formData.listImage = data.buildingListImg.map(item => item.url)[0]
  }

  // 视频
  if (data.videoUrl) {
    formData.videoUrl = [].concat(data.videoUrl)
  }

  // 视频封面
  if (data.videoImage) {
    formData.videoImage = data.videoImage[0].url
  }

  form.setFieldsValue(formData);
}

export function saveData(formData) {
  const {
    arrounds,
    pois,
    receivedDate,
    avatarImage,
    listImage,
    videoUrl,
    tag,
    videoImage,
    ...data
  } = formData
  // 项目周边
  const arroundsData = Object.keys(arrounds).reduce((acc, key) => {
    return {
      ...acc,
      [key]: arrounds[key].map(it => it.name).join(',')
    }
  }, {})
  Object.assign(data, arroundsData)

  // 项目地图周边
  data.mapJson = Object.keys(pois).map((key) => {
    return {
      key,
      data: JSON.stringify(pois[key]),
    }
  })
  //
  data.receivedDate = moment(receivedDate, 'yyyy-MM-dd HH:mm:ss')
  // 项目主图
  data.img = avatarImage.map((item, index) => ({ imgType: 'banner', url: item, orderNo: index + 1 }))
  // 列表图
  data.listImg = listImage ? [{ imgType: 'list', url: listImage, orderNo: 1 }] : []
  //
  data.videoUrl = videoUrl ? videoUrl[0] : undefined
  //
  data.videoImage = videoImage ? [{ imgType: 'videoImage', url: data.videoImage, orderNo: 1 }] : []
  // 项目标签
  data.tag = (tag || []).map((item, _) => ({ tagName: item }))

  const request = fetch(data.buildingId ? apis.building.updateBuilding : apis.building.addBuilding)
  return request({ data })
}
