<!-- 设备收发列表 -->
<script lang="ts" setup name="InterchangeList">
import type { Ref } from 'vue'
import { getCurrentInstance, ref } from 'vue'
import type { DateModelType } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import teminateDialog from './dialog/teminateDialog.vue'
import type { IList, IListQuery } from './sendReceive-interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import scanSampleDialog from '@/components/ScanSampleDialog/index.vue'
import { exportFile } from '@/utils/exportUtils'
import { getDictByCode } from '@/api/system/dict'
import type { IMenu } from '@/components/buttonBox/buttonBox'
import buttonBox from '@/components/buttonBox/buttonBox.vue'
// import { tagBinding } from '@/api/reader'
import {
  exportInterchangeList,
  getInterChangeList,
  interchangeListTerminate,
  interchangeListUrge,
  interchangeStatusChange,
} from '@/api/business/manager/sendReceive'
import type { dictType } from '@/global'

const { proxy } = getCurrentInstance() as any
const $router = useRouter()
const buttonBoxActive = 'businessSendReceive' // 存储在sessionstorage里面的字段名，用于记录右上角buttonbox点击状态
const menu = ref<IMenu[]>([]) // 右上角菜单
const currentMenu = ref('') // 选中的按钮
const active = ref('') // 选中的按钮的code
const terminateRef = ref() // 确认终止dialog
const isBinding = ref(false) // 是否是标签绑定
const scanSampleRef = ref() // 标签绑定弹窗ref
const selectRow = ref() // 标签绑定选择的行数据
const scanType = ref('take') // take扫描收入 complete 扫描结束检定 return扫描归还
const dialogTitle = ref('标签绑定') // 扫描对话框标题
// 查询条件
const listQuery: Ref<IListQuery> = ref({
  sampleNo: '', // 统一编号
  sampleName: '', // 受检设备名称
  orderNo: '', // 任务单编号
  customerName: '', // 委托方
  planDeliverStartTime: '', // 预计送达时间(开始)
  planDeliverEndTime: '', // 预计送达时间(结束)
  sampleStatus: '', // 样品状态
  offset: 1,
  limit: 20,
})
const timeRange = ref<[DateModelType, DateModelType]>(['', ''])
// 表头待收入
const columns = ref<TableColumn[]>([
  { text: '统一编号', value: 'sampleNo', width: '160', align: 'center' },
  { text: '受检设备名称', value: 'sampleName', align: 'center' },
  { text: '任务单编号', value: 'orderNo', align: 'center', width: '160' },
  { text: '委托方', value: 'customerName', align: 'center' },
  { text: '送检人', value: 'deliverer', align: 'center' },
  { text: '预计送达时间', value: 'planDeliverTime', width: '180', align: 'center' },
  { text: '是否加急', value: 'isUrgentName', align: 'center', width: '90', styleFilter: (row: IList) => { return row.isUrgent == 1 ? 'color: red' : '' } },
])
const list = ref<IList[]>([]) // 表格数据
const total = ref(0) // 总数
const loadingTable = ref(false) // 表格加载状态
const checkoutList = ref<IList[]>([]) // 选中的内容
const checkoutIdList = ref<IList[]>([]) // 选中的内容id集合
const operateWidth = ref('160')
// -------------------------------------------字典------------------------------------------
const isUrgentMap = ref({}) as any // 是否加急{1: 是}
const sampleStatusMap = ref<dictType[]>([]) // 样品状态

// 获取字典值
async function getDict() {
  loadingTable.value = true
  // 是否加急
  getDictByCode('isUrgent').then((response) => {
    response.data.forEach((item: any) => {
      isUrgentMap.value[`${item.value}`] = item.name
    })
  })

  // 样品状态
  const res = await getDictByCode('sampleStatus')
  sampleStatusMap.value = res.data.map((item: dictType) => {
    return {
      ...item,
      value: parseInt(item.value as string), // 后端需要int型，在此转换
    }
  })
  // 制作右上角的菜单
  sampleStatusMap.value.forEach((item: dictType) => {
    if (item.name === '待收入' || item.name === '待归还'
      || item.name === '已归还' || item.name === '已超期') {
      menu.value.push({
        name: item.name,
        id: `${item.value}`,
      })
    }
  })
  menu.value.splice(1, 0, {
    name: '已收入',
    id: '2', // 后端规定已收入传2
  })
}
// ---------------------------------------列表数据---------------------------------------------------

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  listQuery.value.sampleStatus = active.value
  getInterChangeList(listQuery.value).then((response) => {
    list.value = response.data.rows.map((item: IList) => {
      return {
        ...item,
        isUrgentName: item.isUrgent == 1 ? '是' : '否',
      }
    })
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}

// 点击搜索
const searchList = () => {
  fetchData(true)
}

// 点击重置
const clearList = () => {
  listQuery.value = {
    sampleNo: '', // 统一编号
    sampleName: '', // 受检设备名称
    orderNo: '', // 任务单编号
    customerName: '', // 委托方
    planDeliverStartTime: '', // 预计送达时间(开始)
    planDeliverEndTime: '', // 预计送达时间(结束)
    sampleStatus: '', // 样品状态
    offset: 1,
    limit: 20,
  }
  timeRange.value = ['', '']
  fetchData(true)
}

// 多选发生改变时
function handleSelectionChange(e: any) {
  checkoutIdList.value = e.map((item: { id: string }) => item.id)
  checkoutList.value = e
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    listQuery.value.limit = val.size
  }
  if (val && val.page) {
    listQuery.value.offset = val.page
  }
  fetchData(true)
}

// 按钮切换
const currentButton = (val: string) => {
  active.value = val
  const currentMenuItem = menu.value.find(item => item.id === val)
  currentMenu.value = currentMenuItem!.name
  window.sessionStorage.setItem(buttonBoxActive, val)
  clearList()
}

// --------------------------------------扫描-------------------------------------------

// -----------------------------------------操作------------------------------------------
/**
 *
 * @param row 行数据
 * @param type 操作类型
 * @param title 操作类型标题
 */
const handleEdit = (row: any, type: string, title: string) => {
  let params = [] as any
  if (Array.isArray(row)) { // 是数组
    params = row.map((item: any) => {
      return {
        orderId: item.orderId, // 委托书id
        reason: '', // 操作原因（终止操作必填，其他无需填写）
        sampleId: item.sampleId, // 样品id
        status: '', // 状态变更(无需检测状态7,前进状态2、5、6,回退状态1,2,5)
      }
    })
  }
  else { // 不是数组
    params = row
  }

  ElMessageBox.confirm(
    `确认${title}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      if (type === 'take') { // 收入
        params.forEach((item: any) => {
          item.status = '2'
        })
        interchangeStatusChange(params).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
      else if (type === 'delete') { // 无需检测
        params.forEach((item: any) => {
          item.status = '7'
        })
        interchangeStatusChange(params).then((res) => {
          if (res.code === 200) {
            ElMessage.success('操作成功')
            fetchData(true)
          }
        })
      }
      else if (type === 'complete') { // 完成
        params.forEach((item: any) => {
          item.status = '5'
        })
        interchangeListTerminate(params).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
      else if (type === 'back') { // 回退
        if (currentMenu.value === '已收入') {
          params.forEach((item: any) => {
            item.status = '1'
          })
        }
        if (currentMenu.value === '待归还') {
          params.forEach((item: any) => {
            item.status = '2'
          })
        }
        if (currentMenu.value === '已归还') {
          params.forEach((item: any) => {
            item.status = '5'
          })
        }
        interchangeStatusChange(params).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
      else if (type === 'return') { // 归还
        params.forEach((item: any) => {
          item.status = '6'
        })
        interchangeStatusChange(params).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
      else if (type === 'urge') { // 催办
        interchangeListUrge({ orderId: row.orderId, reason: '', sampleId: row.sampleId, status: '' }).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
      else if (type === 'terminate') { // 终止
        terminateRef.value.initDialog(row)
      }
    })
}

// 点击详情
const goEdit = (row: IList, pageType: 'edit' | 'detail') => {
  $router.push({
    path: `/sendReceive/${pageType}/${row.id}`,
    query: {
      orderId: row.orderId, // 任务单id
      equipmentId: row.sampleId, // 设备id\样品id
    },
  })
}
// -------------------------------------------表格右上侧按钮------------------------------------
// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      sampleNo: listQuery.value.sampleNo, // 统一编号
      sampleName: listQuery.value.sampleName, // 受检设备名称
      orderNo: listQuery.value.orderNo, // 任务单编号
      customerName: listQuery.value.customerName, // 委托方
      planDeliverStartTime: listQuery.value.planDeliverStartTime, // 预计送达时间(开始)
      planDeliverEndTime: listQuery.value.planDeliverEndTime, // 预计送达时间(结束)
      sampleStatus: listQuery.value.sampleStatus, // 样品状态
      offset: 1,
      limit: 20,
      ids: checkoutIdList.value,
    }
    exportInterchangeList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '设备收发管理列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}

// 点击批量收入
const batchReceive = () => {
  handleEdit(checkoutList.value, 'take', '收入')
}
// 点击批量检完
const batchFinish = () => {
  handleEdit(checkoutList.value, 'complete', '完成')
}
// 点击批量归还
const batchReturn = () => {
  handleEdit(checkoutList.value, 'return', '归还')
}

// =========================扫描===============================
// 点击扫描
const scan = () => {

}
// 点击扫描收入
const scanTake = () => {
  ElMessage.info('敬请期待')
  // isBinding.value = false
  // scanType.value = 'take'
  // dialogTitle.value = '扫描收入'
  // scanSampleRef.value.initDialog(isBinding.value, '1', '1')
}
// 点击扫描结束检定
const scanFinish = () => {
  ElMessage.info('敬请期待')
  // isBinding.value = false
  // scanType.value = 'complete'
  // dialogTitle.value = '扫描结束检定'
  // scanSampleRef.value.initDialog(isBinding.value, '1', '2')
}

// 点击扫描归还
const scanReturn = () => {
  ElMessage.info('敬请期待')
  // isBinding.value = false
  // scanType.value = 'return'
  // dialogTitle.value = '扫描归还'
  // scanSampleRef.value.initDialog(isBinding.value, '1', '3')
}

// 扫描结束
const scanOver = (value: any) => {
  if (isBinding.value) { // 标签绑定
    const label = value.labelBind
    // tagBinding({ label, sampleId: selectRow.value.sampleId }).then((res) => {
    //   ElMessage.success(' 绑定成功')
    // })
  }
  else { // 扫描收入或扫描捡完
    console.log(value)
    if (!value.length) { return }
    const getData = value.map((item: { sampleId: string; orderId: string }) => {
      return {
        ...item,
        sampleId: item.sampleId,
        orderId: item.orderId,
        reason: '',
      }
    })

    if (scanType.value === 'take') { // 扫描收入
      handleEdit(getData, 'take', '收入')
    }
    else if (scanType.value === 'complete') { // 扫描结束检定
      handleEdit(getData, 'complete', '完成')
    }
    else if (scanType.value === 'return') { // 扫描归还
      handleEdit(getData, 'return', '归还')
    }
  }
  scanSampleRef.value.closeDialog()
}

// ----------------------------------钩子------------------------------------------------
// 时间变更
watch(timeRange, (val) => {
  if (val) {
    listQuery.value.planDeliverStartTime = `${val[0]}`
    listQuery.value.planDeliverEndTime = `${val[1]}`
  }
  else {
    listQuery.value.planDeliverStartTime = ''
    listQuery.value.planDeliverEndTime = ''
  }
})
onMounted(async () => {
  await getDict() // 字典
  if (window.sessionStorage.getItem(buttonBoxActive)) {
    active.value = window.sessionStorage.getItem(buttonBoxActive)!
  }
  else {
    active.value = '1' as string // 待收入
  }
  fetchData(true) // 列表数据
})
</script>

<template>
  <app-container>
    <search-area :need-clear="true" @search="searchList" @clear="clearList">
      <search-item>
        <el-input
          v-model.trim="listQuery.sampleNo"
          placeholder="统一编号"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.sampleName"
          placeholder="受检设备名称"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.orderNo"
          placeholder="任务单编号"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.customerName"
          placeholder="委托方"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <search-item>
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            range-separator="至"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="预计送达时间(开始)"
            end-placeholder="预计送达时间(结束)"
          />
        </search-item>
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="currentMenu === '待收入'" icon="icon-batch" title="批量收入" type="primary" @click="batchReceive" />
        <icon-button v-if="currentMenu === '已收入'" icon="icon-batch" title="批量检完" type="primary" @click="batchFinish" />
        <icon-button v-if="currentMenu === '待归还'" icon="icon-batch" title="批量归还" type="primary" @click="batchReturn" />
        <icon-button v-if="currentMenu === '待收入'" icon="icon-scan" title="扫描收入" type="primary" @click="scanTake" />
        <icon-button v-if="currentMenu === '已收入'" icon="icon-scan" title="扫描结束检定" type="primary" @click="scanFinish" />
        <icon-button v-if="currentMenu === '待归还'" icon="icon-scan" title="扫描归还" type="primary" @click="scanReturn" />
        <!-- <icon-button v-if="currentMenu === '待收入' || currentMenu === '已收入' || currentMenu === '待归还'" icon="icon-scan" title="扫描" type="primary" @click="scan" /> -->
        <icon-button icon="icon-export" title="导出" type="primary" @click="exportAll" />
      </template>
      <normal-table
        :data="list" :total="total" :columns="columns" :query="listQuery"
        :list-loading="loadingTable" is-showmulti-select @change="changePage" @multi-select="handleSelectionChange"
      >
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <template #columns>
          <el-table-column label="操作" align="center" fixed="right" :width="operateWidth">
            <template #default="{ row }">
              <el-button
                size="small"
                link
                type="primary"
                @click="goEdit(row, 'detail')"
              >
                详情
              </el-button>
              <el-button
                v-if="currentMenu === '待收入'"
                size="small"
                link
                type="primary"
                @click="handleEdit([row], 'take', '收入')"
              >
                收入
              </el-button>
              <el-button
                v-if="currentMenu === '待收入'"
                size="small"
                link
                type="danger"
                @click="handleEdit([row], 'delete', '无需检测')"
              >
                无需检测
              </el-button>
              <el-button
                v-if="currentMenu === '已收入'"
                size="small"
                link
                type="primary"
                @click="handleEdit([row], 'complete', '完成')"
              >
                完成
              </el-button>
              <el-button
                v-if="currentMenu === '待归还'"
                size="small"
                link
                type="primary"
                @click="handleEdit([row], 'return', '归还')"
              >
                归还
              </el-button>
              <el-button
                v-if="currentMenu === '待归还' || currentMenu === '已收入' || currentMenu === '已归还'"
                size="small"
                link
                type="primary"
                @click="handleEdit([row], 'back', '回退')"
              >
                回退
              </el-button>
              <el-button
                v-if="currentMenu === '已超期'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'urge', '催办')"
              >
                催办
              </el-button>
              <el-button
                v-if="currentMenu === '已收入' || currentMenu === '已超期'"
                size="small"
                link
                type="danger"
                @click="handleEdit(row, 'terminate', '终止')"
              >
                终止
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
    <button-box :active="active" :menu="menu" @change-current-button="currentButton" />
    <!-- 终止弹窗 -->
    <teminate-dialog ref="terminateRef" @on-success="fetchData(true)" />
    <scan-sample-dialog ref="scanSampleRef" :title="dialogTitle" @confirm="scanOver" />
  </app-container>
</template>

<style lang="scss" scoped>
.short-input {
  width: 160px;
}
</style>
