<template>
  <view class="">
    <com-empty-view v-if="jobList.length == 0"></com-empty-view>
    <job-filter ref="filter" :isShowAsn="isShowAsn" :isShowJob="isShowJob" @switchChangeToday="switchChangeToday" @switchChangeWait="switchChangeWait" @onScanNumber="getScanNumber" @onScanAsnNumber="getScanAsnNumber" :checkedToday="checkedToday" :checkedWaitTask="checkedWaitTask"> </job-filter>
    <view v-if="jobList.length > 0" class="u-m-20">
      <u-swipe-action :show="item.show" :index="index" v-for="(item, index) in jobList" :key="index" :options="item.status == '2' ? detailGiveupOptions : detailOptions" bg-color="rgba(255,255,255,0)" class="u-m-b-20" @click="swipeClick">
        <com-receipt-job-card :dataContent="item" @click="openJobDetail(item)"></com-receipt-job-card>
      </u-swipe-action>
      <u-loadmore :status="loadingType" v-if="jobList.length > 0" />
      <receipt-info-popup ref="jobInfoPopup"></receipt-info-popup>
      <receipt-job-list-popup ref="jobListPopup" @selectedItem="selectedItem"></receipt-job-list-popup>
    </view>
    <win-scan-button @goScan="openScanPopup" v-if="jobList.length > 0"></win-scan-button>
    <winScanPackJob :title="scanTitle" ref="scanPopup" @getResult="getScanResult"> </winScanPackJob>
    <jobListCom ref="jobListRef" @selectItem="selectItem"></jobListCom>
    <com-message ref="comMessageRef" />
  </view>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, onMounted, nextTick, watch } from 'vue'
import { getPurchaseReceiptJobList, cancleTakePurchaseReceiptJob } from '@/api/request2.js'

import { goHome, updateTitle } from '@/common/basic.js'

import { getDetailOption, getDetailGiveupOption } from '@/common/array.js'

import comEmptyView from '@/mycomponents/common/comEmptyView.vue'
import jobFilter from '@/mycomponents/job/jobFilter.vue'

import comReceiptJobCard from '@/pages/purchaseReceipt/coms/comReceiptJobCard.vue'
import receiptJobListPopup from '@/pages/purchaseReceipt/coms/receiptJobListPopup.vue'
import receiptInfoPopup from '@/pages/purchaseReceipt/coms/receiptInfoPopup.vue'
import jobListCom from '@/mycomponents/jobList/jobList.vue'
import winScanButton from '@/mycomponents/scan/winScanButton.vue'
import winScanPackJob from '@/mycomponents/scan/winScanPackJob.vue'

const { proxy } = getCurrentInstance()
const jobList = ref([])
const pageNo = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const loadingType = ref('nomore')
const checkedToday = ref(false)
const checkedWaitTask = ref(false)
const todayTime = ref('')
const status = ref('1,2') // 待处理 、进行中
const detailOptions = ref([])
const detailGiveupOptions = ref([])
const filter = ref()
const comMessageRef = ref()
const jobInfoPopup = ref()
const jobListPopup = ref()
const scanPopup = ref()
const jobListRef = ref()
const props = defineProps({
  operation: {
    type: String,
    default: 'reject'
  }, // reject  收货  拒绝
  isShowAsn: {
    type: Boolean,
    default: true
  },
  isShowJob: {
    type: Boolean,
    default: true
  },
  scanTitle: {
    type: String,
    default: '箱标签'
  },
  scanTitle: {
    type: String,
    default: '箱标签'
  }
})
onMounted(() => {
  nextTick(() => {
    detailOptions.value = getDetailOption()
    detailGiveupOptions.value = getDetailGiveupOption()
    // refresh()
  })
})
const refresh = () => {
  getList('refresh')
}
const openFilter = () => {
  filter.value.openFilter()
}
const goHome = () => {
  goHome()
}
const getList = (type) => {
  proxy.$modal.loading('加载中­....')
  loadingType.value = 'loading'
  if (type === 'refresh') {
    pageNo.value = 1
    jobList.value = []
  }

  const filters = []
  if (checkedToday.value) {
    filters.push({
      column: 'create_time',
      action: 'betweeen',
      value: todayTime.value
    })
  }

  filters.push({
    column: 'status',
    action: 'in',
    value: status.value
  })

  const params = {
    filters,
    pageNo: pageNo.value,
    pageSize: pageSize.value
  }
  console.log(params)
  getPurchaseReceiptJobList(params)
    .then((res) => {
      uni.hideLoading()
      if (type === 'refresh') {
        uni.stopPullDownRefresh()
      }

      const { list } = res.data
      totalCount.value = res.data.total
      updateTitle(`采购退货(${totalCount.value})`)
      loadingType.value = 'loadmore'
      if (list == null || list.length == 0) {
        loadingType.value = 'nomore'
        return
      }
      jobList.value = type === 'refresh' ? list : jobList.value.concat(list)
      pageNo.value++
    })
    .catch((error) => {
      if (type === 'refresh') {
        uni.stopPullDownRefresh()
      }
      loadingType.value = ''
      updateTitle('采购收货')
      uni.hideLoading()
      showErrorMessage(error)
    })
}
const getScanAsnNumber = (code) => {
  getDataListByType(code, 'asnNumber')
}
const getScanNumber = (code) => {
  getDataListByType(code, 'number')
}
const getDataListByType = (code, type) => {
  proxy.$modal.loading('加载中­....')
  const filters = []
  filters.push({
    column: 'status',
    action: 'in',
    value: '1,2'
  })
  if (type == 'asnNumber') {
    filters.push({
      column: 'asn_number',
      action: '==',
      value: code
    })
  } else if (type == 'number') {
    filters.push({
      column: 'number',
      action: '==',
      value: code
    })
  }

  const params = {
    filters,
    pageNo: 1,
    pageSize: 100
  }
  getPurchaseReceiptJobList(params)
    .then((res) => {
      uni.hideLoading()
      if (res.data.list.length == 0) {
        showMessage('未查找到' + `【${code}】的收货任务`)
      } else if (res.data.list.length == 1) {
        openJobDetail(res.data.list[0])
      } else if (type == 'asnNumber') {
        showItemList(res.data.list)
      }
    })
    .catch((error) => {
      uni.hideLoading()
      showMessage(error)
    })
}
const openJobDetail = (item, packingNumber = '') => {
  proxy.$tab.navigateTo(`./receiptDetail?id=${item.masterId}&status=${item.status}&operation=${props.operation}&scaned=${props.packingNumber}`)
}
const showItemList = (itemList) => {
  jobListPopup.value.openPopup(itemList)
}
const selectedItem = (item) => {
  openJobDetail(item)
}
const swipeClick = (index, index1) => {
  // var text = clearTirmAndWrap(requestList.value[index].options[index].text)
  let text = ''
  const dataContent = jobList.value[index]
  if (dataContent.status == '2') {
    text = detailGiveupOptions.value[index1].text
  } else {
    text = detailOptions.value[index1].text
  }
  if (text == '详情') {
    openjobInfoPopup(dataContent)
  } else if (text == '放弃') {
    comMessageRef.value.showQuestionMessage('确定要放弃当前任务?', (res) => {
      if (res) {
        cancleJob(dataContent.masterId)
      }
    })
  }
}
const openjobInfoPopup = (item) => {
  jobInfoPopup.value.openPopup(item)
}
const cancleJob = (id) => {
  cancleTakePurchaseReceiptJob(id)
    .then((res) => {
      if (res.data) {
        getList('refresh')
        uni.showToast({
          title: '放弃任务成功'
        })
      } else {
        showMessage('放弃任务失败')
      }
    })
    .catch((error) => {
      showMessage(error)
    })
}
const switchChangeToday = (state, creationTime) => {
  checkedToday.value = state
  todayTime.value = creationTime
  getList('refresh')
}
const switchChangeWait = (state, jobStatus) => {
  checkedWaitTask.value = state
  status.value = jobStatus
  getList('refresh')
}
const showMessage = (message) => {
  comMessageRef.value.showErrorMessage(message, (res) => {
    if (res) {
    }
  })
}
const onReach = (message) => {
  if (loadingType.value == 'loading' || loadingType.value == 'nomore') {
    return
  }
  getList('more')
}
const openScanPopup = () => {
  scanPopup.value.openScanPopup()
}
const selectItem = (item) => {
  scanPopup.value.closeScanPopup()
  openJobDetail(item, item.packingNumber)
}

const getScanResult = (result) => {
  try {
    let filters = []
    if (result.label.barType == 'BarCode') {
      // ASN单号
      filters = [
        {
          column: 'asn_number',
          action: '==',
          value: result.label.code
        }
      ]
    } else {
      filters = [
        {
          column: 'packingNumber',
          action: '==',
          value: result.label.packingNumber
        },
        {
          column: 'batch',
          action: '==',
          value: result.label.batch
        },
        // {
        //   column: 'qty',
        //   action: '==',
        //   value: result.label.qty
        // },
        {
          column: 'itemCode',
          action: '==',
          value: result.label.itemCode
        }
        // {
        //   column: 'fromLocationCode',
        //   action: '==',
        //   value: result.label.fromLocationCode
        // }
      ]
    }
    getPurchaseReceiptJobList({
      filters,
      pageNo: 1,
      pageSize: 100
    })
      .then((res) => {
        const resultList = res.data.list
        if (resultList.length > 0) {
          resultList.forEach((item) => {
            item.title = item.number
            item.selected = false
          })
          const list = []
          resultList.forEach((item) => {
            if (!list.find((subItem) => subItem.title == item.title)) {
              list.push(item)
            }
          })

          if (list.length > 1) {
            jobListRef.value.openList(list)
          } else {
            selectItem(list[0])
          }
        } else {
          showMessage('未查找到任务')
        }
      })
      .catch((error) => {
        showMessage(error)
      })
  } catch (e) {
    showMessage(e.message)
  }
}
defineExpose({
  refresh,
  openFilter,
  goHome,
  onReach
})
</script>

<style scoped lang="scss"></style>
