<template>
  <div class="page-container column-container">
    <!-- 搜索区 -->
    <el-form
      class="list-search-container"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      style="margin-right: 0px"
    >
      <el-form-item label="批次号：" prop="lotCode">
        <el-input
          v-model="queryParams.lotCode"
          placeholder="请输入批次号"
          style="width: 130px"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划单号：" prop="productDescription">
        <el-input
          v-model="queryParams.productionPlanNo"
          placeholder="请输入计划单号"
          style="width: 144px"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品描述：" prop="productDescription">
        <el-input
          v-model="queryParams.productDescription"
          placeholder="请输入产品描述"
          style="width: 144px"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批号状态：">
        <el-select
          v-model="queryParams.itemStatus"
          clearable
          placeholder="批次状态"
          style="width: 120px"
        >
          <el-option
            v-for="dict in special_daywork_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="section-title" label="请选择工段：">
        <el-select-v2
          v-model="queryParams.deptId"
          filterable
          :options="deptList"
          placeholder="请选择工段"
          style="width: 100px"
          @change="handleDeptChange"
        />
      </el-form-item>
      <el-form-item label="创建时间：" prop="createTime">
        <el-date-picker
          v-model="queryParams.specialStartTime"
          type="date"
          style="width: 120px"
          value-format="YYYY-MM-DD"
          placeholder="选择起始日期"
          clearable
        />
        <span style="margin: 0 4px">~</span>
        <el-date-picker
          v-model="queryParams.specialEndTime"
          type="date"
          style="width: 120px"
          value-format="YYYY-MM-DD"
          placeholder="选择结束日期"
          clearable
        />
      </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-form-item>
    </el-form>

    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <el-button
        type="primary"
        icon="Plus"
        v-hasPermi="['business:specialDaywork:add']"
        @click="handleShowFormDialog(null)"
      >
        新增
      </el-button>
      <el-button
        type="danger"
        icon="Delete"
        :disabled="ids.length == 0"
        v-hasPermi="['business:specialDaywork:remove']"
        @click="handleDelete"
      >
        删除
      </el-button>
      <el-button
        type="warning"
        icon="Promotion"
        :disabled="ids.length == 0"
        v-hasPermi="['business:specialDaywork:turnaround']"
        @click="handleShowTurnoverInfoDialog"
      >
        周转
      </el-button>
      <el-button
        type="info"
        icon="Close"
        :disabled="ids.length == 0"
        v-hasPermi="['business:specialDaywork:cancelTurnaround']"
        @click="handleNoTurnoverInfo"
      >
        取消周转
      </el-button>
    </div>
    <!-- 渲染数据区 -->
    <div class="el-table-container">
      <div class="el-table-inner-container">
        <el-table
          ref="dayworkTable"
          v-loading="loading"
          :data="dataList"
          size="small"
          border
          height="100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="48" align="center" />
          <el-table-column
            label="客户简称"
            align="center"
            prop="productionPlanDetail"
            width="120"
          >
            <template #default="scope">
              {{ scope.row.productionPlanDetail.companyAlias }}
            </template>
          </el-table-column>
          <el-table-column
            label="计划单号"
            align="center"
            prop="supplierName"
            width="80"
          >
            <template #default="scope">
              {{ scope.row.productionPlanDetail.productionPlanNo }}
            </template>
          </el-table-column>
          <el-table-column
            label="批次号"
            align="center"
            prop="lotCode"
            width="120"
          >
            <template #default="scope">
              {{ scope.row.lotCode }}
            </template>
          </el-table-column>
          <el-table-column
            label="产品描述"
            align="center"
            prop="formDate"
            min-width="200"
          >
            <template #default="scope">
              {{ scope.row.productionPlanDetail.productDescription }}
            </template>
          </el-table-column>
          <el-table-column
            label="图纸版本"
            align="center"
            prop="formDate"
            width="65"
          >
            <template #default="scope">
              {{ scope.row.productionPlanDetail.technologyVersion }}
            </template>
          </el-table-column>
          <el-table-column
            label="当前工序"
            align="center"
            prop="formDate"
            width="120"
          >
            <template #default="scope">
              {{ scope.row.processAlias }}
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            width="100"
            prop="status"
            align="center"
          >
            <template #default="scope">
              <dict-tag
                :options="daywork_status"
                :value="scope.row.itemStatus"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="投产量"
            align="center"
            prop="prodNum"
            width="60"
          >
          </el-table-column>
          <el-table-column
            label="合格量"
            align="center"
            prop="qualifiedNum"
            width="60"
          >
          </el-table-column>
          <el-table-column
            label="废品量"
            align="center"
            prop="rejectSum"
            width="60"
          >
          </el-table-column>
          <el-table-column
            label="载具"
            align="center"
            prop="carrierCode"
            width="120"
          >
          </el-table-column>
          <el-table-column
            label="操作者"
            align="center"
            prop="itemNames"
            width="200"
          >
          </el-table-column>
          <el-table-column
            label="创建人"
            align="center"
            prop="nickName"
            width="80"
          >
          </el-table-column>

          <el-table-column
            label="创建时间"
            align="center"
            prop="nickName"
            width="140"
          >
            <template #default="scope">
              {{ parseTime(scope.row.startTime, "{y}-{m}-{d} {h}:{i}:{s}") }}
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            class-name="small-padding fixed-width"
            width="200"
          >
            <template #default="scope">
              <el-button
                v-if="scope.row.itemStatus < 4"
                link
                type="primary"
                icon="Edit"
                v-hasPermi="['business:specialDaywork:edit']"
                @click="handleShowFormDialog(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="scope.row.itemStatus < 4"
                link
                type="warning"
                icon="Promotion"
                v-hasPermi="['business:specialDaywork:turnaround']"
                @click="handleShowTurnoverInfoDialog(scope.row)"
              >
                周转
              </el-button>
              <el-button
                v-else
                link
                type="danger"
                icon="close"
                v-hasPermi="['business:specialDaywork:cancelTurnaround']"
                @click="handleNoTurnoverInfo(scope.row)"
              >
                取消周转
              </el-button>
              <el-button
                v-if="scope.row.itemStatus < 4"
                link
                type="danger"
                icon="Delete"
                v-hasPermi="['business:specialDaywork:remove']"
                @click="handleDelete(scope.row)"
              >
                删除
              </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"
    />
    <turnover-info-dialog ref="turnoverInfoDialogRef" :getList="getList" />
    <!-- 表单 -->
    <special-form ref="specialtRef" :getList="getList" />
  </div>
</template>

<script setup name="specialDaywork">
import {
  listSpecialDaywork,
  delSpecialDaywork,
  cancelSpecialDaywork,
  carrierFinishedCheck,
} from "@/api/business/specialDaywork";
import { specialGetDeptList } from "@/api/business/planDetailSubDetail.js";
import {isTakeStock} from "@/api/business/takeStockPeriod.js"
import turnoverInfoDialog from "./turnoverInfoDialog";
import specialForm from "./form";
const { proxy } = getCurrentInstance();
/** 字典数组区 */
const { daywork_status } = proxy.useDict("daywork_status");
const { special_daywork_status } = proxy.useDict("special_daywork_status");

const deptList = ref([]);
const dataList = ref([]);
const dayworkTable = ref(null);
const loading = ref(true);
const selected = ref([]);
const ids = ref([]);
const total = ref(0);
/** 查询对象 */
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  specialStartTime: proxy.moment().subtract(7, "days").format("YYYY-MM-DD"),
  specialEndTime: proxy.moment().format("YYYY-MM-DD"),
});

/***********************  方法区  ****************************/
function init() {
  loading.value = true;
  specialGetDeptList().then((response) => {
    deptList.value = response.data;
    console.log("deptId", deptList.value);
    queryParams.value.deptId = deptList.value[0].value;
    queryParams.value.deptName = deptList.value[0].label;
    if (deptList.value.length > 0) {
      getList();
    } else {
      loading.value = false;
    }
  });
}

function getList() {
  loading.value = true;
  listSpecialDaywork(queryParams.value).then((response) => {
    if ((response.code = 200)) {
      dataList.value = response.rows;
      total.value = response.total;
    }
    loading.value = false;
  });
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    deptId: deptList.value[0].value,
    deptName: deptList.value[0].label,
    specialStartTime: proxy.moment().subtract(7, "days").format("YYYY-MM-DD"),
    specialEndTime: proxy.moment().format("YYYY-MM-DD"),
  };
  handleQuery();
}

/** 取消周转按钮操作 */
function handleNoTurnoverInfo(row) {
  let cancelRows = [];
  if (row.id) {
    cancelRows.push(row);
  } else {
    cancelRows = dayworkTable.value.getSelectionRows();
  }

  if (cancelRows.some((row) => row.itemStatus != 4)) {
    proxy.$modal.msgError("存在未周转的批次，无法取消！");
  } else {
    isTakeStock().then(res =>{
    if(res.data) {
      proxy.$modal.msgError('正在盘点，不能取消周转')
    }else{
    proxy.$modal
      .confirm("是否确认取消周转？")
      .then(() => {
        console.log("是否确认取消周转？", cancelRows);
        return cancelSpecialDaywork(cancelRows);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("操作成功！");
      })
      .catch((err) => {
        console.log("err", err);
      });
    }
  })
  }
}

function handleDeptChange(arg) {
  const dept = deptList.value.filter((v) => v.value == arg);
  queryParams.value.deptName = dept[0].label;
  queryParams.value.deptId = dept[0].value;
}

/**复选框选中数据 */
function handleSelectionChange(selection) {
  selected.value = selection;
  ids.value = selection.map((item) => item.id);
}

/** 新增,修改按钮操作 */
function handleShowFormDialog(row) {
  console.log("编辑按钮传参", row);
  proxy.$refs.specialtRef.open(row, queryParams.value);
}

/** 周转申请按钮操作 */
function handleShowTurnoverInfoDialog(row) {
  let rows = [];
  if (row.id) {
    rows.push(row);
  } else {
    rows = dayworkTable.value.getSelectionRows();
  }

  if (rows.length == 0) {
    proxy.$modal.msgError("请选择周转批次！");

    return;
  }

  //判断是否能够周转
  if (!areProductionPlanDetailIdsConsistent(rows)) {
    proxy.$modal.msgError("请选相同计划单的数据！");
    return;
  }

  if (!areProcessConsistent(rows)) {
    proxy.$modal.msgError("请选相同工序的数据！");
    return;
  }

  if (rows.some((row) => row.itemStatus != 3)) {
    proxy.$modal.msgError("请选择工序已完成的批次进行周转！");
    return;
  } else {
    isTakeStock().then(res =>{
    if(res.data) {
      proxy.$modal.msgError('正在盘点，不能周转')
    }else{
    loading.value = true;
    //查询是否序检完成，或一箱多批是否全部完成
    carrierFinishedCheck(rows)
      .then((res) => {
        if (res.code == 200) {
          proxy.$refs.turnoverInfoDialogRef.open(rows);
        }
        loading.value = false;
      })
      .catch((err) => {
        loading.value = false;
      });
  }
})
}
}

/** 删除按钮操作 */
function handleDelete(row) {
  let delRows = [];
  if (row.id) {
    delRows.push(row);
  } else {
    delRows = dayworkTable.value.getSelectionRows();
  }
  if (delRows.length == 0) {
    proxy.$modal.msgError("请选择需要取消的数据！");
    return;
  }
  if (delRows.some((row) => row.itemStatus == 4)) {
    proxy.$modal.msgError("存在已经周转的批次，无法删除！");
  } else {
    proxy.$modal
      .confirm("是否确定取删除选中的数据项？")
      .then(() => {
        console.log("删除", delRows);
        return delSpecialDaywork(delRows);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功！");
      })
      .catch((err) => {
        console.log("err", err);
      });
  }
}

function areProcessConsistent(cancelRows) {
  // 获取第一个元素的specialProcessId
  const firstId = cancelRows[0].specialProcessId;
  // 遍历数组中的其他元素，检查specialProcessId是否与第一个元素相同
  for (let i = 1; i < cancelRows.length; i++) {
    if (cancelRows[i].specialProcessId !== firstId) {
      return false; // 只要发现有一个不同，立即返回false
    }
  }

  // 如果遍历完所有元素都没有发现不同，则返回true
  return true;
}

function areProductionPlanDetailIdsConsistent(cancelRows) {
  // 获取第一个元素的productionPlanDetailId
  const firstId = cancelRows[0].productionPlanDetailId;

  // 遍历数组中的其他元素，检查productionPlanDetailId是否与第一个元素相同
  for (let i = 1; i < cancelRows.length; i++) {
    if (cancelRows[i].productionPlanDetailId !== firstId) {
      return false; // 只要发现有一个不同，立即返回false
    }
  }

  // 如果遍历完所有元素都没有发现不同，则返回true
  return true;
}

init();
</script>
