<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 type { IListQuery, IinterchangeList } from './interchange_interface'
import ButtonBox from './buttonBox.vue'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import {
  exportInterchangeList,
  getInterChangeList,
  interchangeListBack,
  interchangeListComplete,
  interchangeListDelete,
  interchangeListReturn,
  interchangeListTake,
  interchangeListTerminate,
  interchangeListUrge,
} from '@/api/business/schedule/interchangeList'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'

const { proxy } = getCurrentInstance() as any
const $router = useRouter()

// 是否加急
const isUrgentMap = [
  { label: '全部', value: '0' },
  { label: '是', value: '1' },
  { label: '否', value: '2' },
]

// 样品属性
const sampleAttrMap = [
  { label: '全部', value: '0' },
  { label: '客户样品', value: '1' },
  { label: '自有设备', value: '2' },
]

const currentMenu = ref('taking') // buttonBox菜单选中项

// 查询条件
const listQuery: Ref<IListQuery> = ref({
  sampleNo: '', // 样品编号
  sampleName: '', // 样品名称
  orderCode: '', // 委托书编号
  customerId: '', // 委托方代码
  startTime: '', // 预计送达开始时间
  endTime: '', // 预计送达结束时间
  isUrgent: '', // 是否加急
  sampleAttr: '', // 样品属性
  type: '',
  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: 'evaluationName', align: 'center' },
  { text: '委托书编号', value: 'orderCode', align: 'center' },
  { text: '委托方代码', value: 'customerId', align: 'center' },
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '送检人', value: 'deliverer', align: 'center' },
  { text: '是否加急', value: 'isUrgent', align: 'center', width: '55px', filter: (row: IinterchangeList) => { return row.isUrgent == '1' ? '是' : '否' }, styleFilter: (row: IinterchangeList) => { return row.isUrgent == '1' ? 'color: red' : '' } },
  { text: '样品属性', value: 'sampleAttr', align: 'center' },
  { text: '预计送达时间', value: 'planDeliverTime', 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: 'evaluationName', align: 'center' },
  { text: '委托书编号', value: 'orderCode', align: 'center' },
  { text: '委托方代码', value: 'customerId', align: 'center' },
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '实际送达时间', value: 'deliverTime', align: 'center' },
  { text: '要求检完时间', value: 'requireOverTime', align: 'center' },
  { text: '是否加急', value: 'isUrgent', align: 'center', width: '55px', filter: (row: IinterchangeList) => { return row.isUrgent == '1' ? '是' : '否' }, styleFilter: (row: IinterchangeList) => { return row.isUrgent == '1' ? 'color: red' : '' } },
  { text: '样品属性', value: 'sampleAttr', align: 'center' },
  { text: '当前检定环节', value: 'currentDeliver', align: 'center' },
  { text: '证书出具', value: 'Certifications', align: 'center' },
])

// 表格数据
const list = ref<IinterchangeList[]>([])
// 总数
const total = ref(0)
// 表格加载状态
const loadingTable = ref(false)
// 选中的内容
const checkoutList = ref<string[]>([])
// 数据查询
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.type = currentMenu.value
  // getInterChangeList(listQuery.value).then((response) => {
  //   response.data.rows = [
  //     {
  //       id: 'test',
  //       sampleNo: 'test', // 样品编号
  //       sampleName: 'test', // 样品名称
  //       sampleModel: 'test', // 型号
  //       evaluationName: 'test', // 出厂编号
  //       orderCode: 'test', // 委托书编号
  //       customerId: 'test', // 委托方代码
  //       customerName: 'test', // 委托方名称
  //       deliverer: 'test', // 送检人
  //       isUrgent: 'test', // 是否加急
  //       sampleAttr: 'test', // 样品属性
  //       planDeliverTime: 'test', // 预计送达时间
  //     }]
  //   list.value = response.data.rows.map((item: IinterchangeList) => {
  //     return {
  //       ...item,
  //       Certifications: item.currentCertifications === item.requireCertifications ? item.requireCertifications : (`${item.currentCertifications}/${item.requireCertifications}`),
  //     }
  //   })
  //   total.value = parseInt(response.data.total)
  //   loadingTable.value = false
  // })
  list.value = [
    {
      id: 'test',
      sampleNo: 'test', // 样品编号
      sampleName: 'test', // 样品名称
      sampleModel: 'test', // 型号
      evaluationName: 'test', // 出厂编号
      orderCode: 'test', // 委托书编号
      customerId: 'test', // 委托方代码
      customerName: 'test', // 委托方名称
      deliverer: 'test', // 送检人
      isUrgent: '1', // 是否加急
      sampleAttr: '1', // 样品属性
      planDeliverTime: 'test', // 预计送达时间
      deliverTime: 'test', // 实际送达时间
      requireOverTime: 'test', // 要求检完时间
      currentCertifications: '1', // 已出具证书总数
      requireCertifications: '5', // 应出具证书总数
      currentDeliver: 'test', // 当前检定环节
    }].map((item: IinterchangeList) => {
    return {
      ...item,
      Certifications: item.currentCertifications === item.requireCertifications ? item.requireCertifications : (`${item.currentCertifications}/${item.requireCertifications}`),
      sampleAttr: `${item.sampleAttr}` === '1' ? '客户样品' : '自有设备',
    }
  })
}

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

// 多选发生改变时
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)
}

// 监听buttonBox切换
const changeCurrentButton = (val: string) => {
  currentMenu.value = val
  console.log(currentMenu.value)

  fetchData(true)
}

// 点击扫描收入
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, // 样品名称
      orderCode: listQuery.value.orderCode, // 委托书编号
      customerId: listQuery.value.customerId, // 委托方代码
      startTime: listQuery.value.startTime, // 预计送达开始时间
      endTime: listQuery.value.endTime, // 预计送达结束时间
      isUrgent: listQuery.value.isUrgent, // 是否加急
      sampleAttr: listQuery.value.sampleAttr, // 样品属性
      type: currentMenu.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') { // 收入
        interchangeListTake({ id: row.id, type: currentMenu.value }).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
      else if (type === 'delete') { // 删除
        interchangeListDelete({ id: row.id, type: currentMenu.value }).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
      else if (type === 'complete') { // 完成
        interchangeListComplete({ id: row.id, type: currentMenu.value }).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
      else if (type === 'back') { // 回退
        interchangeListBack({ id: row.id, type: currentMenu.value }).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
      else if (type === 'return') { // 归还
        interchangeListReturn({ id: row.id, type: currentMenu.value }).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
      else if (type === 'urge') { // 催办
        interchangeListUrge({ id: row.id, type: currentMenu.value }).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
      else if (type === 'terminate') { // 终止
        interchangeListTerminate({ id: row.id, type: currentMenu.value }).then((res) => {
          if (res.code === 200) {
            ElMessage.success(`已${title}`)
            fetchData(true)
          }
        })
      }
    })
}

// 打印列表
function printList() {
  // 打印列
  let column = columnsTaking.value
  if (currentMenu.value === 'taking') {
    column = columns.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.id}`)
}

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.orderCode"
          placeholder="委托书编号"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.customerId"
          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"
            value-format="YYYY-MM-DD"
            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.label"
            :value="item.value"
          />
        </el-select>
      </search-item>
      <search-item>
        <el-select v-model="listQuery.sampleAttr" placeholder="样品属性" style="width: 120px;" clearable>
          <el-option
            v-for="item in sampleAttrMap"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/schedule/interchangeList/scanTake') && currentMenu === 'taking'" icon="icon-device" title="扫描收入" type="primary" @click="scanTake" />
        <icon-button v-if="proxy.hasPerm('/schedule/interchangeList/scanOver') && (currentMenu === 'took' || currentMenu === 'overtime') " icon="icon-device" title="扫描结束检定" type="primary" @click="scanOver" />
        <icon-button v-if="proxy.hasPerm('/schedule/interchangeList/scanReturn') && currentMenu === 'returning'" 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 === 'taking' ? columnsTaking : columns" :query="listQuery"
        :list-loading="loadingTable" is-showmulti-select @change="changePage" @multi-select="handleSelectionChange"
      >
        <template #columns>
          <el-table-column label="操作" align="center" fixed="right" width="240">
            <template #default="{ row }">
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/edit') && currentMenu === 'taking'"
                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 === 'taking' || currentMenu === 'took' || currentMenu === 'returning')"
                size="small"
                link
                type="primary"
                @click="scan()"
              >
                标签绑定
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/take') && currentMenu === 'taking'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'take', '收入')"
              >
                收入
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/delete') && currentMenu === 'taking'"
                size="small"
                link
                type="danger"
                @click="handleEdit(row, 'delete', '删除')"
              >
                无需检测
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/complete') && currentMenu === 'took'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'complete', '完成')"
              >
                完成
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/return') && currentMenu === 'returning'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'return', '归还')"
              >
                归还
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/back') && (currentMenu === 'returning' || currentMenu === 'took' || currentMenu === 'returned')"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'back', '回退')"
              >
                回退
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/urge') && currentMenu === 'overtime'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'urge', '催办')"
              >
                催办
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/schedule/interchangeList/terminate') && (currentMenu === 'took' || currentMenu === 'overtime')"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'terminate', '终止')"
              >
                终止
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
    <button-box @changeCurrentButton="changeCurrentButton" />
  </app-container>
</template>

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