<!-- 设备收发列表 -->
<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 '../components/terminateDialog.vue'
import type { IListQuery, IinterchangeList, dictType } from './interchange_interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import {
  exportInterchangeList,
  getInterChangeList,
  interchangeListTerminate,
  interchangeListUrge,
  interchangeStatusChange,
} from '@/api/business/schedule/interchangeList'
import { printJSON } from '@/utils/printUtils'
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'

const { proxy } = getCurrentInstance() as any
const $router = useRouter()
const menu = ref<IMenu[]>([]) // 右上角菜单
const currentMenu = ref('') // 选中的按钮
const active = ref('') // 选中的按钮的code
const terminateRef = ref() // 确认终止dialog

// 查询条件
const listQuery: Ref<IListQuery> = ref({
  sampleNo: '', // 样品编号
  sampleName: '', // 样品名称
  orderNo: '', // 委托书编号
  customerNo: '', // 委托方代码
  startTime: '', // 预计送达开始时间
  endTime: '', // 预计送达结束时间
  isUrgent: '', // 是否加急
  sampleBelong: '', // 样品属性
  sampleStatus: '', // 样品状态
  offset: 1,
  limit: 20,
})
const timeRange = ref<[DateModelType, DateModelType]>(['', ''])
// 表头待收入
const columnsTaking = ref<TableColumn[]>([
  { text: '样品编号', value: 'sampleNo', width: '160', align: 'center' },
  { text: '样品名称', value: 'sampleName', width: '120', align: 'center' },
  { text: '型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  { text: '委托书编号', value: 'orderCode', align: 'center' },
  { text: '委托方代码', value: 'customerNo', width: '160', align: 'center' },
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '送检人', value: 'deliverer', align: 'center' },
  { text: '是否加急', value: 'isUrgentName', align: 'center', width: '55px', styleFilter: (row: IinterchangeList) => { return row.isUrgent == '1' ? 'color: red' : '' } },
  { text: '样品属性', value: 'sampleBelong', align: 'center', width: '90px' },
  { text: '预计送达时间', value: 'planDeliverTime', width: '180', align: 'center' },
])
const columns = ref<TableColumn[]>([
  { text: '样品编号', value: 'sampleNo', width: '160', align: 'center' },
  { text: '样品名称', value: 'sampleName', width: '120', align: 'center' },
  { text: '型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  { text: '委托书编号', value: 'orderCode', align: 'center' },
  { text: '委托方代码', value: 'customerNo', width: '160', align: 'center' },
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '实际送达时间', value: 'realDeliverTime', align: 'center' },
  { text: '要求检完时间', value: 'requireOverTime', align: 'center' },
  { text: '是否加急', value: 'isUrgentName', align: 'center', width: '55px', styleFilter: (row: IinterchangeList) => { return row.isUrgent == '1' ? 'color: red' : '' } },
  { text: '样品属性', value: 'sampleBelong', align: 'center', width: '90px' },
  { text: '当前检定环节', value: 'currentSegment', align: 'center' },
  { text: '证书出具', value: 'Certifications', align: 'center' },
])

// 表格数据
const list = ref<IinterchangeList[]>([])
// 总数
const total = ref(0)
// 表格加载状态
const loadingTable = ref(false)
// 选中的内容
const checkoutList = ref<string[]>([])
const isUrgentMap = ref<dictType[]>([]) // 是否加急
const sampleAttrMap = ref<dictType[]>([]) // 样品属性
const sampleStatusMap = ref<dictType[]>([]) // 样品状态

// 获取字典值
async function getDict() {
  // 是否加急
  getDictByCode('isUrgent').then((response) => {
    isUrgentMap.value = response.data.map((item: dictType) => {
      return {
        ...item,
        value: item.value,
      }
    })
    // 在已有的字典的基础上增加一个全部0进去
    // isUrgentMap.value.unshift({
    //   id: '',
    //   name: '全部',
    //   value: '2', // 是否加急全部后端定为2
    // })
  })
  // 样品属性
  getDictByCode('sampleBelong').then((response) => {
    sampleAttrMap.value = response.data.map((item: dictType) => {
      return {
        ...item,
        value: item.value, // 后端需要int型，在此转换
      }
    })
    // 在已有的字典的基础上增加一个全部进去
    // sampleAttrMap.value.unshift({
    //   id: '',
    //   name: '全部',
    //   value: '2',
    // })
  })
  // 样品状态
  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
  })
}
// 时间变更
watch(timeRange, (val) => {
  if (val) {
    listQuery.value.startTime = `${val[0]}`
    listQuery.value.endTime = `${val[1]}`
  }
  else {
    listQuery.value.startTime = ''
    listQuery.value.endTime = ''
  }
})
// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  // listQuery.value.startTime = timeRange.value[0] as string || ''
  // listQuery.value.endTime = timeRange.value[1] as string || ''
  listQuery.value.sampleStatus = active.value
  getInterChangeList(listQuery.value).then((response) => {
    list.value = response.data.rows.map((item: IinterchangeList) => {
      return {
        ...item,
        Certifications: `${item.alreadyCertifications}/${item.requireCertifications}`,
        sampleBelong: `${item.sampleBelong}` === '1' ? '自有设备' : '客户样品',
        isUrgentName: item.isUrgent == 1 ? '是' : '否',
      }
    })
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}

// 点击搜索
const searchList = () => {
  fetchData(true)
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    sampleNo: '', // 样品编号
    sampleName: '', // 样品名称
    orderNo: '', // 委托书编号
    customerNo: '', // 委托方代码
    startTime: '', // 预计送达开始时间
    endTime: '', // 预计送达结束时间
    isUrgent: '', // 是否加急
    sampleBelong: '', // 样品属性
    sampleStatus: '', // 样品状态
    offset: 1,
    limit: 20,
  }
  timeRange.value = ['', '']
  fetchData(true)
}

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

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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 changeCurrentButton = (val: string) => {
  active.value = val
  const currentMenuItem = menu.value.find(item => item.id === val)
  if (val === '2') {
    currentMenu.value = '已收入'
  }
  else {
    currentMenu.value = currentMenuItem!.name
  }
  window.sessionStorage.setItem('interchangeActive', val)
  clearList()
}

// 点击扫描收入
const scanTake = () => {}
// 点击扫描结束检定
const scanOver = () => {}
// 点击扫描归还
const scanReturn = () => {}
// 点击标签绑定
const scan = () => {}

// 导出
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, // 委托书编号
      customerNo: listQuery.value.customerNo, // 委托方代码
      startTime: listQuery.value.startTime, // 预计送达开始时间
      endTime: listQuery.value.endTime, // 预计送达结束时间
      isUrgent: listQuery.value.isUrgent, // 是否加急
      sampleBelong: listQuery.value.sampleBelong, // 样品属性
      sampleStatus: active.value, // 样品状态
      ids: checkoutList.value,
    }
    exportInterchangeList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '设备收发列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}

// 操作
const handleEdit = (row: IinterchangeList, type: string, title: string) => {
  ElMessageBox.confirm(
    `确认${title}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      if (type === 'take') { // 收入
        interchangeStatusChange({ orderId: row.orderId, reason: '', sampleId: row.sampleId, status: '2' }).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
      else if (type === 'delete') { // 无需检测
        interchangeStatusChange({ orderId: row.orderId, reason: '', sampleId: row.sampleId, status: '7' }).then((res) => {
          if (res.code === 200) {
            ElMessage.success('操作成功')
            fetchData(true)
          }
        })
      }
      else if (type === 'complete') { // 完成
        interchangeListTerminate({ orderId: row.orderId, reason: '', sampleId: row.sampleId, status: '5' }).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
      else if (type === 'back') { // 回退
        let status = ''
        if (currentMenu.value === '已收入') {
          status = '1'
        }
        if (currentMenu.value === '待归还') {
          status = '2'
        }
        if (currentMenu.value === '已归还') {
          status = '5'
        }
        interchangeStatusChange({ orderId: row.orderId, reason: '', sampleId: row.sampleId, status }).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
      else if (type === 'return') { // 归还
        interchangeStatusChange({ orderId: row.orderId, reason: '', sampleId: row.sampleId, status: '6' }).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)
      }
    })
}

// 打印列表
function printList() {
  // 打印列
  let column = columns.value
  if (currentMenu.value === '待收入') {
    column = columnsTaking.value
  }
  const properties = column.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (checkoutList.value.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, '设备收发列表')
  }
  else if (checkoutList.value.length > 0) {
    const printList = list.value.filter((item: IinterchangeList) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '设备收发列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

// 点击编辑或详情
const goEdit = (row: IinterchangeList, pageType: 'edit' | 'detail') => {
  $router.push(`/schedule/interchange/${pageType}/${row.sampleId}`)
}

// 点击生成设备交接单
const createInterchangeReceipt = () => {
  $router.push('/schedule/receipt/add')
}

onMounted(async () => {
  await getDict() // 字典
  if (window.sessionStorage.getItem('interchangeActive')) {
    active.value = window.sessionStorage.getItem('interchangeActive')!
  }
  else {
    active.value = '1' // 待收入
  }
  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.customerNo"
          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-item>
        <el-select v-model="listQuery.isUrgent" placeholder="是否加急" style="width: 120px;" clearable>
          <el-option
            v-for="item in isUrgentMap"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
      <search-item>
        <el-select v-model="listQuery.sampleBelong" placeholder="样品属性" style="width: 120px;" clearable>
          <el-option
            v-for="item in sampleAttrMap"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="currentMenu === '已收入'" icon="icon-create" title="生成设备交接单" type="primary" @click="createInterchangeReceipt" />
        <icon-button v-if="proxy.hasPerm('/schedule/interchangeList/scanTake') && currentMenu === '待收入'" icon="icon-device" title="扫描收入" type="primary" @click="scanTake" />
        <icon-button v-if="proxy.hasPerm('/schedule/interchangeList/scanOver') && (currentMenu === '已收入' || currentMenu === '已超期') " icon="icon-device" title="扫描结束检定" type="primary" @click="scanOver" />
        <icon-button v-if="proxy.hasPerm('/schedule/interchangeList/scanReturn') && currentMenu === '待归还'" icon="icon-device" title="扫描归还" type="primary" @click="scanReturn" />
        <icon-button v-if="proxy.hasPerm('/sample/list/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/sample/list/print')" icon="icon-print" title="打印" type="primary" @click="printList" />
      </template>
      <normal-table
        :data="list" :total="total" :columns="currentMenu === '待收入' ? columnsTaking : 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="currentMenu === '待收入' ? 270 : (currentMenu === '已收入' || currentMenu === '待归还') ? 210
              : (currentMenu === '已归还' || currentMenu === '已超期') ? 130 : 270"
          >
            <template #default="{ row }">
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/edit') && currentMenu === '待收入'"
                size="small"
                type="primary"
                link
                @click="goEdit(row, 'edit')"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                link
                type="primary"
                @click="goEdit(row, 'detail')"
              >
                详情
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/tagBinding') && (currentMenu === '待收入' || currentMenu === '已收入' || currentMenu === '待归还')"
                size="small"
                link
                type="primary"
                @click="scan()"
              >
                标签绑定
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/take') && currentMenu === '待收入'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'take', '收入')"
              >
                收入
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/delete') && currentMenu === '待收入'"
                size="small"
                link
                type="danger"
                @click="handleEdit(row, 'delete', '无需检测')"
              >
                无需检测
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/complete') && currentMenu === '已收入'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'complete', '完成')"
              >
                完成
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/return') && currentMenu === '待归还'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'return', '归还')"
              >
                归还
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/back') && (currentMenu === '待归还' || currentMenu === '已收入' || currentMenu === '已归还')"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'back', '回退')"
              >
                回退
              </el-button>
              <!-- isSelfMeasure: true自检，false外包，外包不允许催办 -->
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/urge') && currentMenu === '已超期' && row.isSelfMeasure"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'urge', '催办')"
              >
                催办
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/terminate') && currentMenu !== '待归还' && 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" @changeCurrentButton="changeCurrentButton" />
    <!-- 终止弹窗 -->
    <teminate-dialog ref="terminateRef" @on-success="fetchData(true)" />
  </app-container>
</template>

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