<script setup>
import { getWorkDataInfoApi, postWorkDataRepairAuditApi } from '@/api/elevator'
import { useUniApi } from '@/composables/use-uni-api'
import { useUserStore } from '@/store/user'

const instance = getCurrentInstance().proxy
const eventChannel = instance.getOpenerEventChannel()

const hasAdminPermission = computed(() => {
  const { isAdmin } = storeToRefs(useUserStore())
  return isAdmin.value
})

const planTypeMap = {
  11: '系统调整优化',
  12: '维修换件'
}

// 电梯名称 工作选项 工作状态 创建时间 发布人员 期望时间 工作描述 被困人数 受伤人数 备注 其它原因
const cellData = ref([
  { key: '电梯名称', field: 'elevatorName' },
  {
    key: '维修类型',
    format: () => {
      return planTypeMap[dataDetail.value.planType]
    }
  },
  { key: '零部件名称', field: 'partName' },
  { key: '规格型号', field: 'partModel' },
  { key: '数量', field: 'partNum' },
  {
    key: '材料报价',
    field: 'materialQuote',
    format: (info) => {
      const num = info.materialQuote || 0
      return Number(num).toString()
    }
  },
  {
    key: '人工及杂费',
    field: 'otherExpenses',
    format: (info) => {
      const num = info.otherExpenses || 0
      return Number(num).toString()
    }
  },
  // { key: '总预算', field: '' },
  { key: '故障类型', field: 'faultType' },
  { key: '发生时间', field: 'happenTime' },
  { key: '恢复时间', field: 'restoreTime' },
  { key: '工作描述', field: 'description' }
])

const { navigateTo } = useUniApi()
const toRecord = () => {
  const { id, elevatorNum } = dataDetail.value
  navigateTo(
    `/pages/views/elevator-maintenance/work-sheet?id=${id}&elevatorNum=${elevatorNum}`
  )
}

const dataDetail = ref({})
const getDetail = async () => {
  const { error, data } = await getWorkDataInfoApi({
    ...options.value
  })
  if (error) {
    return
  }
  dataDetail.value = data || {}
}
watchEffect(() => {
  let { repairMaterialData, planType } = dataDetail.value
  try {
    repairMaterialData = JSON.parse(repairMaterialData)
  } catch (error) {
    repairMaterialData = {}
  }
  const { partName, partModel, partNum } = repairMaterialData
  dataDetail.value.partName = partName
  dataDetail.value.partModel = partModel
  dataDetail.value.partNum = partNum

  // 找到 cellData 中 partName 的 index
  const partNameIndex = cellData.value.findIndex(
    (item) => item.field === 'partName'
  )
  if (planType === 11) {
    cellData.value[partNameIndex].key = '调整优化项目'
    // } else if (planType === 12) {
  } else {
    cellData.value[partNameIndex].key = '零部件名称'
  }
})

// 相册
const albumUrls = ref([])
watchEffect(() => {
  const { repairBeforeRecord, repairReplaceRecord, repairAfterRecord } =
    dataDetail.value
  albumUrls.value = [repairBeforeRecord, repairReplaceRecord, repairAfterRecord]
})

// 是否显示维保记录
const showMaintainRecord = computed(() => {
  const { state } = dataDetail.value
  return [4, 7].includes(state)
})
const options = ref({})
onLoad(async (e) => {
  dataDetail.value = {}
  options.value = e
  await getDetail()
})

const materialQuoteModal = ref({
  show: false,
  content: ''
})
const confirmMaterialQuote = () => {
  materialQuoteModal.value.show = false
  dataDetail.value.materialQuote = materialQuoteModal.value.content
}

const otherExpensesModal = ref({
  show: false,
  content: ''
})
const confirmOtherExpenses = () => {
  otherExpensesModal.value.show = false
  dataDetail.value.otherExpenses = otherExpensesModal.value.content
}

const handlerAdjust = (field) => {
  const { materialQuote, otherExpenses } = dataDetail.value
  if (field === 'materialQuote') {
    materialQuoteModal.value.show = true
    const num = materialQuote || 0
    materialQuoteModal.value.content = Number(num).toString()
  } else if (field === 'otherExpenses') {
    const num = otherExpenses || 0
    otherExpensesModal.value.show = true
    otherExpensesModal.value.content = Number(num).toString()
  }
}

const postWorkDataRepairAudit = async () => {
  const materialQuote = materialQuoteModal.value.content || 0
  const otherExpenses = otherExpensesModal.value.content || 0
  const { id } = dataDetail.value
  const { error, result } = await postWorkDataRepairAuditApi({
    id,
    materialQuote,
    otherExpenses
  })
  if (error) {
    uni.$u.toast(result.msg || '提交失败，请稍后重试')
  }
  uni.$u.toast('审核成功')
  eventChannel.emit('done', {})
  setTimeout(() => {
    uni.navigateBack()
  }, 1500)
}

const submit = () => {
  uni.showModal({
    title: '确认订单',
    content: '已确认订单的报价？',
    success: ({ confirm, cancel }) => {
      if (confirm) {
        console.log('用户点击确定')
        postWorkDataRepairAudit()
      } else if (cancel) {
        console.log('用户点击取消')
      }
    }
  })
}
</script>

<template>
  <view px-28>
    <up-cell-group :border="false">
      <up-cell v-for="(item, index) in cellData" :key="index" :title="item.key">
        <template #value>
          <view f-c-c>
            <text mr-12>
              {{
                item.format ? item.format(dataDetail) : dataDetail[item.field]
              }}
            </text>
            <up-button
              v-if="
                ['materialQuote', 'otherExpenses'].includes(item.field) &&
                hasAdminPermission
              "
              type="primary"
              size="mini"
              :plain="true"
              text="调整"
              @click="handlerAdjust(item.field)"
            />
          </view>
        </template>
      </up-cell>
    </up-cell-group>

    <!-- 图片 -->
    <view mt-20 mb-100>
      <up-album :urls="albumUrls" multiple-size="100" auto-wrap="true" />
    </view>
  </view>

  <view
    v-if="hasAdminPermission"
    position="fixed"
    w-full
    h-130
    bottom-0
    z-9
    f-s-c
    flex-col
    bg-white
  >
    <view absolute left-0 right-0 m-auto bottom-36>
      <up-button
        type="primary"
        text="确认订单"
        :custom-style="{
          width: '650rpx'
        }"
        @click="submit"
      />
    </view>
  </view>

  <up-modal
    title="材料报价"
    :show="materialQuoteModal.show"
    close-on-click-overlay
    :show-cancel-button="true"
    @close="materialQuoteModal.show = false"
    @cancel="materialQuoteModal.show = false"
    @confirm="confirmMaterialQuote"
  >
    <view f-s-c>
      <up-input
        v-model="materialQuoteModal.content"
        type="digit"
        placeholder="请输入"
      />
    </view>
  </up-modal>

  <up-modal
    title="人工及杂费"
    :show="otherExpensesModal.show"
    close-on-click-overlay
    :show-cancel-button="true"
    @close="otherExpensesModal.show = false"
    @cancel="otherExpensesModal.show = false"
    @confirm="confirmOtherExpenses"
  >
    <view f-s-c>
      <up-input
        v-model="otherExpensesModal.content"
        type="digit"
        placeholder="请输入"
      />
    </view>
  </up-modal>
</template>
