import { create } from 'zustand'
import { fetchJSON, postForm } from '@/utils/request'
import { API_HOST } from '@/config'
import { isNotEmpty, prepareUrl } from '@/utils/commons'

export const useOrderStore = create((set, get) => ({

  orderList: [],
  orderDetail: {},
  customerDetail: {},
  lastQuotation: {},
  quotationList: [],

  fetchOrderList: async (formValues, loginUser) => {
    let fetchOrderUrl = `${API_HOST}/getwlorder?opisn=${loginUser.userIdStr}&otype=${formValues.type}`

    if (formValues.type === 'advance') {

      let fromDate = null
      let thruDate = null

      if (isNotEmpty(formValues.startDateRange)) {
        fromDate = formValues.startDateRange[0].format('YYYY-MM-DD')
        thruDate = formValues.startDateRange[1].format('YYYY-MM-DD')
      }

      let confirmFromDate = null
      let confirmThruDate = null

      if (isNotEmpty(formValues.confirmDateRange)) {
        confirmFromDate = formValues.confirmDateRange[0].format('YYYY-MM-DD')
        confirmThruDate = formValues.confirmDateRange[1].format('YYYY-MM-DD')
      }

      fetchOrderUrl = prepareUrl('https://p9axztuwd7x8a7.mycht.cn/whatsapp_server/getdvancedwlorder')
        .append('opisn', loginUser.userIdStr)
        .append('startdate', fromDate)
        .append('enddate', thruDate)
        .append('tag', formValues.orderLabel)
        .append('orderstate', formValues.orderStatus)
        .append('remindstate', formValues.remindState)
        .append('coli_id', formValues.orderNumber)
        .append('firstName', formValues.firstName)
        .append('lastName', formValues.lastName)
        .append('emailphone', formValues.emailOrPhone)
        .append('ConfirmDateStart', confirmFromDate)
        .append('ConfirmDateEnd', confirmThruDate)
        .build()
    }

    return fetchJSON(fetchOrderUrl)
      .then(json => {
        if (json.errcode === 0) {
          set(() => ({
            orderList: json.result.map((order) => { return { ...order, key: order.COLI_ID } }),
          }))
        } else {
          throw new Error(json?.errmsg + ': ' + json.errcode)
        }
      })

  },

  fetchOrderDetail: (colisn) => {
    return fetchJSON(`${API_HOST}/getorderinfo`, { colisn })
      .then(json => {
        if (json.errcode === 0 && json.result.length > 0) {
          const orderResult = json.result[0]
          set(() => ({
            orderDetail: orderResult,
            customerDetail: orderResult.contact.length > 0 ? orderResult.contact[0] : {},
            lastQuotation: orderResult.quotes.length > 0 ? orderResult.quotes[0] : {},
            quotationList: orderResult.quotes,
          }))
        } else {
          throw new Error(json?.errmsg + ': ' + json.errcode)
        }
      })

  },


  appendOrderComment: async (opi_sn, coli_sn, comment) => {
    const { fetchOrderDetail } = get()
    const formData = new FormData()
    formData.append('opi_sn', opi_sn)
    formData.append('coli_sn', coli_sn)
    formData.append('remark', comment)

    return postForm(`${API_HOST}/remark_order`, formData)
      .then(json => {
        if (json.errcode === 0) {
          return fetchOrderDetail(coli_sn)
        } else {
          throw new Error(json?.errmsg + ': ' + json.errcode)
        }
      })
  },

  setOrderPropValue: async (colisn, propName, value) => {

    if (propName === 'orderlabel') {
      set((state) => ({
        orderDetail: {
          ...state.orderDetail,
          tags: value
        }
      }))
    }

    if (propName === 'orderstatus') {
      set((state) => ({
        orderDetail: {
          ...state.orderDetail,
          states: value
        }
      }))
    }

    return fetchJSON(`${API_HOST}/setorderstatus`, { colisn, stype: propName, svalue: value })
      .then(json => {
        if (json.errcode > 0) {
          throw new Error(json?.errmsg + ': ' + json.errcode)
        }
      })
  },

}))

export const OrderLabelDefaultOptions = [
  { value: 240003, label: '重点' },
  { value: 240002, label: '次重点' },
  { value: 240001, label: '一般' }
]

export const OrderStatusDefaultOptions = [
  { value: 1, label: '新订单' },
  { value: 2, label: '报价中' },
  { value: 3, label: '以后联系' },
  { value: 4, label: '等待付订金' },
  { value: 5, label: '成行' },
  { value: 6, label: '丢失' },
  { value: 7, label: '取消' },
  { value: 8, label: '未报价' }
]

export const RemindStateDefaultOptions = [
  { value: '1', label: '一催' },
  { value: '2', label: '二催' },
  { value: '3', label: '三催' }
]