<template>
  <view>
    <navbar-back :autoBack="false" title="样品分析-收样" @leftClick="customBack"></navbar-back>

    <u-row gutter="16">
      <u-col span="4">
        <view class="content-title-name">
          <text>任务列表</text>
          <up-badge v-if="taskList.length > 0" class="ml5" :value="taskList.length" type="warning"></up-badge>
        </view>
        <u-gap height="5" bg-color="#0055A2"></u-gap>
        <scroll-view
          style="height: 75vh"
          scroll-y
          scroll-with-animation
          class="content-main-left"
          :scroll-top="scrollTop"
        >
          <TaskItem
            v-for="(task, index) in taskList"
            :key="index"
            :task="task"
            :seq="index + 1"
            :active="current === index"
            @click="switchTask(index)"
          />
        </scroll-view>
      </u-col>
      <u-col span="8">
        <view class="content-title-name">
          <text>样品列表</text>
        </view>
        <u-gap height="5" bg-color="#0055A2"></u-gap>
        <view>
          <scroll-view scroll-y scroll-with-animation style="height: calc(75vh - 60px)">
            <block v-for="(sample, index) in sampleList" :key="index">
              <view sclass="p5 fs16">
                <u-row>
                  <u-col span="3" class="text-center">
                    <u-row>
                      <u-col span="6" style="text-align: center">
                        <u-checkbox
                          v-model="sample.checked"
                          v-if="sample.sampleProcessNo === currentNode"
                          @change="selectSample(sample)"
                        ></u-checkbox>
                      </u-col>
                      <u-col span="6" style="text-align: center">
                        <text>【{{ sample.sort }}】</text>
                      </u-col>
                    </u-row>
                  </u-col>
                  <u-col span="9" class="sample_desc">
                    <view>
                      <view
                        ><text class="pl10">{{ sample.sampleCode }}</text></view
                      >
                      <view>
                        <text class="pl10">
                          {{ getDataSourceTypeShow(sample.dataSourceType) }}{{ sample.sampleName }}
                        </text>
                      </view>
                    </view>
                    <view class="sample_desc_warn" v-if="sample.sampleProcessNo !== currentNode">
                      当前节点：{{ getProcessNameShow(sample.sampleProcessNo) }}
                    </view>
                  </u-col>
                </u-row>
                <u-line class="p5" color="#bbb" />
              </view>
            </block>
          </scroll-view>

          <view class="content-main-right-operation">
            <u-row>
              <u-col span="8"></u-col>
              <u-col span="4">
                <u-button class="btn-operation" :disabled="taskList.length <= 0" type="success" @click="confirmReceipt">
                  确认收样
                </u-button>
              </u-col>
            </u-row>
          </view>
        </view>
      </u-col>
    </u-row>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import nx from '@/nx'
import { onLoad, onBackPress } from '@dcloudio/uni-app'
import TaskItem from './components/task-item.vue'
import { getDataSourceTypeShow } from '../common'

// 响应式数据
const currentNode = ref('F30')
const scrollTop = ref(0)
const current = ref(0)
const taskList = ref([
  { id: 1, taskNo: 'TASK-1', taskName: '任务1', taskOperTime: '2022-03-01 10:00:00' },
  { id: 1, taskNo: 'TASK-1', taskName: '任务1', taskOperTime: '2022-03-01 10:00:00' },
  { id: 1, taskNo: 'TASK-1', taskName: '任务1', taskOperTime: '2022-03-01 10:00:00' },
  { id: 1, taskNo: 'TASK-1', taskName: '任务1', taskOperTime: '2022-03-01 10:00:00' },
  { id: 1, taskNo: 'TASK-1', taskName: '任务1', taskOperTime: '2022-03-01 10:00:00' },
  { id: 1, taskNo: 'TASK-1', taskName: '任务1', taskOperTime: '2022-03-01 10:00:00' },
  { id: 1, taskNo: 'TASK-1', taskName: '任务1', taskOperTime: '2022-03-01 10:00:00' },
  { id: 1, taskNo: 'TASK-1', taskName: '任务1', taskOperTime: '2022-03-01 10:00:00' },
  { id: 1, taskNo: 'TASK-1', taskName: '任务1', taskOperTime: '2022-03-01 10:00:00' }
])
const sampleList = ref([
  { id: 1, sampleCode: 'SAMPLE-1', sampleName: '样品1', sort: 1, checked: false, sampleProcessNo: 'F30' }
])
const dicSampleProcessCodeList = ref([])

// 计算属性
const userInfo = computed(() => nx.$store('user').userInfo)

// 方法
const customBack = () => {
  uni.reLaunch({ url: '/pages/analysis/index/index' })
}

const selectSample = sample => {
  sample.checked = !sample.checked
}

const confirmReceipt = () => {
  const errNodeList = sampleList.value.filter(item => item.sampleProcessNo !== currentNode.value)
  if (errNodeList.length > 0) {
    uni.showToast({
      title: '存在异常节点，联系管理员处理！',
      icon: 'none',
      duration: 3000
    })
    return
  }

  const checkedSampleList = sampleList.value.filter(item => item.checked)
  if (checkedSampleList.length !== sampleList.value.length) {
    uni.showToast({ title: '样品未全部勾选，请检查！', icon: 'none' })
    return
  }

  uni.showModal({
    title: '提示',
    content: '确认收样？',
    cancelColor: '#0055A2',
    confirmColor: '#0055A2',
    success: res => {
      if (res.cancel) return

      const sampleIdList = checkedSampleList.map(item => item.busSubCsampleId)
      const data = {
        busAssayTaskId: taskList.value[current.value]?.id,
        sampleSourceType: 2,
        sampleProcessNo: currentNode.value,
        isGenSampleHandover: false,
        sampleIdList
      }

      nx.$api.assayTask
        .execReceiveSample(data)
        .then(() => {
          getAssayTask()
        })
        .catch(err => {
          console.error('收样失败:', err)
        })
    }
  })
}

const switchTask = index => {
  if (index === current.value) return
  current.value = index

  const task = taskList.value[index]
  if (!task) return

  getAssayTaskDetail(task.taskNo)
}

const getAssayTask = () => {
  const param = {
    finishStatus: 'waiting_receive',
    assayOper: userInfo.value.nickname
  }

  nx.$api.auncel
    .getAssayTaskList(param)
    .then(res => {
      taskList.value = res || []
      if (taskList.value.length > 0) {
        current.value = 0
        getAssayTaskDetail(taskList.value[0].taskNo)
      } else {
        sampleList.value = []
      }
    })
    .catch(err => {
      console.error('获取任务列表失败:', err)
      sampleList.value = []
    })
}

const getAssayTaskDetail = taskNo => {
  const param = {
    taskNo,
    waiting_receive: '1'
  }

  nx.$api.assayTask
    .getAssayTaskDetailListByTaskNo(param)
    .then(res => {
      sampleList.value = (res.result || []).map(item => ({ ...item, checked: false }))
    })
    .catch(err => {
      console.error('获取任务详情失败:', err)
      sampleList.value = []
    })
}

const getDicSampleProcessCodeList = () => {
  nx.$api.assayTask.queryQmsDicSampleProcessCodeList().then(res => {
    dicSampleProcessCodeList.value = res.records || []
  })
}

const getProcessNameShow = val => {
  const item = dicSampleProcessCodeList.value.find(i => i.processCode === val)
  return item ? item.processName : val
}

// 生命周期
onLoad(() => {
  getDicSampleProcessCodeList()
  // getAssayTask()
})

onBackPress(() => {
  customBack()
  return true
})
</script>

<style lang="scss" scoped>
.content-title-name {
  height: 50px;
  box-sizing: border-box;
  font-size: 20px;
  font-weight: 300;
  padding: 10px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.content-main-left {
  background-color: #f6f6f6;
}

.content-main-right-operation {
  height: 50px;
  padding-top: 10px;
  padding-right: 10px;
}

.btn-operation {
  font-size: 18px;
}

.sample_desc {
  width: 100%;
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between !important;
  padding-right: 15px !important;
}

.sample_desc_warn {
  color: red;
}
</style>
