<template>
  <!-- 退料任务 -->
  <view class="page-container">
    <view class="complete-btn">
      <view class="btn" @click="changeTab(1)">
        <span>未完成</span>
        <div v-if="active == 1" class="bt-line"></div>
      </view>
      <view class="btn" style="margin-left: 120rpx" @click="changeTab(2)">
        <span>已完成</span>
        <div v-if="active == 2" class="bt-line"></div>
      </view>
    </view>
    <uni-row :gutter="24" class="search-form">
      <uni-col :span="24">
        <view>
          <uni-datetime-picker
              v-model="dateArray"
              type="daterange"
              @maskClick="maskClick"
              @change="onChangeDate"
              placeholder="选择日期范围"
              :styles="{ width: '100%' }"
          />
        </view>
      </uni-col>
    </uni-row>
    <uni-row :gutter="24" class="search-form">
      <!-- 新增签字状态筛选 -->
      <uni-col :span="6">
        <view>
          <uni-data-select
              v-model="queryParams.isSign"
              :localdata="signOptions"
              @change="getTableList(true)"
              placeholder="请选择签字状态"
              :clear="false"
          ></uni-data-select>
        </view>
      </uni-col>
      <uni-col :span="10">
        <view>
          <uni-easyinput placeholder="请输入内容" v-model="queryParams.keyWord"/>
        </view>
      </uni-col>
      <uni-col :span="4">
        <view class="search" @click="getTableList(true)">搜索</view>
      </uni-col>
      <uni-col :span="4">
        <view class="addBtn" @click="goAdd()">新增</view>
      </uni-col>
    </uni-row>
    <scroll-view scroll-y @scrolltolower="onScrollTolower" class="scroll-container">
      <div class="table-list-item" v-for="(item, index) in tableList" :key="index" @click="handleItem(item)">
        <uni-swipe-action  class="swipe-action" ref="swipeRef">
          <uni-swipe-action-item :right-options="item.taskStatus==0 ? options:options2" @click="onClick($event,item, index)">
            <div class="title">
              <span class="code">{{ item.code }}</span>
              <div class="status-tag">
                <!-- 任务状态标签 -->
                <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"/>

                <!-- 签字状态标签（所有状态都显示） -->
                <uni-tag
                    v-if="item.backSignUrl"
                    text="已签字"
                    type="primary"
                    custom-style="primaryStyle"
                    style="margin-left: 10rpx;"
                />
                <uni-tag
                    v-if="!item.backSignUrl"
                    text="未签字"
                    type="error"
                    custom-style="errorStyle"
                    style="margin-left: 10rpx;"
                />
              </div>
            </div>
            <div class="line"></div>
            <uni-row :gutter="24">
              <uni-col :span="8">申请时间：</uni-col>
              <uni-col :span="16"
              ><div class="cont">{{ item.createTime }}</div></uni-col
              >
            </uni-row>
            <uni-row :gutter="24">
              <uni-col :span="8">退料单号：</uni-col>
              <uni-col :span="16"
              ><div class="cont">{{ item.code }}</div></uni-col
              >
            </uni-row>
            <uni-row :gutter="24">
              <uni-col :span="8">退料物资：</uni-col>
              <uni-col :span="16"
              ><div class="cont">{{ item.typeName }}</div></uni-col
              >
            </uni-row>
            <uni-row :gutter="24">
              <uni-col :span="8">退料单位：</uni-col>
              <uni-col :span="16"
              ><div class="cont">{{ item.unitName }}</div></uni-col
              >
            </uni-row>
            <uni-row :gutter="24">
              <uni-col :span="8">工程名称：</uni-col>
              <uni-col :span="16"
              ><div class="cont">{{ item.proName }}</div></uni-col
              >
            </uni-row>
            <uni-row :gutter="24">
              <uni-col :span="8">制单人：</uni-col>
              <uni-col :span="16"
              ><div class="cont">{{ item.backPerson }}</div></uni-col
              >
            </uni-row>
            <uni-row :gutter="24">
              <uni-col :span="8">联系电话：</uni-col>
              <uni-col :span="16"
              ><div class="cont">{{ item.phone }}</div></uni-col
              >
            </uni-row>
            <!-- <uni-row :gutter="24">
                 <uni-col :span="8">已退数量：</uni-col>
                 <uni-col :span="16"><div class="cont">{{  }}</div></uni-col>
             </uni-row> -->
            <uni-row :gutter="24">
              <uni-col :span="8">备注：</uni-col>
              <uni-col :span="16"
              ><div class="cont">{{ item.remark }}</div></uni-col
              >
            </uni-row>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </div>
      <view class="loading-text">
        {{ finish ? '没有更多数据了~' : '正在加载...' }}
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { getBackList,submitBackApply,backApplyRemove } from '../../services/back.js'
import { onLoad,onShow} from '@dcloudio/uni-app'
import { debounce } from 'lodash-es'
const total = ref(0) //                 数据总量
const active = ref(1) //                tap索引
const tableList = ref([]) //            列表数据源
const dateArray = ref([]) //            日期范围
const swipeRef = ref()
// 签字状态选项
const signOptions = ref([
  { value: 0, text: "全部" },
  { value: 1, text: "未签字" },
  { value: 2, text: "已签字" }
]);
// 查询参数
const queryParams = ref({
  startTime: '', //                   开始时间
  endTime: '', //                     结束时间
  keyWord: '', //                     关键字
  appTaskStatus: 0,
  isSign: 0, // 默认显示全部
  pageNum: 1,
  pageSize: 5,
})

// 右滑按钮组-未完成
const options = ref([
  {
    text: '电子签名',
    style: {
      backgroundColor: '#65a1ff',
      color: '#fff',
      fontSize: '30rpx',
    },
  },
  {
    text: '提交',
    style: {
      backgroundColor: '#13ce66',
      color: '#fff',
      fontSize: '30rpx',
    },
  },
  {
    text: '删除',
    style: {
      backgroundColor: '#ed6042',
      color: '#fff',
      fontSize: '30rpx',
    },
  },
])
// 右滑按钮组-已完成
const options2 = ref([
  {
    text: '签名',
    style: {
      backgroundColor: '#65a1ff',
      color: '#fff',
      fontSize: '30rpx',
    },
  },
  {
    text: '查看',
    style: {
      backgroundColor: '#13ce66',
      color: '#fff',
      fontSize: '30rpx',
    },
  },
  // {
  //     text: '删除',
  //     style: {
  //         backgroundColor: '#ed6042',
  //         color: '#fff',
  //         fontSize: '30rpx',
  //     },
  // },
])
//点击事件
const onClick=(e,item,itemIndex)=> {
  console.log('🚀 ~ onClick ~ item:', item)
  const { index } = e
  console.log(index)
  if (index === 0) {
    const params = {
      id: item.id,
      backSignUrl: item.backSignUrl,
      backSignType: item.backSignType,
      isBack: true
    }
    uni.navigateTo({
      url: `/pages/my/signature?params=${JSON.stringify(params)}`,
    })
  }
  if (index === 1) {
    if (item.taskStatus == 0) {//未完成-提交
      console.log(item)
      let param = {
        id:item.id,
        taskId:item.taskId
      }
      console.log(param)
      submitBackApply(param).then(res => {
        console.log(res)
        if(res.code==200){
          uni.showToast({ title: '提交成功', icon: 'none' })
          getTableList(true)
        }else{
          uni.showToast({ title: '提交失败', icon: 'none' })
        }
      }).catch(error => {
        console.log(error)
      })
    } else if(item.taskStatus == 2) {//已完成-查看
      handleItem(item)
    }
  }
  // 2. 删除
  if (index === 2) {
    console.log(item)
    let param = {
      id:item.id
    }
    console.log(param)
    backApplyRemove(param).then(res => {
      console.log(res)
      if(res.code==200){
        uni.showToast({ title: '删除成功', icon: 'none' })
        getTableList(true)
      }else{
        uni.showToast({ title: '删除失败', icon: 'none' })
      }
    }).catch(error => {
      console.log(error)
    })
  }
  swipeRef.value[itemIndex].closeAll()
}

//获取列表
const getTableList = async (isTap = false) => {
  console.log('queryParams.value查询参数', queryParams.value)
  const res  = await getBackList(queryParams.value)
  console.log('res列表数据', res)
  total.value = res.data.total
  if (isTap) {
    tableList.value = res.data.rows
  } else {
    if (res.data.rows.length == 0) {
      tableList.value = []
    } else {
      tableList.value.push(...res.data.rows)
    }
  }
}

// 滚动触底事件
const onScrollTolower = debounce(() => {
  if (total.value > tableList.value.length) {
    queryParams.value.pageNum++
    getTableList()
  }
})
//切换tab
const changeTab = (index) => {
  active.value = index
  if (index == 1) {
    queryParams.value.appTaskStatus = 0;
  } else if (index == 2) {
    queryParams.value.appTaskStatus = 1;
  }
  queryParams.value.pageNum = 1
  getTableList(true)
}
// 日期 change 事件
const onChangeDate = (val) => {
  const [val_1, val_2] = val
  queryParams.value.startTime = val_1
  queryParams.value.endTime = val_2
}
//日期选择
const maskClick = () => {}

//点击新增
const goAdd = () => {
  uni.navigateTo({ url: `/pages/back/addBack` })
}
//点击详情
const handleItem = (item) => {
  console.log('🚀 ~ handleItem ~ item:', item)
  uni.navigateTo({ url: `/pages/back/detail?id=${item.id}&taskId=${item.taskId}` })
}
// 判断数据是否加载完毕
const finish = computed(() => {
  if (total.value === tableList.value.length) return true
})
onShow(() => {
  tableList.value = []
  total.value = 0
  getTableList(true)
})

// 状态标签样式
const successStyle = {
  color: '#52c41a',
  backgroundColor: 'rgba(82, 196, 26, 0.1)',
  border: '2rpx solid rgba(82, 196, 26, 0.2)',
  fontWeight: '600'
}

const warningStyle = {
  color: '#fa8c16',
  backgroundColor: 'rgba(250, 140, 22, 0.1)',
  border: '2rpx solid rgba(250, 140, 22, 0.2)',
  fontWeight: '600'
}

const primaryStyle = {
  color: '#1890ff',
  backgroundColor: 'rgba(24, 144, 255, 0.1)',
  border: '2rpx solid rgba(24, 144, 255, 0.2)',
  fontWeight: '600'
}

const errorStyle = {
  color: '#f5222d',
  backgroundColor: 'rgba(245, 34, 45, 0.1)',
  border: '2rpx solid rgba(245, 34, 45, 0.2)',
  fontWeight: '600'
}
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  height: 100vh;
  flex-direction: column;
  background-color: #f7f8fa;
  padding: 24rpx;

  // 顶部切换按钮
  .complete-btn {
    display: flex;
    padding: 20rpx 24rpx;
    justify-content: center;
    background: #fff;
    border-radius: 20rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

    .btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 0 60rpx;
      position: relative;
      transition: all 0.3s ease;

      span {
        font-size: 32rpx;
        color: #8c8c8c;
        font-weight: 500;

        &.active {
          color: #3784fb;
          font-weight: 600;

          .second-active & {
            color: #fa8c16;
          }
        }
      }

      .bt-line {
        width: 32rpx;
        height: 6rpx;
        background: #3784fb;
        margin-top: 12rpx;
        border-radius: 6rpx;
        transition: all 0.3s ease;

        .second-active & {
          background: #fa8c16;
        }
      }
    }
  }

  // 搜索表单
  .search-form {
    display: flex;
    align-items: center;
    background: #fff;
    padding: 24rpx;
    border-radius: 20rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

    :deep(.uni-easyinput__content),
    :deep(.uni-date-editor) {
      background-color: #f7f8fa;
      border: 2rpx solid #e8e8e8;
      border-radius: 12rpx;
      height: 80rpx;
      transition: all 0.3s ease;

      &:focus-within {
        border-color: #3784fb;
        box-shadow: 0 0 0 2rpx rgba(55, 132, 251, 0.1);
      }
    }

    :deep(.uni-data-select) {
      .uni-select {
        background-color: #f7f8fa;
        border: 2rpx solid #e8e8e8;
        border-radius: 12rpx;
        height: 80rpx;
        transition: all 0.3s ease;

        &:focus-within {
          border-color: #3784fb;
          box-shadow: 0 0 0 2rpx rgba(55, 132, 251, 0.1);
        }

        .uni-select__input-text {
          line-height: 80rpx;
          padding-left: 24rpx;
        }

        .uni-select__selector {
          border-radius: 12rpx;
          box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);

          .uni-select__selector-item {
            padding: 20rpx 24rpx;

            &.selected {
              color: #3784fb;
              background-color: rgba(55, 132, 251, 0.1);
            }
          }
        }
      }
    }

    :deep(.uni-date) {
      width: 100%;

      .uni-date-x {
        width: 100%;
      }

      .uni-date-editor--x {
        width: 100%;
      }

      .uni-date-range--x {
        width: 100%;

        .uni-date-range--x-input {
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 24rpx;

          .uni-date-range--x-text {
            font-size: 28rpx;
            color: #262626;
          }
        }
      }

      .uni-date-x--border {
        width: 100%;
        border: 2rpx solid #e8e8e8;
        border-radius: 12rpx;
        background-color: #f7f8fa;
        height: 80rpx;
        transition: all 0.3s ease;

        &:focus-within {
          border-color: #3784fb;
          box-shadow: 0 0 0 2rpx rgba(55, 132, 251, 0.1);
        }
      }
    }

    :deep(.uni-date-editor) {
      .uni-date-range {
        display: flex;
        align-items: center;
        width: 100%;

        .uni-date-range--text {
          width: 50%;
          text-align: center;
          color: #333;
        }
      }
    }

    // 搜索按钮
    .search {
      height: 80rpx;
      background: linear-gradient(135deg, #4b8eff 0%, #3784fb 100%);
      text-align: center;
      line-height: 80rpx;
      color: #fff;
      border-radius: 12rpx;
      font-size: 28rpx;
      font-weight: 600;
      box-shadow: 0 6rpx 20rpx rgba(55, 132, 251, 0.2);
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.98);
        opacity: 0.9;
      }
    }

    // 新增按钮
    .addBtn {
      height: 80rpx;
      background: linear-gradient(135deg, #19be6b 0%, #16a75c 100%);
      text-align: center;
      line-height: 80rpx;
      color: #fff;
      border-radius: 12rpx;
      font-size: 28rpx;
      font-weight: 600;
      box-shadow: 0 6rpx 20rpx rgba(25, 190, 107, 0.2);
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.98);
        opacity: 0.9;
      }
    }
  }

  // 列表容器
  .table-list-item {
    margin: 24rpx 0;
    padding: 32rpx;
    background-color: #fff;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.985);
      background-color: #fafbfc;
    }

    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24rpx;

      .code {
        font-size: 32rpx;
        font-weight: 600;
        color: #007aff;
        letter-spacing: 1rpx;
        background: linear-gradient(90deg, #007aff, #4b8eff);
        -webkit-background-clip: text;
        color: transparent;
      }

      .status-tag {
        display: flex;
        align-items: center;
      }

      .cont {
        :deep(.uni-tag) {
          padding: 6rpx 20rpx;
          border-radius: 8rpx;
          font-size: 26rpx;
          font-weight: 600;
          border: none;
          transition: all 0.3s ease;

          &[type='warning'] {
            background-color: rgba(250, 140, 22, 0.1);
            color: #fa8c16;
            border: 2rpx solid rgba(250, 140, 22, 0.2);
          }

          &[type='success'] {
            // 样式将通过 custom-style 控制
          }

          &:active {
            opacity: 0.8;
            transform: scale(0.98);
          }
        }
      }
    }

    .line {
      margin: 24rpx 0;
      height: 2rpx;
      background: linear-gradient(
              90deg,
              rgba(232, 232, 232, 0) 0%,
              rgba(232, 232, 232, 1) 50%,
              rgba(232, 232, 232, 0) 100%
      );
    }

    :deep(.uni-row) {
      margin-bottom: 20rpx;

      .uni-col-7 {
        color: #8c8c8c;
        font-size: 28rpx;
        font-weight: 500;
      }

      .cont {
        display: flex;
        justify-content: flex-end;
        line-height: 1.8;
        color: #262626;
        font-size: 28rpx;
        font-weight: 500;
      }
    }

    // 优化滑动区域样式
    :deep(.uni-swipe_action) {
      border-radius: 20rpx;
      overflow: hidden;

      .uni-swipe_content {
        margin: 0 !important;
        padding: 0;
        background-color: #fff;
      }

      .uni-swipe_button-group {
        height: 100%;

        .uni-swipe_button {
          writing-mode: vertical-rl;
          padding: 0 24rpx;
          font-size: 28rpx !important;
          font-weight: 600;

          // 查看按钮
          &:nth-child(1) {
            background: linear-gradient(to bottom, #3ad980, #34C759) !important;
          }

          // 出库按钮
          &:nth-child(2) {
            background: linear-gradient(to bottom, #3b95ff, #007AFF) !important;
          }

          &:active {
            opacity: 0.85;
          }
        }
      }
    }
  }
}
// 加载提示文字
.loading-text {
  text-align: center;
  font-size: 26rpx;
  color: #8c8c8c;
  padding: 32rpx 0;
  letter-spacing: 1rpx;
}
</style>