<!-- 首序外协 -->
<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>
        <el-button
          v-show="!editStatus"
          type="warning"
          icon="Download"
          @click="handlePrint"
          v-hasPermi="['business:inboundOrder:export']"
        >
          打印
        </el-button>
        <el-button
          v-show="!editStatus && checkEdit()"
          type="warning"
          icon="Edit"
          @click="handleEdit"
        >
          编辑
        </el-button>
        <el-button
          v-show="editStatus && form.id != null"
          type="info"
          icon="Edit"
          @click="cancelEdit"
          v-hasPermi="['business:inboundOrder:export']"
        >
          取消编辑
        </el-button>
        <el-button
          v-if="editStatus"
          type="primary"
          icon="Finished"
          @click="handleSubmit"
          >保存</el-button
        >
        <el-button
          v-if="
            !editStatus &&
            form.id != null &&
            auth.hasPermi('business:inboundOrder:francise:input') &&
            form.status != 2
          "
          type="info"
          icon="Calendar"
          @click="handleInbound"
          >入库</el-button
        >
        <div class="close-btn" @click="cancel">
          <i class="fa fa-times" aria-hidden="true" />
          <!-- <span>关闭</span> -->
        </div>
      </div>
      <el-form
        ref="formRef"
        class="master-container"
        :model="form"
        v-loading="loading"
        :rules="rules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="入库类别" prop="type">
              <el-select
                v-if="editStatus"
                v-model="form.type"
                placeholder="请选择入库类别"
                style="width: 100%"
              >
                <el-option
                  v-for="item in inbound_type"
                  :key="item.value"
                  :label="item.label"
                  :value="parseInt(item.value)"
                  :disabled="checkDisabledForType(item)"
                />
              </el-select>
              <span v-else>{{ selectText(form.type, inbound_type) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="入库部门" prop="deptName">
              <span>{{ form.deptName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="包装线" prop="packageResourceGroupName">
              <span>{{ form.packageResourceGroupName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="入库单号" prop="inboundNumber">
              <el-input
                v-if="editStatus"
                disabled
                v-model="form.inboundNumber"
                placeholder="自动生成"
              />
              <span v-else>{{ form.inboundNumber }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="入库日期" prop="inboundTime">
              <el-date-picker
                v-if="editStatus"
                disabled
                v-model="form.inboundTime"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD"
                style="width: 100%"
              />
              <span v-else>{{ form.inboundTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="转运托盘码" prop="transferCode">
              <el-input
                v-if="editStatus"
                v-model="form.transferCode"
                placeholder="请输入转运托盘码"
              />
              <span v-else>{{ form.transferCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="储存区域" prop="storageArea">
              <el-select
                v-if="editStatus"
                v-model="form.storageArea"
                placeholder="请选择"
              >
                <el-option
                  v-for="dict in storage_area"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  :disabled="checkDisabled(dict)"
                />
              </el-select>
              <span v-else>{{
                selectText(form.storageArea, storage_area)
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item
              label="反检出库单号"
              prop="reSelectOutgoingOrderNumber"
            >
              <el-input
                v-if="editStatus"
                v-model="form.reSelectOutgoingOrderNumber"
                placeholder="请输入反检出库单号"
              />
              <span v-else>{{ form.reSelectOutgoingOrderNumber }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="产品种类" prop="productionType">
              <!-- <span>{{ form.productionType }}</span> -->
              <dict-tag
                :value="form.productType"
                :options="product_production_category"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="有无子件" prop="bomsta">
              <span>{{ form.isSubclass == 1 ? "有" : "无" }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="录入者" prop="inputNickName">
              <span>{{
                form.inputUserId != null
                  ? form.inputUserName + " " + form.inputNickName
                  : ""
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="规格" prop="standard">
              <span>{{ form.standard }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="保管员" prop="storageUserName">
              <span>{{
                form.storageUserId != null
                  ? form.storageUserName + " " + form.storageNickName
                  : ""
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="客户" prop="companyAlias">
              <span>{{ form.companyAlias }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="单箱支数" prop="labelNumber">
              <span>{{ form.labelNumber }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="原转运托盘码" prop="originalTransferCode">
              <span>{{ form.originalTransferCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="箱数" prop="boxNumber">
              <span>{{ form.boxNumber }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="入库总量" prop="inboundTotalNum">
              <span>{{ form.inboundTotalNum }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="单位" prop="unit">
              <span>{{ form.unit }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="包装形式码" prop="packageType">
              <span>{{ form.packageType }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="是否全部入库" prop="status">
              <span>{{ form.isPrint == 1 ? "是" : "否" }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图号" prop="drawingNo">
              <span>{{ form.drawingNo }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 渲染数据区 -->
      <div class="form-details-btns-container">
        <el-button
          v-show="editStatus"
          type="primary"
          icon="Plus"
          @click="handleAddByCode"
          v-hasPermi="['business:inboundOrder:add']"
        >
          添加
        </el-button>
        <el-button
          :disabled="selections.length === 0"
          type="primary"
          icon="Plus"
          @click="handlePrintCertificate"
        >
          合格证重印
        </el-button>
      </div>
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table
            v-loading="loading"
            :data="form.details"
            size="small"
            border
            height="100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" align="center" width="48" />
            <el-table-column
              label="行号"
              type="index"
              align="center"
              width="48"
            />
            <el-table-column
              label="合格证编号"
              align="center"
              prop="certificateCode"
            />
            <el-table-column label="批号" align="center" prop="lotCode" />
            <el-table-column
              label="入库数量"
              width="80"
              prop="inboundNum"
              align="center"
            />
            <el-table-column
              label="是否入库"
              width="80"
              prop="isInbound"
              align="center"
            >
              <template #default="scope">
                <div>{{ scope.row.isInbound == "1" ? "是" : "否" }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="工号1"
              width="80"
              prop="firstOperatorUserName"
              align="center"
            >
              <template #default="scope">
                <el-button
                  v-if="editStatus"
                  type="primary"
                  link
                  icon="Edit"
                  @click="handleUser(scope.row, 'firstOperator')"
                  >{{ scope.row.firstOperatorUserName }}</el-button
                >
                <div v-else>{{ scope.row.firstOperatorUserName }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="操作者1"
              width="80"
              prop="firstOperatorNickName"
              align="center"
            />
            <el-table-column
              label="工号2"
              width="80"
              prop="secondOperatorUserName"
              align="center"
            >
              <template #default="scope">
                <el-button
                  v-if="editStatus"
                  type="primary"
                  link
                  icon="Edit"
                  @click="handleUser(scope.row, 'secondOperator')"
                  >{{ scope.row.secondOperatorUserName }}</el-button
                >
                <div v-else>{{ scope.row.secondOperatorUserName }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="操作者2"
              width="80"
              prop="secondOperatorNickName"
              align="center"
            />
            <el-table-column
              label="工号3"
              width="80"
              prop="thirdOperatorUserName"
              align="center"
            >
              <template #default="scope">
                <el-button
                  v-if="editStatus"
                  type="primary"
                  link
                  icon="Edit"
                  @click="handleUser(scope.row, 'thirdOperator')"
                  >{{ scope.row.thirdOperatorUserName }}</el-button
                >
                <div v-else>{{ scope.row.thirdOperatorUserName }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="操作者3"
              width="80"
              prop="thirdOperatorNickName"
              align="center"
            />
            <el-table-column
              label="包装形式码"
              width="80"
              prop="packageTypeCode"
              align="center"
            />
            <el-table-column label="备注" prop="remark" align="center">
              <template #default="scope">
                <el-input
                  v-if="editStatus"
                  v-model="scope.row.remark"
                  placeholder="请输入备注"
                />
                <span v-else>{{ scope.row.remark }}</span>
              </template>
            </el-table-column>
            <el-table-column
              v-if="editStatus"
              label="操作"
              align="center"
              fixed="right"
              class-name="small-padding fixed-width"
              width="64"
            >
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  icon="Delete"
                  @click="handleDelete(scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <certificateSearchDialog
      ref="certificateSearchDialogRef"
      @submit="addDetails"
    />
    <person
      ref="personRef"
      :multiple="false"
      :singleSelected="handleUserSingleSelected"
    />
  </el-drawer>
</template>
<script setup>
import {
  addInboundOrder,
  updateInboundOrder,
  getInboundOrder,
  exportInboundOrderPdf,
  setPrint,
  exportCertificateLots,
  inboundAllLot,
} from "@/api/business/inboundOrder";
// import FormDetailsRecycling from "./detailsRecyclingForm";
import certificateSearchDialog from "./certificateSearchDialog";
import person from "@/views/dialog/person.vue";
const personRef = ref(null);
const { proxy } = getCurrentInstance();
const { inbound_type } = proxy.useDict("inbound_type");
const { storage_area } = proxy.useDict("storage_area");
const { product_production_category } = proxy.useDict(
  "product_production_category"
);
import useUserStore from "@/store/modules/user";
import auth from "@/plugins/auth";
/** 父组件传参 */
const props = defineProps({
  getList: {
    type: Function,
    default: () => {},
  },
  deliveryMethod: {
    type: Array,
    default: [],
  },
  settlementType: {
    type: Array,
    default: [],
  },
  packagingMethod: {
    type: Array,
    default: [],
  },
});
const { getList } = toRefs(props);
/** 字典数组区 */
/** 表单抽屉 页变量 */

const loading = ref(false);
const visible = ref(false);
const editStatus = ref(true);
const hasReturnReceiptDetailFlag = ref(true);
const editUser = ref("");
const currentRow = ref(null);
// 创建一个引用来存储最后一次请求的时间戳
const totalCarriersNum = ref(0);
const detailInfo = ref({});
const webHost = import.meta.env.VITE_APP_BASE_API;
const form = ref({
  details: [],
});
const selections = ref([]);
const certificateSearchDialogRef = ref(null);

let submitValue = 0;
const rules = {
  type: [{ required: true, message: "请选择入库类型", trigger: "change" }],
  inboundTime: [{ required: true, message: "请选择入库时间", trigger: "blur" }],
  transferCode: [
    { required: true, message: "请输入转运托盘码", trigger: "blur" },
  ],
  storageArea: [
    { required: true, message: "请选择储存区域", trigger: "change" },
  ],
};

/***********************  方法区  ****************************/
/** 导出按钮操作 */
function handleExport() {
  exportOutsource({ id: form.value.id });
}

/** 打印按钮操作 */
function handlePrint() {
  exportInboundOrderPdf({ id: form.value.id }).then((_) => {
    console.log("已打印完毕");
    setPrint({ id: form.value.id, isPrint: 1 }).then(() => {
      getForm();
      getList.value();
    });
  });
}

/** 打开抽屉 */
function open(row, edit) {
  reset();
  totalCarriersNum.value = 0;
  visible.value = true;
  if (row) {
    editStatus.value = edit ? true : false;
    hasReturnReceiptDetailFlag.value = true;
    console.log(row);
    detailInfo.value = row;
    form.value.id = row.id;
    getForm();
  } else {
    editStatus.value = true;
    hasReturnReceiptDetailFlag.value = true;
    console.log(useUserStore().user);
    form.value.inputUserId = useUserStore().user.userId;
    form.value.inputUserName = useUserStore().user.userName;
    form.value.inputNickName = useUserStore().user.nickName;
    form.value.inboundTime = proxy.moment().format("YYYY-MM-DD HH:mm:ss");
  }
}
/** 查询表单信息  */
function getForm() {
  loading.value = true;
  getInboundOrder(form.value.id).then((response) => {
    form.value = response.data;
    console.log(response.data);
    loading.value = false;
  });
}
//打开历史记录弹窗
function handleViewRecords() {
  proxy.$refs.dialogOutsourcedRecordsRef.open(form.value.id);
}

function selectText(value, data) {
  if (value) {
    return data.filter((item) => item.value == value)[0].label;
  }
}

/** 取消按钮 */
function cancel() {
  visible.value = false;
  reset();
}

const handleDelete = (index) => {
  form.value.details.splice(index, 1);
};

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    tenantId: null,
    formCode: null,
    formDate: proxy.parseTime(new Date(), "{y}-{m}-{d}"),
    supplierId: "0",
    supplierName: "",
    deliveryMethod: "0",
    freightPrice: 0.0,
    freightAmount: 0.0,
    packagingMethod: "0",
    remark: null,
    details: [],
    isSubmit: 0,
    isFirstProcess: 1,
    status: 0,
    isPrint: 0,
  };
  proxy.resetForm("formRef");
}
//5.29保存
function handleSubmit() {
  // 判断是否可以保存
  // 判断是否有数量问题不能入智能区
  proxy.$refs.formRef.validate((valid) => {
    if (valid) {
      if (
        form.value.storageArea == "0" &&
        form.value.details.some((t) => form.value.labelNumber != t.inboundNum)
      ) {
        proxy.$modal.msgError("包装箱内数量与规格不符，不能智能入库");
        return;
      }
      if (!form.value.details || form.value.details.length == 0) {
        proxy.$modal.msgError("请添加产品明细");
        return;
      }
      if (form.value.id == null) {
        addInboundOrder(form.value).then((response) => {
          if (response.code == 200) {
            proxy.$modal.msgSuccess("保存成功");
            visible.value = false;
            getList.value();
          } else {
            proxy.$modal.msgError(response.msg);
          }
        });
      } else {
        updateInboundOrder(form.value).then((response) => {
          if (response.code == 200) {
            proxy.$modal.msgSuccess("保存成功");
            visible.value = false;
            getList.value();
          } else {
            proxy.$modal.msgError(response.msg);
          }
        });
      }
    }
  });
}
function handleSelectionChange(selection) {
  selections.value = selection;
}

function handleAddByCode() {
  const first =
    form.value.id != null
      ? {
          inboundOrderId: form.value.id,
          deptCode: form.value.deptCode,
          deptId: form.value.deptId,
          deptName: form.value.deptName,
          productCode: form.value.productCode,
          packageResourceGroupId: form.value.packageResourceGroupId,
          packageTypeCode: form.value.packageType,
        }
      : form.value.details.length > 0
      ? form.value.details[0]
      : null;
  certificateSearchDialogRef.value.open(first, form.value.id);
}

function addDetails(details) {
  // 假设已选择入库类型为样品入库
  // 判断产品是否为样品 假设不是样品 输出错误
  if (form.value.type == 3 && !details.some((v) => v.productType == "X")) {
    proxy.$modal.msgError("样品入库请添加样品批次");
    return;
  }
  form.value.details.push(
    ...details.filter(
      (v) =>
        !form.value.details.some((t) => t.certificateCode === v.certificateCode)
    )
  );
  if (form.value.details.length > 0) {
    form.value.deptName = form.value.details[0].deptName;
    form.value.packageResourceGroupName =
      form.value.details[0].packageResourceGroupName;
    form.value.packageResourceGroupLineNo =
      form.value.details[0].packageResourceGroupLineNo;
    form.value.deptId = form.value.details[0].deptId;
    form.value.productType = form.value.details[0].productType;
    form.value.isSubclass = form.value.details[0].isSubclass;
    form.value.packageResourceGroupId =
      form.value.details[0].packageResourceGroupId;
    form.value.storageUserId = form.value.details[0].bgyId;
    form.value.storageUserName = form.value.details[0].bgyno;
    form.value.storageNickName = form.value.details[0].bgyna;
    form.value.isSubclass = form.value.details[0].isSubclass;
    form.value.standard = form.value.details[0].standard;
    form.value.drawingNo = form.value.details[0].drawingNo;
    form.value.productDescription = form.value.details[0].productDescription;
    form.value.companyId = form.value.details[0].companyId;
    form.value.companyAlias = form.value.details[0].companyAlias;
    form.value.companyCode = form.value.details[0].companyCode;
    form.value.labelNumber = form.value.details[0].labelNumber;
    form.value.productCode = form.value.details[0].productCode;
    form.value.productId = form.value.details[0].productId;
    form.value.boxNumber = form.value.details.length;
    form.value.inboundTotalNum = 0;
    form.value.deptCode = form.value.details[0].deptCode;
    form.value.details.forEach((item) => {
      form.value.inboundTotalNum += Number(item.inboundNum);
    });
    form.value.unit = "支";
    form.value.packageType = form.value.details[0].packageTypeCode;
    // 判断包装箱的areaType,"Manual字符-- 人工区；Automatic字符代表智能区
    if (form.value.details[0].areaType) {
      if (form.value.details[0].areaType == "Manual") {
        form.value.storageArea = "1";
      } else if (form.value.details[0].areaType == "Automatic") {
        form.value.storageArea = "0";
      }
    }
    // 假设默认每箱支数和实际不符则不能智能入库
    if (form.value.details.some((t) => form.value.labelNumber != t.inboundNum))
      form.value.storageArea = "1";
    if (form.value.details.some((t) => t.productType == "X")) {
      form.value.type = 3;
      form.value.storageArea = "1";
    }
  }
}

function checkDisabled(item) {
  // 判断是样品入库不能入智能区
  // 判断数量不符不能入智能区
  if (item.value == "0") {
    return (
      form.value.type == 3
      // ||
      // form.value.details.some(t => form.value.labelNumber != t.inboundNum)
    );
  } else {
    return false;
  }
}

function checkDisabledForType(item) {
  if (item.value == 3) {
    return (
      form.value.details.length > 0 &&
      !form.value.details.some((t) => t.productType == "X")
    );
  } else {
    return form.value.details.some((t) => t.productType == "X");
  }
}

function handleEdit() {
  editStatus.value = !editStatus.value;
}

function cancelEdit() {
  editStatus.value = false;
  getForm();
}

function checkEdit() {
  // 未打印 判断权限
  // 已打印 判断权限
  // 已出库 不可编辑
  if (form.value.status >= 1) {
    return false;
  } else if (form.value.isPrint == 1) {
    if (auth.hasPermi("business:inboundOrder:francise:edit")) {
      return true;
    } else {
      return false;
    }
  } else if (auth.hasPermi("business:inboundOrder:edit")) {
    return true;
  }
  return false;
}

function handleInbound() {
  // 确认是否全部入库
  proxy
    .$confirm("是否确认全部入库？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(() => {
      inboundAllLot(form.value).then((res) => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess("操作成功");
          getForm();
          getList.value();
        }
      });
    });
}

function handlePrintCertificate() {
  // console.log()
  exportCertificateLots({
    ids: selections.value.map((item) => item.certificateLotId),
  });
}

function handleUser(row, field) {
  editUser.value = field;
  const userInfo = { deptId: form.value.deptId };
  currentRow.value = row;
  proxy.$refs.personRef.open(userInfo);
}

function handleUserSingleSelected(info) {
  currentRow.value[editUser.value + "UserId"] = info.userId;
  currentRow.value[editUser.value + "UserName"] = info.userName;
  currentRow.value[editUser.value + "NickName"] = info.nickName;
  console.log(currentRow.value);
  console.log(editUser.value);
}

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