<!-- 外协结算前审核 -->
<template>
  <div class="page-container column-container">
    <!-- 搜索区 -->
    <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
      <!-- <el-form-item label="检查日期：" prop="startTime">
        <el-input v-model="queryParams.startTime" placeholder="" style="width: 144px" clearable
          @keyup.enter="handleQuery" />
        <el-date-picker v-model="queryParams.startTime" type="date" placeholder="选择日期" style="width: 144px" clearable
          @keyup.enter="handleQuery" value-format="YYYY-MM-DD" />
      </el-form-item> -->
      <el-form-item label="外协商名称：" prop="supplierName">
        <el-input v-model="queryParams.supplierName" placeholder="请输入外协商名称" style="width: 144px" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="批次号：" prop="lotCode">
        <el-input v-model.trim="queryParams.lotCode" placeholder="请输入批次号" style="width: 144px" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="发出单号：" prop="outsourcedOrderDetailFormCode">
        <el-input v-model.trim="queryParams.outsourcedOrderDetailFormCode" placeholder="请输入发出单号" style="width: 144px"
          clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="收回单号：" prop="returnReceiptDetailFormCode">
        <el-input v-model.trim="queryParams.returnReceiptDetailFormCode" placeholder="请输入收回单号" style="width: 144px"
          clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="检查日期：">
        <el-date-picker v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD" :editable="false"
          :clearable="false" placeholder="请选择开始时间" style="width: 130px" @change="handleDateChange" />
        <span>到</span>
        <el-date-picker v-model="queryParams.endTime" type="date" value-format="YYYY-MM-DD" :editable="false"
          :clearable="false" placeholder="请选择结束时间" style="width: 130px" @change="handleDateChange" />
      </el-form-item>
      <el-form-item label="状态：" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" style="width: 144px" clearable placeholder="请选择">
          <el-option v-for="dict in outsource_before_checkout_verify_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="Check" :disabled="ids && ids.length == 0" @click="handlePass"
          :loading="confirmLoading">批量通过</el-button>
        <el-button type="danger" icon="Close" :disabled="ids && ids.length == 0" @click="handleFail">批量不通过</el-button>
        <el-button type="primary" @click="exportForYear">导出审核列表</el-button>
        <!-- <el-button v-if="exportSuccess" type="warning" icon="Download" @click="downloadExcel">下载导出excel</el-button>
        <el-progress v-if="doingExport" class="export-progress" :percentage="exportProgress" />
        <el-button v-if="doingExport && !exportSuccess" type="danger">停止导出</el-button> -->
      </el-form-item>
    </el-form>

    <!-- 功能按钮区 -->
    <!-- <div class="list-btns-container">
    </div> -->

    <!-- 渲染数据区 -->
    <div class="el-table-container">
      <div class="el-table-inner-container">
        <el-table v-loading="loading" :data="orderList" size="small" border height="100%"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="48" align="center" />
          <el-table-column label="外协单位" align="center" prop="outsourcedOrderDetail.supplierName" width="150" />
          <el-table-column label="批次号" align="center" prop="lotCode" width="100" />
          <el-table-column label="产品描述" align="center" prop="productDescription" width="320" />
          <!-- <el-table-column label="检查单号" align="center" prop="outsourcedInspectionNo" width="120" /> -->
          <el-table-column label="检查状态" align="center" prop="status" width="120">
            <template #default="scope">
              <dict-tag :options="process_inspection_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="外协工序" align="center" prop="processNames" width="120" />
          <el-table-column label="外协日期" align="center" prop="outsourcedOrderDetail.formDate" width="120">
            <template #default="scope">
              {{
                parseTime(
                  scope.row.outsourcedOrderDetail.formDate,
                  "{y}-{m}-{d}"
                )
              }}
            </template>
          </el-table-column>
          <el-table-column label="发出单号" align="center" prop="outsourcedOrderDetail.formCode" width="120" />
          <el-table-column label="发出量" align="center" prop="outsourcedOrderDetail.productNum" width="120" />
          <el-table-column label="收回日期" align="center" prop="returnReceiptDetail.formDate" width="120" />
          <el-table-column label="收回单号" align="center" prop="returnReceiptDetail.formCode" width="120" />
          <el-table-column label="收回量" align="center" prop="returnReceiptDetail.auditNum" width="120" />
          <el-table-column label="状态" align="center" prop="auditStatus" width="120">
            <template #default="scope">
              <dict-tag :options="outsource_before_checkout_verify_status" :value="scope.row.auditStatus" />
            </template>
          </el-table-column>
          <el-table-column label="检查日期" align="center" prop="startTime" width="120">
            <template #default="scope">
              {{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }}
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" width="120" show-overflow-tooltip />
          <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="200">
            <template #default="scope">
              <el-button v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == 2" :loading="confirmLoading" link
                type="warning" icon="Check" @click="handleConfirm(scope.row)"
                v-hasPermi="['business:beforeCheckoutVerify:edit']">
                通过
              </el-button>
              <el-button v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == 1" link type="primary"
                icon="Close" @click="handleReject(scope.row)" v-hasPermi="['business:beforeCheckoutVerify:edit']">
                不通过
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <el-dialog v-model="doingExport" title="导出审核列表" width="500px" height="400px" @close="close" append-to-body draggable
      :close-on-click-modal="false" :show-close="!doingExport || exportSuccess">
      <div v-if="doingExport && !exportSuccess"
        style="color: red;font-weight: 600;width:100%; text-align:center;height:40px;display: inline-block;line-height: 40px;">
        导出中请勿关闭</div>
      <div v-else
        style="color: red;font-weight: 600;width:100%; text-align:center;height:40px;display: inline-block;line-height: 40px;">
        导出完成</div>
      <div class="form-btns-container" style="width: 100%;">
        <el-progress v-if="doingExport" class="export-progress" :percentage="exportProgress" style="width: 100%;"
          :text-inside="true" />
        <div style="width: 100%; align-items: center; align-content: center;height: 60px;position: relative;">
          <el-button v-if="exportSuccess" type="warning" icon="Download" @click="downloadExcel"
            style="position: absolute; top: 0px; left: 50%; transform: translateX(-50%);">下载导出excel</el-button>
          <el-button v-if="doingExport && !exportSuccess" type="danger" @click="close"
            style="position: absolute; top: 0px; left: 50%; transform: translateX(-50%);">停止导出</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import {
  listCheckoutInspection,
  rejectInspection,
  confirmInspection,
  checkFurnace,
  checkMultiplyFurnace,
  exportAsync,
  getExportCount
} from "@/api/business/beforeCheckoutVerify";

import { nextTick } from "vue";
import { getToken } from '@/utils/auth'
import useUserStore from '@/store/modules/user'
import { patternNginxExportWsUrl } from "../../utils/ws"
const { proxy } = getCurrentInstance();
/** 字典数组区 */
const { outsource_before_checkout_verify_status } = proxy.useDict(
  "outsource_before_checkout_verify_status"
);

const { process_inspection_status } = proxy.useDict(
  "process_inspection_status"
);

const orderList = ref([]);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const selections = ref([])
const printCarriers = ref([]);
const confirmLoading = ref(false)
const exportSuccess = ref(false)
const doingExport = ref(false)
const exportProgress = ref(0)
const exportUrl = ref(null)
// const wsUrl = 'ws://localhost:8081/wsExport/'
const innetUrl = import.meta.env.VITE_WS_INNET_EXPORT_API
const outnetUrl = import.meta.env.VITE_WS_OUTNET_EXPORT_API
const hostIp = import.meta.env.VITE_HOST_IP;

// const wsUrl = import.meta.env.VITE_WS_EXPORT_API
let ws = null

const webHost = import.meta.env.VITE_APP_BASE_API;
/** 查询对象 */
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  formCode: null,
  formDate: null,
  endTime: proxy.moment().format("YYYY-MM-DD"),
  startTime: proxy.moment().subtract(1, "month").format("YYYY-MM-DD"),
  supplierName: null,
  deliveryMethod: null,
  packagingMethod: null,
  freightPrice: null,
  freightAmount: null,
  isFirstProcess: 0,
});

/***********************  方法区  ****************************/

/** 查询外协单主 带箱方式，是整单的。如果换新箱子，明细中，都需要更换箱子列表 */
function getList() {
  loading.value = true;
  listCheckoutInspection(queryParams.value).then((response) => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log(queryParams.value);
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.endTime = proxy.moment().format("YYYY-MM-DD"),
    queryParams.value.startTime = proxy.moment().subtract(1, "month").format("YYYY-MM-DD"),
    proxy.resetForm("queryRef");
  handleQuery();
}
//批量通过
function handlePass() {
  loading.value = true
  checkMultiplyFurnace(selections.value).then((res) => {
    if (res.code === 200) {
      if (res.data.length >= 1) {
        proxy
          .$confirm("是否确认通过？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            confirmInspection(res.data).then((res) => {
              getList()
              loading.value = false
            }).catch(e => {
              loading.value = false
            })
          })
          .catch(_ => { loading.value = false })
      } else {
        proxy
          .$confirm("该炉已全部质检，是否全部确认通过？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            confirmInspection(res.data).then((res) => {
              getList();
              loading.value = false
            }).catch(e => {
              loading.value = false
            })
          }).catch(e => {
            loading.value = false
          })
      }
    } else {
      proxy.$msgError(res.msg)
      loading.value = false
    }
  }).catch(e => {
    loading.value = false
  })
}
//批量不通过
function handleFail() {
  checkMultiplyFurnace(selections.value).then((res) => {
    if (res.code === 200) {
      proxy
        .$confirm("是否确认不通过？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          rejectInspection(res.data).then((res) => {
            getList();
          });
        })
        .catch(_ => ({}))
    }
  });
}
// 多选框选中数据
function handleSelectionChange(selection) {
  selections.value = selection;
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleConfirm(row) {
  loading.value = true
  checkFurnace(row).then((res) => {
    if (res.code === 200) {
      if (res.data.length === 1) {
        proxy
          .$confirm("是否确认通过？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            confirmInspection(res.data).then((res) => {
              getList();
              loading.value = false
            }).catch(e => {
              loading.value = false
            });
          })
          .catch(e => {
            loading.value = false
          })
      } else {
        proxy
          .$confirm("该炉已全部质检，是否全部确认通过？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            confirmInspection(res.data).then((res) => {
              loading.value = false
              getList();
            }).catch(e => {
              loading.value = false
            })
          })
          .catch(e => {
            loading.value = false
          });
      }
    } else {
      proxy.$msgError(res.msg);
      loading.value = false
    }
  }).catch(err => {
    loading.value = false
  })
}

function handleDateChange() {
  console.log(queryParams.value.startTime);
  console.log(queryParams.value.endTime);
}
function handleReject(row) {
  checkFurnace(row).then((res) => {
    if (res.code === 200) {
      proxy
        .$confirm("是否确认不通过？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          rejectInspection(res.data).then((res) => {
            getList();
          });
        });
    }
  });
}
/** 异步导出excel */
async function exportForYear() {
  // 导出前提示
  const res = await getExportCount(queryParams.value)
  console.log(res)
  const num = res.data
  const confirm = await proxy.$modal.confirm(`共${num}条数据是否确认导出？`).then(_ => true).catch(_ => false)
  if (confirm) {
    if (ws == null) {
      // 启动一个websocket
      console.log(useUserStore().user.userId)
      createWebSocket(useUserStore().user.userId, getToken()).then(_ => {
        console.log(ws)
        initWebsocket()
      })
    } else {
      initWebsocket()
    }
    // 发送请求要求导出excel
    exportAsync(queryParams.value).then(res => {
      console.log(res)
      if (res.code == 200) {
        doingExport.value = true
      }
    })
  }
}

async function createWebSocket(id, token) {
  try {
    // const options = { headers: { Authorization: 'Bearer ' + token } }
    // console.log(options)
    var itemUrl = document.location.origin;
    var wsUrl = patternNginxExportWsUrl();
    // if (itemUrl.includes(hostIp)) {
    //   wsUrl = innetUrl;
    // } else {
    //   wsUrl = outnetUrl;
    // }
    ws = new WebSocket(wsUrl + id)
  } catch (e) {
    console.log(e)
    reconnection()
  }
}
let lockReconnect = false
let timerReconnect = undefined
let timerHeart = undefined
let timerServerHeart = undefined
const heartTimeOut = 40000
let handClose = false
function reconnection() {
  console.log("重新连接")
  if (lockReconnect) {
    return
  }
  lockReconnect = true
  if (timerReconnect) {
    clearTimer(timerReconnect)
  }
  //没连上会一直重连， 设置迟延，避免请求过多
  timerReconnect = setTimeout(() => {
    //setTimeout 到点了执行
    connection(useUserStore().user.userId, getToken())
    lockReconnect = false
  }, 5000);
}

async function connection(id, token) {
  await createWebSocket(id, token)
}

function clearTimer() {
  timerReconnect && clearTimeout(timerReconnect)
  timerHeart && clearTimeout(timerHeart)
  timerServerHeart && clearTimeout(timerServerHeart)
}

function initWebsocket() {
  ws.onopen = (e) => {
    ws.send("open server")
    console.log("链接成功")
    heartCheck()
  }
  ws.onmessage = (message) => {
    // console.log(message)
    const data = JSON.parse(message.data)
    exportProgress.value = data.progress
    if (data.url != null) {
      exportSuccess.value = true
      exportUrl.value = data.url
      closeWs()
      downloadExcel()
    }
    heartCheck()
  }
  ws.onerror = (e) => {
    console.log(e)
    console.log('链接失败')
    reconnection()
  }
  ws.onclose = (e) => {
    console.log("关闭连接")
    if (!handClose) {
      reconnection()
    }
  }
}

function sentMessage(message) {
  ws.send(message)
}

function closeWs() {
  handClose = true
  clearTimer()
  if (ws != null) {
    ws.close()
    ws = null
  }
}

function heartCheck() {
  console.log('心跳检测')
  if (timerHeart) {
    clearTimeout(timerHeart)
  }
  timerHeart = setTimeout(() => {
    // console.log("ping")
    ws.send("ping")
    lockReconnect = false
  }, heartTimeOut)
}

function downloadExcel() {
  // 下载文件
  window.open(webHost + exportUrl.value)
}

function close() {
  closeWs()
  doingExport.value = false
  exportSuccess.value = false
  exportProgress.value = 0
}

onUnmounted(() => {
  if (ws != null) {
    closeWs()
  }
})

getList();
</script>
<style>
/* .export-progress .el-progress-bar {
  margin-bottom: 15px;
  width: 100px;
} */

.export-progress .el-progress-bar__outer {
  height: 20px !important;
}

.export-progress {
  /* margin-left: 6px;
  margin-right: 6px; */
  padding-left: 10px;
  padding-right: 10px;
  margin-bottom: 40px;
}
</style>
