<template>
  <el-drawer title="外协单信息" :with-header="false" v-model="visible" direction="rtl" size="100%">
    <div class="form-container column-container">
      <div class="form-btns-container">
        <span class="title-label">
          <el-icon>
            <Document />
          </el-icon>
          <span>盘点批次</span>
        </span>

        <div class="close-btn" @click="cancel">
          <i class="fa fa-times" aria-hidden="true" />
          <!-- <span>关闭</span> -->
        </div>
      </div>
      <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true"
        style="margin-right: 0px">
        <el-form-item class="section-title" label="外协盘点批次列表" />
        <el-form-item label="外协单号：">
          <el-input placeholder="请输入外协单号" v-model.trim="queryParams.outsourceFormNo"
            @keydown.enter.prevent="submitQuery" clearable style="width: 130px" />
        </el-form-item>
        <el-form-item style="margin-left: 0">
          <el-button type="info" icon="Search" @click="submitQuery">搜索
          </el-button>
          <el-button type="danger" icon="Close" @click="deleteLots">删除
          </el-button>
          <el-button type="primary" icon="Check" @click="handleTaksLot">一键盘点
          </el-button>
        </el-form-item>
      </el-form>
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table 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="行号" type="index" align="center" width="48" />
            <el-table-column label="批次号" prop="lotCode" align="center" width="120px">
              <template #default="scope">
                <el-button link type="primary" @click="handleColumnClick(scope.row.lotCode)"><span>{{ scope.row.lotCode
                    }}</span></el-button>
              </template>
            </el-table-column>
            <el-table-column label="产品描述" align="center" prop="productDescription" />
            <el-table-column label="箱号" align="center" prop="carrierName" width="120" />
            <el-table-column label="生产状态" prop="isProductStatus" width="90" align="center">
              <template #default="scope">
                <dict-tag :options="inventory_production_status" :value="scope.row.isProductStatus" />
              </template>
            </el-table-column>
            <el-table-column label="工段" align="center" prop="deptName" width="100" />
            <el-table-column label="工序" align="center" prop="processAlias" width="110" />
            <el-table-column label="投入数" align="center" prop="prodNum" width="96" />
            <el-table-column label="盘点数量" align="center" prop="taksStockNum" width="96">
              <template #default="scope">
                <el-input-number v-if="scope.row.editStatus" v-model="scope.row.taksStockNum" controls-position="right"
                  style="width: 100px" :min="0" :precision="0" :max="99999"
                  @input="(val) => { handleChangeTaksStockNum(val, scope.row, scope.$index) }" />
                <div v-else>{{ scope.row.taksStockNum }}</div>
              </template>
            </el-table-column>
            <el-table-column label="外协单号" align="center" prop="outsourceFormNo" width="110" />
            <el-table-column label="标识" width="300" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.isWaste == 1" class="spacing" type="danger">{{ "批废" }}</el-tag>
                <el-tag v-if="scope.row.isAmend == 1" class="spacing" type="danger">{{ "工艺修改" }}</el-tag>
                <el-tag v-if="scope.row.isWasteRecycling == 1" class="spacing" type="primary">{{ "废品回用" }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="盘点状态" prop="isTaksStock" width="200" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.isTaksStock" placeholder="请选择盘点状态" style="width: 160px"
                  v-if="scope.row.editStatus"
                  @change="(val) => { handleChangeTaksStock(val, scope.row, scope.$index) }">
                  <el-option v-for="dict in is_taks_stock" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
                <div v-else>
                  <dict-tag :options="is_taks_stock" :value="scope.row.isTaksStock" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160" align="center" v-if="detailInfo.status != 2">
              <template #default="scope">
                <el-button link icon="Check" v-if="scope.row.editStatus" type="success"
                  @click="handleSave(scope.row, scope.$index)">保存</el-button>
                <el-button link icon="Edit" v-else type="warning" @click="handleEdit(scope.row, scope.$index)"
                  v-hasPermi="['business:inventoryCheck:editDetail']">编辑</el-button>
                <el-button link icon="Close" v-if="scope.row.editStatus" type="danger"
                  @click="handleCancel(scope.row, scope.$index)">取消</el-button>
                <el-button link icon="Delete" v-else type="danger" @click="handleDelete(scope.row, scope.$index)"
                  v-hasPermi="['business:inventoryCheck:deleteDetail']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </el-drawer>
</template>
<script setup>
import {
  listTaksStockLot, updateTaksStockLot, updateNoStartLot, exportNoStartLot, getLotsByOutsourceFormNo, batchTaksStockLot
} from "@/api/business/taksStockLot";
import { getDeptList } from "@/api/business/planDetailSubDetail.js";
import { ref } from "vue";
import router from "@/router";
const { proxy } = getCurrentInstance();
/** 字典 */
const { is_identification } = proxy.useDict("is_identification");
const { is_taks_stock } = proxy.useDict("is_taks_stock");
const { inventory_production_status } = proxy.useDict("inventory_production_status");

/** 表单抽屉 页变量 */
const loading = ref(false);
const visible = ref(false);
const detailInfo = ref({});
const total = ref(0)
const isDispatch = ref(false)
const deptList = ref([])
const dataList = ref([])
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
/** 查询对象 */
const queryParams = ref({
  pageNum: 1,
  pageSize: 50,
  productDescription: "",
  lotCode: "",
  deptId: null,
  flags: null,
  isTaksStock: null
});

/****************************  方法区  ****************************/
/** 打开抽屉 */
const open = (row) => {
  visible.value = true;
  reset();
  detailInfo.value = proxy.deepClone(row);
}
function handleEdit(row, index) {
  row.editStatus = true
  console.log(row);
  if (row.isTaksStock != 1) {
    row.taksStockNum = row.prodNum
  }
  console.log(row)
}
//一键盘点
function handleTaksLot() {
  if (dataList.value.length == 0) {
    proxy.$message.error('没有可盘点批次')
    return
  }
  batchTaksStockLot(dataList.value).then(res => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess(res.msg);
      dataList.value = []
    }
  })
}
function handleSave(row, index) {
  updateTaksStockLot(row).then(res => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess("保存成功");
      console.log(res)
      dataList.value[index] = { ...res.data, editStatus: false }
    }
  })
}
/** 打开批次详情页 */
// function handleColumnClick(lotCode) {
//   router.push({ path: "/reviseBath/lotFormParticulars/" + lotCode });
// }
function handleColumnClick(lotCode) {
  // 拼接 URL
  const url = "/reviseBath/lotFormParticulars/" + lotCode;
  // 在新标签页打开 URL
  window.open(url, '_blank');
}
function handleChangeTaksStock(value, row, index) {
  if (value == 0) {
    dataList.value[index].taksStockNum = 0
  }
}
function handleChangeTaksStockNum(value, row, index) {
  if (value != 0) {
    dataList.value[index].isTaksStock = "1"
  }
}
function handleCancel(row, index) {
  dataList.value[index].editStatus = false
}

function handleDelete(row, index) {
  dataList.value.splice(index, 1)
}

function submitQuery() {
  console.log(detailInfo.value)
  getLotsByOutsourceFormNo({ outsourceFormNo: queryParams.value.outsourceFormNo, takeStockPeriodId: detailInfo.value.id }).then(res => {
    if (res.code === 200) {
      dataList.value.push(...res.data.filter(e => !dataList.value.some(t => t.id === e.id)))
    }
  })
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function deleteLots() {
  dataList.value = dataList.value.filter(e => !ids.value.includes(e.id))
  handleSelectionChange([])
}
/** 取消按钮 */
const cancel = () => {
  visible.value = false;
  reset();
};

/** 表单重置 */
const reset = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 50,
    productDescription: "",
    lotCode: "",
    deptId: null,
    flags: null,
    isTaksStock: null
  };
  dataList.value = [];
};


/** 暴露给父组件的方法 */
defineExpose({
  open,
});
</script>
