<script lang="ts" setup>
import type { BatchCompleteDispatchWorkType } from '@/api/types/operator'
import { executeCommandAPI } from '@/api/centerControl'
import {
  batchCreateDispatchOrderAPI,
  getEbikeDetailForWorkAPI,
} from '@/api/operator'
import { useOperatorStore } from '@/store'
import { systemInfo } from '@/utils/systemInfo'
import { scanCode } from '@/utils/tools'

definePage({
  style: {
    navigationStyle: 'custom',
  },
})
const btnConfig = reactive({
  btnLoading: false,
  btnLoadingText: '正在生成订单',
})
const btnConfig_submit = reactive({
  btnLoading: false,
  btnLoadingText: '正在提交',
})
const acceptOrders = ref(false) // 是否接受订单
const operatorStore = useOperatorStore()
const tableRef = ref<any>(null)
const tableLoading = ref(false)
const table_tr_list = ref<any>([
  {
    title: '车辆编号',
    key: 'bikeCode',
    width: '100',
  },
  // {
  //   title: '状态',
  //   key: 'bikeStatus',
  //   width: '40',
  // },
  {
    title: '响铃',
    key: 'findBike',
    width: '40',
  },
  {
    title: '操作',
    key: 'actions',
    width: '40',
  },
])
const orderIds = ref<any>(undefined)
const popupRef = ref<any>(null)
const labelStyle = {
  padding: '0 5px 0 0',
  color: '#333333',
  fontSize: '30rpx',
  fontWeight: '400',
}
const radiolist = ref<any>([
  { label: '是', value: true },
  { label: '否', value: false },
])
// 表单数据
const formData = reactive<BatchCompleteDispatchWorkType>({
  bikeCodes: [],
  siteId: '',
  fileUrls: [],
  remarks: '',
})
const rules = ref({})
const fileList = ref<any[]>([])

// 返回
function handleBack() {
  uni.navigateBack()
}

function handleAddByCode() {
  uni.navigateTo({
    url: '/pages-sub/common/inputBikeCode?type=dispatch',
  })
}

// 扫码新增车辆
function handleScan() {
  scanCode({
    success: async (res: any) => {
      const { code } = res
      addBike(code)
    },
    fail: (err: any) => {
      console.log('扫码失败', err)
    },
  })
}

// 添加车辆
async function addBike(bikeCode: string, isShowToast = true) {
  try {
    const bikeInfo: any = await getEbikeDetailForWorkAPI(bikeCode)

    operatorStore.AddDispathBike({
      bikeInfo: {
        ...bikeInfo,
        bikeCode,
      },
      sucsuess: () => {
        isShowToast && uni.showToast({
          title: '添加成功',
          icon: 'none',
        })
      },
      fail: (err: any) => {
        uni.showToast({
          title: err.message || '添加失败',
          icon: 'none',
        })
      },
    })
  }
  catch (err) {
    console.error('获取车辆信息失败', err)
    const str = err.message || '获取车辆信息失败，请确认车辆编号是否正确'
    uni.showToast({
      title: str,
      icon: str.length < 4 ? 'error' : 'none',
    })
  }
}

// 删除
function handleDelete(item: any) {
  operatorStore.RemoveDispathBike(item, !orderIds.value)
}

// 响铃
async function handleVolume(item: any) {
  uni.showLoading({
    title: '正在发送响铃指令',
    mask: true,
  })
  try {
    const result: boolean = await executeCommandAPI({
      ecuSn: item.ecuSn,
      bikeCode: item.bikeCode,
      commandCode: 'FIND_BIKE',
    })
    if (result) {
      uni.showToast({
        title: '响铃指令已发送，请注意听取车辆声音',
        icon: 'none',
      })
    }
    else {
      uni.showToast({
        title: '响铃失败，请稍后重试',
        icon: 'none',
      })
    }
  }
  catch (err) {
    console.error('响铃失败', err)
    uni.showToast({
      title: err.message || '响铃失败，请稍后重试',
      icon: 'none',
    })
  }
  finally {
    uni.hideLoading()
  }
}

function openedPopup() {
  popupRef.value.open()
}

// 生成调度订单
async function createDispatchOrder() {
  btnConfig.btnLoading = true
  try {
    const list = operatorStore.dispathBikeList.map((item: any) => item.bikeCode)
    const res: any = await batchCreateDispatchOrderAPI({
      bikeCodes: list,
      acceptOrders: acceptOrders.value,
    })

    if (acceptOrders.value) {
      uni.showModal({
        title: '提示',
        content: '调度工单创建成功，是否完成调度？',
        confirmText: '继续完成',
        cancelText: '返回',
        success: (res) => {
          if (res.confirm) {
            uni.reLaunch({
              url: `/pages-sub/warehouse/dispatch/dispatch?isComplete=true&bikeCodes=${encodeURIComponent(JSON.stringify(operatorStore.dispathBikeList))}`,
            })
          }
          else {
            uni.navigateBack()
          }
        },
      })
    }
    else {
      uni.showModal({
        title: '提示',
        content: '工单创建成功，请前往工单大厅查看',
        confirmText: '我知道了',
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack()
          }
        },
      })
    }
  }
  catch (err) {
    console.error('创建调度订单失败', err)
    uni.showToast({
      title: err.message || '创建调度订单失败，请稍后重试',
      icon: 'none',
    })
  }
  finally {
    btnConfig.btnLoading = false
  }
}

// 提交调度订单
function submitDispatchOrder() {
  if (operatorStore.dispathBikeList.length === 0) {
    uni.showToast({
      title: '请先添加车辆',
      icon: 'none',
    })
    return
  }

  // 已有订单，直接打开弹窗
  if (orderIds.value) {
    openedPopup()
  }
  else {
    uni.showModal({
      title: '提示',
      content: '请确认好的车辆信息，确定要提交吗？',
      confirmText: '确定',
      success: (res) => {
        console.log(res)
        if (res.confirm) {
          createDispatchOrder()
        }
      },
    })
  }
}

// 重置表单数据
function resetData() {
  formData.bikeCodes = []
  formData.fileUrls = []
  formData.remarks = ''
  formData.siteId = ''
}

onLoad((query) => {
  const { bikeCode, orderId } = query

  if (bikeCode) {
    addBike(bikeCode, false)
  }
})
onUnload(() => {
  operatorStore.ClearDispathBike()
})
</script>

<template>
  <view>
    <z-paging
      ref="paging"
      bg-color="#f3f3f3"
    >
      <template #top>
        <view class="custom_navbar" :style="{ height: `${systemInfo.statusBarHeight + 44}px` }">
          <view class="back_bar">
            <uv-icon name="arrow-left" color="#222222" size="24" @click="handleBack" />
            <text class="text">调度工单</text>
          </view>
        </view>
      </template>

      <view class="container">
        <uni-card>
          <uv-form ref="form" label-position="top">
            <uv-form-item label="自己是否接单" border-bottom :label-width="100">
              <uv-radio-group v-model="acceptOrders">
                <uv-radio
                  v-for="(item, index) in radiolist"
                  :key="index"
                  :custom-style="{ margin: '8px' }"
                  :label="item.label"
                  :name="item.value"
                />
              </uv-radio-group>
            </uv-form-item>
          </uv-form>
        </uni-card>

        <uni-card>
          <uni-table
            ref="tableRef"
            :loading="tableLoading"
            stripe
            border
            empty-text="请扫码添加车辆"
          >
            <uni-tr>
              <uni-th
                v-for="(item, index) in table_tr_list"
                :key="index"
                class="th_style"
                :align="item.align || 'center'"
                :width="item.width || 'auto'"
              >
                {{ item.title }}
              </uni-th>
            </uni-tr>
            <uni-tr
              v-for="(item, index) in operatorStore.dispathBikeList"
              :key="index"
            >
              <uni-td align="center">
                {{ item.bikeCode || '--' }}
              </uni-td>
              <!-- <uni-td align="center">
                  <text
                    :style="{
                      color: item.online ? '#00C851' : '#ff4444',
                    }"
                  >
                    {{ item.online ? '在线' : '离线' }}
                  </text>
                </uni-td> -->
              <uni-td align="center">
                <view style="width: 100%; display: flex;justify-content: center;">
                  <uv-icon name="volume" size="18" @click="handleVolume(item)" />
                </view>
              </uni-td>
              <uni-td>
                <view style="width: 100%; display: flex;justify-content: center;">
                  <uv-icon name="trash" size="18" @click="handleDelete(item)" />
                </view>
              </uni-td>
            </uni-tr>
          </uni-table>
        </uni-card>
      </view>

      <template #bottom>
        <view class="bottom-button-zaping">
          <view v-if="!orderIds" class="tools_bar">
            <uv-button type="primary" :plain="true" text="扫码新增" @click="handleScan" />
            <uv-button type="primary" :plain="true" text="编号新增" @click="handleAddByCode" />
          </view>
          <uv-button
            type="primary"
            text="生成工单"
            :loading="btnConfig.btnLoading"
            :loading-text="btnConfig.btnLoadingText"
            :custom-style="{
              backgroundImage: `linear-gradient(135deg, #1089FF 0%, #0F5BFF 100%)`,
              borderRadius: '28rpx',
              height: '100rpx',
            }"
            :custom-text-style="{
              fontSize: '32rpx',
              marginLeft: '8rpx',
            }"
            @click="submitDispatchOrder"
          />
        </view>
      </template>
    </z-paging>
  </view>
</template>

  <style lang="scss" scoped>
  .custom_navbar {
  width: 100%;
  position: relative;
  background-color: white;

  .back_bar {
    display: flex;
    align-items: center;
    position: absolute;
    bottom: 25rpx;
    left: 30rpx;

    .text {
      font-family: SourceHanSansCN-Medium;
      font-size: 34rpx;
      color: #222222;
      letter-spacing: 0;
      font-weight: 500;
    }
  }
}

::v-deep .uni-table-th {
  background-color: #f7f7f7 !important;
}

.container {
  width: 100%;
}

.tools_bar {
  display: flex;
  width: 100%;
  padding-bottom: 30rpx;
  align-items: center;
  justify-content: space-around;
}

.popup_content {
  width: 100%;

  .header_bar {
    position: relative;
    height: 100rpx;
    width: 100%;
    text-align: center;

    .title {
      font-size: 32rpx;
      line-height: 100rpx;
      font-weight: bold;
      color: #222222;
    }
  }

  .content_bar {
    padding: 20rpx 30rpx;
    width: calc(100% - 60rpx);
    overflow-y: auto;
  }

  .footer_bar {
    border-top: 1rpx solid #e5e5e5;
    padding-top: 20rpx;
    height: 100rpx;
    width: 100%;
    display: flex;
    justify-content: space-around;
  }
}

.select_bar {
  width: calc(100% - 40rpx);
  padding: 20rpx;
  border: 2rpx solid rgba(153, 153, 153, 0.6);
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  background-color: white;
  justify-content: space-between;

  .text {
    width: 90%;
    font-size: 28rpx;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    color: #999999;
  }
}
</style>
