import { defineStore } from 'pinia'
import { getOperatorAllListAPI, validateDispatchOrderAPI } from '@/api/operator'

interface OperatorItem {
  address: string
  contactPhone: string
  createBy: string
  createTime: string
  isDeleted: boolean
  operatorId: string
  operatorName: string
  updateBy: null | string
  updateTime: null | string
}

/**
 * 操作相关的仓库（后续所有与操作相关的数据都放在这里）
 */
export const useOperatorStore = defineStore(
  'operator',
  () => {
    const operatorList = ref<OperatorItem[]>([])
    const selectSite = ref<{
      siteName: string
      siteId: string
    }>({
      siteName: '',
      siteId: '',
    })

    const dispathBikeList = ref<any[]>([]) // 调度单车辆
    const initialDispathBikeList = ref<any[]>([]) // 待调度的车辆

    /**
     * 调度车辆
     */
    function dispatchVehicles({ bikeInfo = undefined, isOneKey = false, sucsuess = null, fail = null }: {
      bikeInfo?: any
      isOneKey?: boolean // 是否一键添加车辆
      sucsuess?: () => void
      fail?: () => void
    }) {
      if (!bikeInfo && !isOneKey) {
        fail && fail()
      }

      // 一键添加
      if (isOneKey) {
        initialDispathBikeList.value.forEach((bike) => {
          const isExist = dispathBikeList.value.some(item => item.bikeCode === bike.bikeCode)
          if (!isExist) {
            dispathBikeList.value.push(bike)
            initialDispathBikeList.value = initialDispathBikeList.value.filter(item => item.bikeCode !== bike.bikeCode)
          }
        })
        sucsuess && sucsuess()
        return
      }

      // 添加单个车辆，移除当前列表车辆
      initialDispathBikeList.value = initialDispathBikeList.value.filter(item => item.bikeCode !== bikeInfo.bikeCode)
      dispathBikeList.value.push(bikeInfo)
      sucsuess && sucsuess()
    }

    /**
     * 取消调度车辆
     */
    function cancelDispatchOrder(bikeInfo: any) {
      // 移除调度单车辆
      initialDispathBikeList.value = initialDispathBikeList.value.filter(item => item.bikeCode !== bikeInfo.bikeCode)
    }

    /**
     * 添加调度单车辆
     * @param bike
     */
    async function AddDispathBike({ bikeInfo, sucsuess = null, fail = null }: {
      bikeInfo: any
      sucsuess?: () => void
      fail?: (e: any) => void
    }) {
      // 查重
      const isExist = dispathBikeList.value.some(item => item.bikeCode === bikeInfo.bikeCode)
      if (isExist) {
        fail && fail({
          message: '车辆已存在',
        })
        return uni.showToast({
          title: '车辆已存在',
          icon: 'none',
        })
      }

      try {
        const res: any = await validateDispatchOrderAPI(bikeInfo.bikeCode)
        if (res) {
          dispathBikeList.value.push(bikeInfo)
          sucsuess && sucsuess()
        }
        else {
          fail && fail({
            message: '该车辆不可调度',
          })
        }
      }
      catch (e) {
        fail && fail(e)
      }
    }

    /**
     * 移除调度单车辆
     * @param bike
     * @param isnoreInitial 是否忽略初始列表添加
     */
    function RemoveDispathBike(bike: any, isnoreInitial = true) {
      dispathBikeList.value = dispathBikeList.value.filter(item => item.bikeCode !== bike.bikeCode)

      if (!isnoreInitial) {
        initialDispathBikeList.value.push(bike)
      }
    }

    /**
     * 清空调度单车辆
     */
    function ClearDispathBike() {
      dispathBikeList.value = []
    }

    /**
     * 清空剩余调度工单
     */
    function ClearRemainingDispatchOrders() {
      initialDispathBikeList.value = []
    }

    /**
     * 设置选择的站点
     */
    function setSelectSite(siteName: string, siteId: string) {
      selectSite.value = {
        siteName,
        siteId,
      }
    }

    /**
     * 清空选择的站点
     */
    function clearSelectSite() {
      selectSite.value = {
        siteName: '',
        siteId: '',
      }
    }

    /**
     * 获取运营商列表
     * @param isSupportSelect 是否转为为select支持的格式
     */
    async function getOperatorList(isSupportSelect = false) {
      try {
        const _list: OperatorItem[] = await getOperatorAllListAPI()
        if (isSupportSelect) {
          return _list.map(item => ({
            text: item.operatorName,
            value: item.operatorId,
          }))
        }
        return _list
      }
      catch (e) {
        return []
      }
    }

    /**
     *根据operatorId翻译
     */
    function translateOperatorId(operatorId: string, list: OperatorItem[] = []) {
      if (!list || list.length === 0)
        return operatorId

      const operator = list.find(item => item.operatorId === operatorId)
      return operator ? operator.operatorName : operatorId
    }

    return {
      selectSite,
      dispathBikeList,
      initialDispathBikeList,

      // 调度
      AddDispathBike,
      RemoveDispathBike,
      ClearDispathBike,
      dispatchVehicles,
      cancelDispatchOrder,
      ClearRemainingDispatchOrders,

      getOperatorList,
      setSelectSite,
      clearSelectSite,
      translateOperatorId,
    }
  },
)
