<script setup>
import {
  postWorkDataArriveApi,
  getWorkDataInfoApi,
  putWorkDataApi
} from '@/api/elevator'
import { useUniApi } from '@/composables/use-uni-api'
import { useUpload } from '@/composables/use-upload'
const { navigateTo } = useUniApi()
const { uploadFile } = useUpload()

const dataDetail = ref({})
const getWorkDataInfo = async () => {
  const { error, data } = await getWorkDataInfoApi(options.value)
  if (!error) {
    dataDetail.value = data
  }
}
onMounted(() => {
  getWorkDataInfo()
})

const operationStateMap = {
  2: '接收',
  3: '到场',
  4: '完成',
  7: '评价'
}
const planTypeMap = {
  1: '半月',
  2: '季度',
  3: '半年',
  4: '年度'
}

const actionRecord = ref([])
watchEffect(() => {
  const { status, operationRecords } = dataDetail.value
  if ([4, 7].includes(status)) {
    cellData.value[2].value = '已完成'
  }

  if (operationRecords) {
    actionRecord.value = operationRecords.map((item) => {
      const { operationState } = item
      return {
        ...item,
        operationStateStr: operationStateMap[operationState]
      }
    })
  }
})

// 拍照 视频 扫一扫 记录 工作表
const apps = [
  {
    name: '拍照',
    type: 'camera',
    background: '#88C3F3',
    icon: 'camera'
  },
  {
    name: '视频',
    type: 'video',
    background: '#668FE6',
    icon: 'video'
  },
  {
    name: '扫一扫',
    type: 'scan',
    background: '#DC635E',
    icon: 'scan'
  },
  {
    name: '记录',
    type: 'record',
    background: '#EF8833',
    icon: 'edit'
  },
  {
    name: '工作表',
    type: 'sheet',
    background: '#DD7A92',
    icon: 'form'
  }
]

const workSheetModal = ref({
  name: '工作表',
  show: false,
  actions: [
    { name: '半月维保', value: '1' },
    { name: '季度维保', value: '2' },
    { name: '半年维保', value: '3' },
    { name: '年度维保', value: '4' }
  ]
})
const workSheetActionSelect = (item) => {
  console.log('workSheetActionSelect:', item)
  const { value: type } = item
  const { id } = options.value
  navigateTo(`/pages/views/submit-sheet/index?id=${id}&type=${type}`)
}

const locations = ref({
  latitude: 30.59276,
  longitude: 114.30525
})
const getLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: ({ latitude, longitude }) => {
      locations.value = {
        latitude,
        longitude
      }
    }
  })
}

const options = ref({})
onLoad((e) => {
  options.value = e
})
onMounted(() => {
  getLocation()
})

const handleAppItem = (item) => {
  console.log(`handleItem: ${item.name}`)
  const { type } = item
  switch (type) {
    case 'camera':
      uni.chooseImage({
        success: ({ tempFilePaths }) => {
          uploadFile(tempFilePaths)
        }
      })
      break
    case 'video':
      uni.chooseVideo({
        success: ({ tempFilePath }) => {
          uploadFile([tempFilePath])
        }
      })
      break
    case 'scan':
      uni.scanCode({
        success: (res) => {
          console.log('scanCode success, res=', res)
        },
        fail: () => {
          uni.$u.toast('无内容')
        }
      })
      break
    case 'record':
      navigateTo({
        url: '/pages/views/elevator-maintenance/add-record',
        events: {
          done: () => getWorkDataInfo()
        }
      })
      break
    case 'sheet':
      workSheetModal.value.show = true
      break
    default:
      break
  }
}

const timesModal = ref({
  show: false,
  content: '1'
})
const openTimesDialog = () => {
  timesModal.value.show = true
}
const confirmTimesDialog = async () => {
  console.log('confirmTimesDialog', timesModal.value)
  const { id } = options.value
  const { content } = timesModal.value
  const { workType } = dataDetail.value
  await putWorkDataApi({
    id,
    workType,
    maintenanceNum: content
  })
  uni.$u.toast('修改成功')
  timesModal.value.show = false
}

const currStep = ref(0)
const undoneSteps = ref([
  { name: '接单', value: 2 },
  { name: '到场', value: 3 },
  { name: '待签名', value: 4 },
  { name: '待评价', value: 7 }
])
watchEffect(() => {
  const { state, maintenanceNum } = dataDetail.value
  currStep.value = undoneSteps.value.findIndex((item) => item.value === state)

  timesModal.value.content = maintenanceNum || '1'
})
const setStepItemStyle = (index) => {
  return {
    width: '80rpx',
    height: '80rpx',
    backgroundColor: currStep.value >= index ? '#4395D5' : '#B2DAEF'
  }
}
const handleStepItem = (item, index) => {
  // currStep.value = index
  switch (index) {
    case 1:
      openArriveModal()
      break
    case 2:
      openSignature()
      break
    case 3:
      openEvaluate()
      break
  }
}
const arrivalModal = ref({
  show: false
})
const openArriveModal = () => {
  console.log('openArriveModal')
  uni.showModal({
    title: '提示',
    content: '确认到场工作吗？',
    success: async (res) => {
      if (res.confirm) {
        console.log('用户点击确定')
        const { latitude: lat, longitude: lng } = locations.value
        const { error } = await postWorkDataArriveApi({
          workId: options.value.id,
          lat,
          lng
        })
        if (error) {
          return uni.$u.toast('系统繁忙，请稍后重试')
        }
        uni.$u.toast('到场成功')
        getWorkDataInfo()
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
  // arrivalModal.value.show = true
  // 调用接口
  // 刷新记录列表
}
const confirmArrival = () => {
  console.log('confirmArrival')
  arrivalModal.value.show = false
}
const openSignature = () => {
  console.log('openSignature')
  const { id } = options.value
  navigateTo(`/pages/views/elevator-maintenance/user-signature?id=${id}`)
}
const openEvaluate = () => {
  console.log('openEvaluate')
  const { id } = options.value
  navigateTo(`/pages/views/elevator-maintenance/evaluation?id=${id}`)
}
</script>

<template>
  <view class="undone-detail" bg="#ECECEC">
    <!-- 操作功能 -->
    <view mt-20 bg="#FFFFFF">
      <up-grid :border="false" col="5">
        <up-grid-item
          v-for="(item, index) in apps"
          :key="index"
          @click="handleAppItem(item)"
        >
          <view
            w-90
            h-90
            rounded-34
            f-c-c
            relative
            :style="{
              background: item.background
            }"
          >
            <up-icon
              :name="item.icon"
              :size="30"
              custom-prefix="custom-icon"
              :color="`${'#FFFFFF'}`"
            />
          </view>
          <text text-28 font-400 mt-8 mb-30>{{ item.name }}</text>
        </up-grid-item>
      </up-grid>
    </view>

    <!-- 地图定位 -->
    <view w-full h-300 mt-20 bg="#FFFFFF">
      <map
        id="map"
        class="map"
        style="width: 100%; height: 100%"
        :show-location="true"
        :latitude="locations.latitude"
        :longitude="locations.longitude"
      ></map>
    </view>

    <!-- 操作流程 -->
    <view py-30 bg="#FFFFFF">
      <up-steps :current="currStep">
        <up-steps-item
          v-for="(item, index) in undoneSteps"
          :key="index"
          :title="item.name"
          :item-style="setStepItemStyle(index)"
          @tap="handleStepItem(item, index)"
        >
          <template #icon>
            <up-icon name="checkmark" size="18" :color="`${'#FFF'}`" />
          </template>
        </up-steps-item>
      </up-steps>

      <view mt-20 px-28>
        <up-cell-group :border="false">
          <up-cell
            v-for="(item, index) in actionRecord"
            :key="index"
            :title="item.operator"
            :label="item.operationStateStr"
            :value="item.operationTime"
          />
        </up-cell-group>
      </view>
    </view>

    <!-- 操作记录 -->
    <view px-28 mt-20 bg="#FFFFFF">
      <!-- <view text-32 font-500>操作记录</view> -->
      <up-cell-group :border="false">
        <up-cell
          title="[维保记录]"
          :label="`本次维保为第${dataDetail.maintenanceNum}次维保，为半月维保`"
          :is-link="true"
          @click="openTimesDialog"
        />
      </up-cell-group>
    </view>
  </view>

  <up-modal
    title="维保记录"
    :show="timesModal.show"
    close-on-click-overlay
    :show-cancel-button="true"
    @close="timesModal.show = false"
    @cancel="timesModal.show = false"
    @confirm="confirmTimesDialog"
  >
    <view f-s-c>
      <view text-28>
        本次维保为{{ planTypeMap[dataDetail.planType] }}维保，维保次数为
      </view>
      <up-input
        v-model="timesModal.content"
        type="number"
        placeholder="请输入"
      />
    </view>
  </up-modal>

  <up-modal
    title="确认到场工作吗？"
    :show="arrivalModal.show"
    close-on-click-overlay
    :show-cancel-button="true"
    @close="arrivalModal.show = false"
    @cancel="arrivalModal.show = false"
    @confirm="confirmArrival"
  />

  <up-action-sheet
    :show="workSheetModal.show"
    cancel-text="取消"
    :actions="workSheetModal.actions"
    @close="workSheetModal.show = false"
    @select="workSheetActionSelect"
  />
</template>

<style>
.undone-detail .u-steps {
  grid-template-columns: repeat(auto-fit, minmax(60px, 1fr)) !important;
}
.undone-detail .u-steps-item__line {
  top: 40rpx !important;
}
</style>
