<script lang="ts" setup name="CustomerList">
import { getCurrentInstance, ref } from 'vue'
import type { Ref } from 'vue'
import type { DateModelType } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { Watch } from '@element-plus/icons-vue'
import RollbackDialog from './../components/rollbackDialog.vue'
import addDeviceCom from './components/addDevice.vue'
import sendBackDialog from './../components/sendBackDialog.vue'
import type { ILabQuery, ITaskList, ITaskQuery } from '@/views/business/schedule/task/task-interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import { getDictByCode } from '@/api/system/dict'
import { claimTasks, getMyMeasureList, getTaskDetail, myExecutiveDone, myExecutiveReceive } from '@/api/business/schedule/task'
import type { dictType } from '@/global'
import { keepSearchParams, renewSearchParams } from '@/utils/keepQuery'
import {
  getReportDetail,
} from '@/api/business/lab/report'
import type { IMenu } from '@/components/buttonBox/buttonBox'
const { proxy } = getCurrentInstance() as any
const $router = useRouter()
// 右上角按钮
const menu = ref<IMenu[]>([]) // 右上角审批状态按钮组合
const active = ref('') // 选中的按钮
const tableRef = ref() // 表格组件ref
// 查询条件
const timeRange = ref<[DateModelType, DateModelType]>(['', ''])
const listQuery: Ref<ILabQuery> = ref({
  sampleNo: '', // 样品编号
  sampleName: '', // 样品名称
  sampleModel: '', // 型号
  manufacturingNo: '', // 出厂编号
  orderNo: '', // 委托单编号
  customerNo: '', // 委托方代码
  customerName: '', // 委托方名称
  isUrgent: '', // 是否加急
  sampleBelong: '', // 样品属性
  startTime: '', // 应检完时间-开始
  endTime: '', // 应检完时间-结束
  measureStatus: active.value, // 检测状态
  remark: '', // 备注
  offset: 1,
  limit: 20,
})
// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, 'lab-myMeasureList', listQuery.value)
})
// 重新赋值
listQuery.value = renewSearchParams('lab-myMeasureList') || {
  sampleNo: '', // 样品编号
  sampleName: '', // 样品名称
  orderNo: '', // 委托单编号
  customerNo: '', // 委托方代码
  customerName: '', // 委托方名称
  isUrgent: '', // 是否加急
  sampleBelong: '', // 样品属性
  startTime: '', // 应检完时间-开始
  endTime: '', // 应检完时间-结束
  measureStatus: active.value, // 检测状态
  remark: '', // 备注
  offset: 1,
  limit: 20,
}
// --------------获取所需字典值----------------
const sampleBelongList = ref<dictType[]>([]) // 样品属性列表
function getDict() {
  // 获取样品属性
  getDictByCode('sampleBelong').then((response) => {
    sampleBelongList.value = response.data
  })
  return new Promise((resolve, reject) => {
    // 获取菜单字典
    getDictByCode('measureStatus').then((response) => {
      response.data.forEach((item: dictType) => {
        if (['待检测', '检测中', '检测完成'].includes(item.name)) {
          menu.value.push({
            name: item.name,
            id: `${item.value}`,
          })
          resolve(menu.value)
        }
      })
    })
  })
}

// 表头
const columns = ref<TableColumn[]>([
  { text: '样品编号', value: 'sampleNo', width: '160', align: 'center' },
  { text: '样品名称', value: 'sampleName', align: 'center' },
  { text: '型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  { text: '委托单编号', value: 'orderNo', align: 'center', width: '160' },
  { text: '委托方代码', value: 'customerNo', align: 'center', width: '160' },
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '业务员', value: 'busPersonName', align: 'center' },
  { text: '是否加急', value: 'isUrgentName', align: 'center', width: '55px', styleFilter: (row: ITaskList) => { return row.isUrgentName == '是' ? 'color: red' : '' } },
  { text: '应检完时间', value: 'requireOverTime', align: 'center', width: '180' },
  { text: '样品属性', value: 'sampleBelongName', align: 'center' },
  { text: '当前检定环节', value: 'currentSegment', align: 'center' },
  { text: '备注', value: 'remark', align: 'center' },
  // { text: '证书出具', value: 'certificationState', align: 'center', filter: (row: ITaskList) => { return `${row.currentCertifications}/${row.requireCertifications}` } },
])
// 表格数据
const list = ref<ITaskList[]>([])
// 总数
const total = ref(0)
// 表格加载状态
const loadingTable = ref(false)
// 选中的内容
const checkoutList = ref<ITaskList[]>([])
const checkoutIdList = ref<string[]>([])
// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  // if (!isNowPage) {
  //   // 是否显示当前页，否则跳转第一页
  //   listQuery.value.offset = 1
  // }
  if (!listQuery.value.measureStatus) {
    listQuery.value.measureStatus = '2' // 待检测
  }
  getMyMeasureList(listQuery.value).then((res) => {
    list.value = res.data.rows.map((item: ITaskList) => {
      item.isUrgentName = item.isUrgent == 1 ? '是' : '否'
      item.sampleFileStatus = String(item.sampleFileStatus)
      return item
    })
    total.value = res.data.total
    loadingTable.value = false
  })
}
// 多选发生改变时
function handleSelectionChange(e: any) {
  checkoutIdList.value = e.map((item: { id: string }) => item.id)
  checkoutList.value = e
}

// 点击搜索
const searchList = () => {
  fetchData(true)
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    sampleNo: '', // 样品编号
    sampleName: '', // 样品名称
    sampleModel: '', // 型号
    manufacturingNo: '', // 出厂编号
    orderNo: '', // 委托单编号
    customerNo: '', // 委托方代码
    customerName: '', // 委托方名称
    isUrgent: '', // 是否加急
    sampleBelong: '', // 样品属性
    startTime: '', // 应检完时间-开始
    endTime: '', // 应检完时间-结束
    remark: '', // 备注
    measureStatus: active.value, // 检测状态
    offset: 1,
    limit: 20,
  }
  timeRange.value = ['', '']
  fetchData(false)
}
// 点击详情
const handleDetail = (row: ITaskList) => {
  $router.push(`myMeasureDetail/detail/${row.sampleId}?order=${row.orderId}&customerId=${row.customerId}&measureStatus=${listQuery.value.measureStatus}&certificateReportId=${row.certificateReportId}`)
}

// 点击分发， 弹窗
const distributeDialogRef = ref()
const handleDistribute = (row: ITaskList) => {
  distributeDialogRef.value.initDialog(row.orderId, row.sampleId)
}
// 点击标签绑定
const barCodeBind = ref()
const bindLabel = (row: ITaskList) => {
  barCodeBind.value.initDialog(row.sampleId)
}
// 标签绑定完成
const bindLabelOver = () => {
  searchList()
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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)
}

// 打印列表
function printList() {
  // 打印列
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (checkoutIdList.value.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, '我的检测列表')
  }
  else if (checkoutIdList.value.length > 0) {
    const printList = list.value.filter((item: ITaskList) => checkoutIdList.value.includes(item.sampleId))
    printJSON(printList, properties, '我的检测列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

// 点击批量收入
const scanSampleRef = ref()
const batchScan = () => {
  scanSampleRef.value.initDialog(false, '3', '1')
}

// 收入
const takeIn = function (row: ITaskList) {
  let param = [] as any
  if (Array.isArray(row)) {
    param = row.map((item: { sampleId: string; orderId: string }) => {
      return {
        orderId: item.orderId,
        sampleId: item.sampleId,
      }
    })
  }
  else {
    param = [row]
  }
  ElMessageBox.confirm(
    '确认收入该样品吗？',
    '提示',
    { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' },
  ).then(() => {
    // 收入样品
    myExecutiveReceive(param).then((res) => {
      if (res.code == 200) {
        ElMessage.success('已收入')
        fetchData()
      }
    })
  })
}
// 对列表中样品批量收入
const scanOver = function (list: any) {
  // TODO:批量收入
  takeIn(list)
  scanSampleRef.value.closeDialog()
  fetchData()
}

// 退回
const rollbackRef = ref()
const rollback = function (row: ITaskList) {
  rollbackRef.value.initDialog(row)
}
// 退检
const sendBackRef = ref()
const sendBack = function (row: ITaskList) {
  sendBackRef.value.initDialog(row)
}

/**
 * 检完
 * @param row
 * @param type scan 默认是批量扫完，batchComplete 为点击按钮批量检完
 */
const mearsureOver = function (row: any, type = 'scan') {
  let param = [] as any
  if (Array.isArray(row) && type === 'scan') { // 是数组说明是扫码过来的
    param = row.map((item: { sampleId: string; orderId: string }) => {
      return {
        orderId: item.orderId,
        sampleId: item.sampleId,
      }
    })
  }
  else if (type === 'batchComplete') { // 点击批量检完按钮
    if (!checkoutIdList.value.length) {
      ElMessage.warning('请选中')
      return false
    }
    param = checkoutList.value.map((item: { sampleId: string; orderId: string }) => {
      return {
        orderId: item.orderId,
        sampleId: item.sampleId,
      }
    })
  }
  else {
    param = [row]
  }
  ElMessageBox.confirm(
    '确认完成该样品检测吗？',
    '提示',
    { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' },
  ).then(() => {
    myExecutiveDone(param).then((res) => {
      if (res.code == 200) {
        ElMessage.success('检测完成')
        fetchData()
        if (tableRef.value) {
          tableRef.value.clearMulti()
        }
      }
    })
  })
}

// 点击批量捡完
const scanOverRef = ref()
const batchOverScan = () => {
  scanOverRef.value.initDialog(false, '3', '2')
}
// 对列表中样品批量捡完
const scanMeasureOver = function (list: any) {
  // TODO:批量收入
  mearsureOver(list)
  scanOverRef.value.closeDialog()
  fetchData()
}

// 选择按钮变更
const changeCurrentButton = (val: string) => {
  active.value = val
  window.sessionStorage.setItem('myMeasureActive', val)
  // clearList()
  listQuery.value.measureStatus = active.value
  fetchData(true)
  if (tableRef.value) {
    tableRef.value.clearMulti()
  }
}

// 点击生成原始记录
const createPrimitiveLog = (row: any) => {
  let type = 'add'
  switch (String(row.sampleFileStatus)) {
    case '1':
      type = 'add'
      break
    case '4':
      type = 'detail'
      break
    default:
      type = 'edit'
      break
  }
  // 获取任务详情
  getTaskDetail({ orderId: row.orderId, sampleId: row.sampleId }).then((res) => {
    $router.push({
      path: `/lab/primitiveLogList/${type}/${row.originalRecordId}`,
      query: {
        ...res.data,
      },
    })
  })
}
// 生成证书
const createCertificate = (row: any) => {
  let type = 'add'
  switch (String(row.sampleFileStatus)) {
    case '2':
      type = 'add'
      break
    case '4':
      type = 'detail'
      break
    default:
      type = 'edit'
      break
  }
  const nav = (data: any) => {
    $router.push({
      path: `/lab/reportOnCredentialsApproval/${type}/${row.certificateReportId}`,
      query: {
        processId: data.processId,
        row: JSON.stringify(data),
        originalRecordId: row.originalRecordId,
        flag: 'myMeasureList',
        // processId: data.processId,
      },
    })
  }
  if (type === 'add') {
    nav({})
    return
  }
  // 获取证书详情
  getReportDetail({ id: row.certificateReportId }).then((res) => {
    nav(res.data)
  })
}
// 点击添加设备
const deviceRef = ref()
const addDevice = () => {
  deviceRef.value?.initDialog()
}
// 确认添加设备
const confirmDevice = (device: any[]) => {
  console.log(device, 'devicedevice')
  claimTasks(device.map(item => ({ sampleId: item.sampleId, orderId: item.orderId }))).then((res) => {
    ElMessage.success('添加成功')
  })
}

// 点击推退检
watch(timeRange, (val) => {
  if (val) {
    listQuery.value.startTime = `${val[0]}`
    listQuery.value.endTime = `${val[1]}`
  }
  else {
    listQuery.value.startTime = ''
    listQuery.value.endTime = ''
  }
})

onMounted(async () => {
  getDict().then(() => {
    if (window.sessionStorage.getItem('myMeasureActive') != null) {
      active.value = window.sessionStorage.getItem('myMeasureActive') as string
    }
    else {
      active.value = menu.value.find(item => item.name === '待检测')!.id as string // 待检测
    }
    listQuery.value.measureStatus = active.value
    fetchData(true)
  })
  // nextTick(() => {
  // fetchData(true)
  // })
})
</script>

<template>
  <app-container>
    <button-box :active="active" :menu="menu" @change-current-button="changeCurrentButton" />
    <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="样品名称"
          clearable
          class="short-input"
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.sampleModel"
          placeholder="型号"
          clearable
          class="short-input"
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.manufacturingNo"
          placeholder="出厂编号"
          clearable
          class="short-input"
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.orderNo"
          placeholder="委托单编号"
          clearable
          class="short-input"
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.customerNo"
          placeholder="委托方代码"
          class="short-input"
          clearable
        />
      </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>
        <el-input
          v-if="listQuery.measureStatus === '4' || listQuery.measureStatus === '3'"
          v-model.trim="listQuery.remark"
          placeholder="备注"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-select v-model="listQuery.isUrgent" placeholder="是否加急" style="width: 120px;" clearable>
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </search-item>
      <search-item>
        <el-select v-model="listQuery.sampleBelong" placeholder="样品属性" style="width: 120px;" clearable>
          <el-option v-for="item in sampleBelongList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="listQuery.measureStatus === '2'" icon="icon-add" title="添加设备" type="primary" @click="addDevice" />
        <icon-button v-if="listQuery.measureStatus === '2'" icon="icon-scan" title="扫描收入" type="primary" @click="batchScan" />
        <icon-button v-if="listQuery.measureStatus === '3'" icon="icon-scan" title="扫描检完" type="primary" @click="batchOverScan" />
        <icon-button v-if="listQuery.measureStatus === '3'" icon="icon-batch" title="批量检完" type="primary" @click="mearsureOver(null, 'batchComplete')" />
        <icon-button v-if="proxy.hasPerm('/meter/customer/export')" icon="icon-print" title="打印" type="primary" @click="printList" />
      </template>
      <normal-table
        ref="tableRef"
        :data="list" :total="total" :columns="columns" :query="listQuery"
        :list-loading="loadingTable" is-showmulti-select @change="changePage" @multi-select="handleSelectionChange"
      >
        <template #columns>
          <!-- <el-table-column v-if="listQuery.measureStatus === '4' || listQuery.measureStatus === '3'" label="备注" align="center">
            <template #default="{ row }">
              {{
                row.remark
              }}
            </template>
          </el-table-column> -->
          <el-table-column label="操作" align="center" fixed="right" width="200">
            <template #default="{ row }">
              <el-button size="small" link type="primary" @click="handleDetail(row)">
                详情
              </el-button>
              <el-button v-if="listQuery.measureStatus === '2'" size="small" type="primary" link @click="takeIn(row)">
                收入
              </el-button>
              <el-button v-if="listQuery.measureStatus === '2'" size="small" type="primary" link @click="rollback(row)">
                退回
              </el-button>
              <el-button v-if="listQuery.measureStatus === '2'" size="small" type="primary" link @click="sendBack(row)">
                退检
              </el-button>
              <!-- <el-button v-if="listQuery.measureStatus === '3'" size="small" type="primary" link @click="createPrimitiveLog(row)">
                {{ row.sampleFileStatus === '1' ? '生成原始记录' : row.sampleFileStatus === '4' ? '查看原始记录' : '编辑原始记录' }}
              </el-button> -->
              <!-- <el-button v-if="listQuery.measureStatus === '3'" :disabled="row.sampleFileStatus === '1'" size="small" type="primary" link @click="createCertificate(row)">
                {{ row.sampleFileStatus === '3' ? '编辑证书' : row.sampleFileStatus === '4' ? '查看证书' : '生成证书' }}
              </el-button> -->
              <el-button v-if="listQuery.measureStatus === '3'" size="small" type="primary" link @click="mearsureOver(row)">
                完成
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
      <!-- 退检弹窗 -->
      <send-back-dialog ref="sendBackRef" @on-success="fetchData(true)" />
      <!-- 退回弹窗 -->
      <rollback-dialog ref="rollbackRef" @on-success="fetchData(true)" />
      <!-- 批量收入弹窗 -->
      <scan-sample-dialog ref="scanSampleRef" @confirm="scanOver" />
      <!-- 批量捡完弹窗 -->
      <scan-sample-dialog ref="scanOverRef" title="批量检完" @confirm="scanMeasureOver" />
      <!-- 添加设备弹窗 -->
      <add-device-com ref="deviceRef" @confirm="confirmDevice" />
    </table-container>
  </app-container>
</template>

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