<template>
  <uni-nav-bar
    dark
    :fixed="true"
    shadow
    background-color="#4AA4EA"
    status-bar
    left-icon="left"
    left-text="返回"
    :title="title"
    right-text="新增"
    @clickLeft="back"
    @clickRight="add"
  />
  <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">
      <uni-swipe-action>
        <uni-swipe-action-item
          :right-options="current == 0 ? options : optionsFinish"
          v-for="(item, index) in tableList"
          :key="index"
          @click="(e) => onClickSwipe(e, item)"
        >
          <div class="list" @click="leaseOut(item)">
            <div style="margin-right: 8px">{{ index + 1 }}.</div>
            <div class="item">
              <div>申请时间: {{ item.createTime }}</div>
              <div>领料单号: {{ item.code }}</div>
              <div>领料工器具: {{ item.maTypeNames }}</div>
              <div>领料班组: {{ item.teamName }}</div>
              <div>领料工程: {{ item.projectName }}</div>
              <div>班组长: {{ item.leasePerson }}</div>
              <div>预领数量: {{ item.preCountNum || 0 }}</div>
              <div>已领数量: {{ item.alNum || 0 }}</div>
              <div>待领数量: {{ item.waitCountNum || 0 }}</div>
              <div>
                状态:
                <uni-tag
                  :text="item.taskStatusName"
                  :inverted="true"
                  :type="item.taskStatus == 1 ? 'error' : 'success'"
                />
              </div>
              <div>是否签名: 
                <uni-tag
                  :text="item.isElectronicSign == 1 ? '未签名' : '已签名'"
                  :inverted="true"
                  :type="item.isElectronicSign == 1 ? 'error' : 'success'"
                />
              </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 { getPickingOutboundListAPI, deleteLeaseApplyApi,submitLeaseOut } from '@/services/picking/outbound.js'

const title = ref('工器具领料')
const opts = ref()
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  range: [],
  keyWord: '',
  taskStatus: 1,
})
const items = ref(['未完成', '已完成'])
const current = ref(0)
const tableList = ref([])
const total = ref(0)
const options = ref([
  {
    text: '电子签名',
    style: {
      backgroundColor: '#c6bf3b',
    },
  },
  {
    text: '提交',
    style: {
      backgroundColor: '#2c954f',
    },
  },
  {
    text: '编辑',
    style: {
      backgroundColor: '#2f8cf0',
    },
  },
  {
    text: '删除',
    style: {
      backgroundColor: '#ff4949',
    },
  },
])
const optionsFinish = ref([
  {
    text: '电子签名',
    style: {
      backgroundColor: '#c6bf3b',
    },
  },
])

const finish = computed(() => {
  if (total.value === tableList.value.length) return true
})
const back = () => {
  uni.navigateBack({
    delta: 1,
  })
}
const add = () => {
  uni.navigateTo({
    url: '/pages/toolsLease/toolsLeaseAdd',
  })
}

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,
    taskStatus: queryParams.taskStatus,
  }
  console.log('🚀 ~ getList ~ params:', params)
  try {
    const res = await getPickingOutboundListAPI(params)
    console.log('🚀 ~ getList ~ res:', res)
    if (res.code == 200) {
      tableList.value = res.data.rows
      console.log('🚀 ~ getList ~ tableList.value:', tableList.value)
      total.value = res.data.total
    }
  } catch (error) {
    console.log('🚀 ~ getList ~ error:', error)
    tableList.value = []
    total.value = 0
  }
}

// 点击列表项
const onClickItem = (item) => {
  current.value = item.currentIndex
  queryParams.taskStatus = item.currentIndex == 0 ? 1 : 4
  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)
  if (e.index == 0) {
    // 电子签名
    console.log('电子签名-e', e)
    console.log('电子签名-item', item)
    const params = {
        id: item.id,
        leaseSignUrl: item.leaseSignUrl,
        // leaseSignType: item.leaseSignType,
        isLease: true,
    }
    uni.navigateTo({
        url: `/pages/my/signature?params=${JSON.stringify(params)}`,
    })
  }else if(e.index == 1) {
    // 提交
          try {
            let paramsOne = {
              id: item.id,
              isSubmit: 0,
            }
            const submitRes = await submitLeaseOut(paramsOne)
            console.log('🚀 ~ 提交成功 ~ submitRes:', submitRes)
            if (submitRes.code === 200 && submitRes.msg === "该领料单无未出库领料数据，请确认是否提交") {
            uni.showModal({
              title: '提示',
              content: "是否确认提交？",
              success: async (res) => {
                if (res.confirm) {
                  const params = {
                    id: item.id,
                  }
                  try {
                    const submitRes = await submitLeaseOut(params)
                    if (submitRes.code === 200) {
                      uni.showToast({
                        title: '提交成功', // 设置提示信息
                        icon: 'success'
                      })
                      getList() // 取消注释，提交成功后刷新列表
                    } else {
                      uni.showToast({
                        title: '提交失败',
                        icon: 'none'
                      })
                    }
                  } catch (error) {
                    console.log('🚀 ~ 提交失败 ~ error:', error)
                    uni.showToast({
                      title: '提交失败',
                      icon: 'none'
                    })
                  }
                } else if (res.cancel) {
                  console.log('用户取消提交')
                }
              }
            })
            } else if (submitRes.code === 200 && submitRes.msg === "该领料单有未出库领料数据，请确认是否提交") {
            uni.showModal({
              title: '提示',
              content: "该领料单有未出库领料数据，是否确认提交？",
              success: async (res) => {
                if (res.confirm) {
                  const params = {
                    id: item.id,
                  }
                  try {
                    const submitRes = await submitLeaseOut(params)
                    if (submitRes.code === 200) {
                      uni.showToast({
                        title: '提交成功', // 设置提示信息
                        icon: 'success'
                      })
                      getList() // 取消注释，提交成功后刷新列表
                    } else {
                      uni.showToast({
                        title: '提交失败',
                        icon: 'none'
                      })
                    }
                  } catch (error) {
                    console.log('🚀 ~ 提交失败 ~ error:', error)
                    uni.showToast({
                      title: '提交失败',
                      icon: 'none'
                    })
                  }
                } else if (res.cancel) {
                  console.log('用户取消提交')
                }
              }
            })
            }
          } catch (error) {
            console.log('🚀 ~ 提交失败 ~ error:', error)
            uni.showToast({
              title: '提交失败',
              icon: 'none'
            })
          }



  }else if(e.index == 2){
    // 编辑
    const params = JSON.stringify({
      id: item.id,
      taskId: item.taskId,
      isEdit: true,
    })
    uni.navigateTo({
      url: `/pages/toolsLease/toolsLeaseAdd?params=${params}`,
    })
  } else {
    // 删除
    deleteItem(item)
  }
}

// 出库
const leaseOut = (item) => {
  console.log('🚀 ~ leaseOut ~ item:', item)
  if (opts.value.isOut && item.taskStatus == 1) {
    const params = JSON.stringify({
      id: item.id,
      projectId: item.projectId,
      projectName: item.projectName,
      teamId: item.teamId,
      teamName: item.teamName,
    })
    uni.navigateTo({
      url: `/pages/toolsLease/toolsLeaseOut?params=${params}`,
    })
  } else {
    uni.showToast({
      title: '已完成出库',
      icon: 'none',
    })
  }
}

// 删除
const deleteItem = (item) => {
  console.log('🚀 ~ deleteItem ~ item:', item)
  uni.showModal({
    title: '提示',
    content: '确定删除吗？',
    success: (res) => {
      if (res.confirm) {
        deleteLeaseApplyApi([item.id])
          .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)
  opts.value = options.params ? JSON.parse(options.params) : {}
  title.value = opts.value.isOut ? '工器具出库' : '工器具领料'
})
onShow(() => {
  setTimeout(() => {
    getList()
  }, 300)
})
</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>
