<template>
  <uni-nav-bar dark :fixed="true" shadow background-color="#4AA4EA" status-bar title="退料任务">
    <template v-slot:left>
      <view style="font-size: 18px; display: flex; align-items: center" @click="back">
        <!-- 图标 -->
        <uni-icons type="left" size="20" color="#fff"></uni-icons>
        <!-- 文本 -->
        <text>返回</text>
      </view>
    </template>
    <template v-slot:right>
      <view style="font-size: 18px">
        <text @click="add">新增</text>
      </view>
    </template></uni-nav-bar
  >
  <div class="content">
    <div class="query">
      <uni-datetime-picker
        v-model="queryParams.range"
        type="daterange"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
      />
      <uni-easyinput
        errorMessage
        v-model="queryParams.keyWord"
        placeholder="请输入内容"
        style="margin: 0 5px"
      />
      <button size="mini" style="background-color: #f0a037; color: #fff" @click="handleQuery">
        查询
      </button>
    </div>

    <div style="width: 60%; margin: 10px auto">
      <uni-segmented-control
        :values="items"
        :current="current"
        @clickItem="onClickItem"
        styleType="button"
        activeColor="#007aff"
      />
    </div>

    <!-- 滚动列表 -->
    <scroll-view scroll-y @scrolltolower="onScrollTolower" class="scroll-container">
      <uni-swipe-action class="swipe-action" ref="swipeRef">
        <uni-swipe-action-item
          v-for="(item, index) in tableList"
          :right-options="item.options"
          :key="index"
          @click="(e) => onClickSwipe(e, item)"
        >
          <div class="list" @click="handleDetails(item)">
            <div style="margin-right: 8px">{{ index + 1 }}.</div>
            <div class="item">
              <div>申请时间: {{ item.createTime }}</div>
              <div>退料单号: {{ item.code }}</div>
              <div>退料物资: {{ item.typeName }}</div>
              <div>退料班组: {{ item.teamName }}</div>
              <div>工程名称: {{ item.proName }}</div>
              <div>退料人: {{ item.backPerson }}</div>
              <div>联系电话: {{ item.phone }}</div>
              <div>已退数量: {{ item.backNum }}</div>
              <div>备注: {{ item.remark }}</div>
              <div>
                状态:
                <uni-tag
                  v-if="item.taskStatus == 0"
                  text="未完成"
                  type="warning"
                  custom-style="warningStyle"
                />
                <uni-tag
                  v-if="item.taskStatus == 1"
                  text="已驳回"
                  type="warning"
                  custom-style="warningStyle"
                />
                <uni-tag
                  v-if="item.taskStatus == 2"
                  text="已完成"
                  type="success"
                  custom-style="successStyle"
                />
              </div>
            </div>
          </div>
        </uni-swipe-action-item>
      </uni-swipe-action>
      <div style="display: flex; justify-content: center; align-items: center; height: 50px">
        {{ finish ? '没有更多数据了~' : '正在加载...' }}
      </div>
    </scroll-view>
  </div>
</template>

<script setup>
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref, reactive, computed } from 'vue'
import { getBackListAPI, deleteBackApi } from '@/services/materialsStation'

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  range: [],
  keyWord: '',
  appTaskStatus: 0,
})
const items = ref(['未完成', '已完成'])
const current = ref(0)
const tableList = ref([])
const total = ref(0)
const swipeRef = ref()
const finish = computed(() => {
  if (total.value === tableList.value.length) return true
})
const back = () => {
  uni.navigateBack({
    delta: 1,
  })
}
const add = () => {
  uni.navigateTo({ url: `/pages/materialsStation/toolsBack/toolsAddBack` })
}

const handleQuery = () => {
  console.log('🚀 ~ handleQuery ~ handleQuery:', queryParams)
  getList()
}

const getList = async () => {
  const params = {
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
    startTime: queryParams.range && queryParams.range[0],
    endTime: queryParams.range && queryParams.range[1],
    keyWord: queryParams.keyWord,
    appTaskStatus: queryParams.appTaskStatus,
  }
  console.log('🚀 ~ getList ~ params:', params)
  try {
    uni.showLoading({ title: '加载中', mask: true })
    const res = await getBackListAPI(params)
    console.log('🚀 ~ getList ~ res:', res)
    if (res.code == 200) {
      tableList.value = res.data.rows.map((item, index) => {
        let options = [
          // { text: '电子签名', style: { backgroundColor: '#c6bf3b' } },
          { text: '编辑', style: { backgroundColor: '#2f8cf0' } },
          { text: '删除', style: { backgroundColor: '#ff4949' } },
        ]
        return {
          ...item,
          options: item.taskStatus == 2 ? [] : options, // 如果任务状态为4，则不显示操作按钮
        }
      })
      console.log('🚀 ~ getList ~ tableList.value:', tableList.value)
      total.value = res.data.total
    }
  } catch (error) {
    console.log('🚀 ~ getList ~ error:', error)
    tableList.value = []
    total.value = 0
  } finally {
    uni.hideLoading()
  }
}

// 点击列表项
const onClickItem = (item) => {
  current.value = item.currentIndex
  queryParams.appTaskStatus = item.currentIndex === 0 ? 0 : 1
  getList()
}

// 滚动事件
const onScrollTolower = () => {
  console.log('🚀 ~ onScrollTolower ~ onScrollTolower:')
  if (total.value > tableList.value.length) {
    queryParams.pageSize += 10
    getList()
  }
}

// 滑动
const onClickSwipe = async (e, item) => {
  console.log('🚀 ~ onClickSwipe ~ e:', e, item)
  try {
    if (e.content.text == '编辑') {
      // 编辑
      console.log('🚀 ~ 编辑 ~ item:', item)
      const params = JSON.stringify({
        id: item.id,
        taskId: item.taskId,
        isEdit: true,
      })
      uni.navigateTo({
        url: `/pages/materialsStation/toolsBack/toolsAddBack?params=${params}`,
      })
    } else if (e.content.text == '删除') {
      // 删除
      await deleteItem(item)
    }
    swipeRef.value.closeAll()
  } catch (error) {
    console.error('操作失败:', error)
    uni.showToast({
      title: error.message || '操作失败',
      icon: 'error',
    })
    swipeRef.value.closeAll()
  }
}

// 详情
const handleDetails = async (item) => {
  console.log('🚀 ~ handleDetails ~ item:', item)
  uni.navigateTo({
    url: `/pages/materialsStation/teamLeaseRecord/equipmentDetails?id=${item.id}&isBack=${true}`,
  })
}

// 删除
const deleteItem = (item) => {
  console.log('🚀 ~ deleteItem ~ item:', item)
  uni.showModal({
    title: '提示',
    content: '确定删除吗？',
    success: (res) => {
      if (res.confirm) {
        const params = JSON.stringify({
          id: item.id,
        })
        deleteBackApi(params)
          .then((res) => {
            console.log('🚀 ~ .then ~ res:', res)
            if (res.code == 200) {
              getList()
            }
          })
          .catch((err) => {
            console.log('🚀 ~ deleteItem ~ err:', err)
          })
      }
    },
  })
}

onLoad((options) => {
  console.log('🚀 ~ onLoad ~ options:', options)
  getList()
})

onShow(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.content {
  padding: 10px;
  height: calc(100vh - 147px);
  .query {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #f0a037;
  }

  .list {
    min-height: 120px;
    margin-bottom: 10px;
    background: #fafafa;
    border-radius: 6px;
    padding: 8px;
    display: flex;
  }
}
</style>
