<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-group>
          <el-button v-if="editStatus && submitStatus" type="success" @click="saveForm">
            保存
          </el-button>
          <el-button v-if="editStatus && submitStatus" type="primary" @click="submitForm">
            提交
          </el-button>
          <el-button v-if="!editStatus" type="primary" icon="Finished" @click="cancel">
            确定
          </el-button>
        </el-button-group>

        <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" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据号" prop="formCode">
              <el-input v-model="form.formCode" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="表单日期" prop="formDate">
              <el-date-picker v-if="editStatus && submitStatus" v-model="form.formDate" type="date"
                value-format="YYYY-MM-DD" style="width: 100%">
              </el-date-picker>
              <el-input v-model="form.formDate" v-else readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model.trim="form.remark" v-if="editStatus && submitStatus" />
              <el-input v-model="form.remark" v-else readonly />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 渲染数据区 -->
      <div class="form-details-btns-container">
        <el-button type="primary" icon="Plus" v-if="editStatus && submitStatus"
          @click="handleShowDialogOutSourceDetails">
          添加收回明细
        </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%">
            <el-table-column label="行号" type="index" align="center" width="48" />
            <el-table-column label="批次号" align="center" prop="lotCode" width="104" />
            <el-table-column label="产品描述" align="center" prop="productDescription" width="320" />
            <el-table-column label="产品数量" align="center" prop="productNum" width="96" />
            <el-table-column label="箱号" align="center" prop="newCarrier" width="320">
              <template #default="scope">
                {{ scope.row.newCarrier }} {{ scope.row.unbind == 1 ? "(已解绑)" : "" }}
              </template>
            </el-table-column>
            <el-table-column label="外协工序" align="center" prop="processAlias" width="320" />
            <el-table-column label="收回数量" align="center" prop="receiptNum" width="104" />
            <el-table-column label="备注" align="center" prop="remark">
              <template #default="scope">
                <el-input v-model.trim="scope.row.remark" v-if="editStatus && submitStatus" />
                <el-input v-model="scope.row.remark" v-else readonly />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="64">
              <template #default="scope">
                <el-button v-if="editStatus && submitStatus" link type="danger" icon="Delete"
                  @click="handleDeletedDetails(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 外协商选择 -->
    <dialog-outsource-details ref="dialogOutsourceDetailsRef"
      :multiple-selected="handleMultipleSelectedOutsourceDetails" />
  </el-drawer>
</template>
<script setup>
import {
  getReceipt,
  addReceipt,
  updateReceipt,
  checkFurnace
} from "@/api/business/returnReceipt";
import dialogOutsourceDetails from "./DialogOutsourceDetails";
import { getTenant } from "@/utils/auth";
const emit = defineEmits(["handleSaveSuccess"]);
const { proxy } = getCurrentInstance();
/** 表单抽屉 页变量 */
const loading = ref(false);
const visible = ref(false);
const editStatus = ref(true);
const submitStatus = ref(true);
const webHost = import.meta.env.VITE_APP_BASE_API;
const form = ref({});

/****************************  方法区  ****************************/
/** 打开抽屉 */
const open = (row) => {
  reset();
  visible.value = true;
  if (row) {
    editStatus.value = row.editStatus == false ? row.editStatus : true;
    submitStatus.value = row.isSubmit == 0 ? true : false;
    loading.value = true;
    getReceipt(row.id).then((response) => {
      form.value = response.data;
      console.log(form.value)
      loading.value = false;
    });
  } else {
    form.value.supplierName = getTenant().tenantName;
    form.value.category = 1
  }
};

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

/** 表单重置 */
const reset = () => {
  form.value = {
    id: null,
    formCode: "",
    formDate: proxy.parseTime(new Date(), "{y}-{m}-{d}"),
    supplierId: "0",
    supplierName: "",
    remark: "",
    details: [],
    detailInfo: [],
  };
  editStatus.value = true
  submitStatus.value = true
  proxy.resetForm("formRef");
};
/***************************** 外协明细对话框相关 *****************************/
// 打开外协明细选择对话框
const handleShowDialogOutSourceDetails = () => {
  const outsourceDetailIds =
    form.value.details && form.value.details.length > 0
      ? form.value.details.map((item) => item.outsourceDetailId)
      : [];
  proxy.$refs.dialogOutsourceDetailsRef.open(outsourceDetailIds);
};
// 外协明细选择带回
const handleMultipleSelectedOutsourceDetails = (selection) => {
  for (let i = 0; i < selection.length; i++) {
    // console.log(selection[i])
    for (
      let j = 0;
      j < selection[i].outsourcedOrderDetailProcessList.length;
      j++
    ) {
      //存进数据库的内容
      const newDetail = {
        outsourceDetailId: selection[i].id,
        productDescription: selection[i].productDescription,
        lotCode: selection[i].lotCode,
        lotId: selection[i].lotId,
        dayworkId: selection[i].dayworkId,
        productId: selection[i].productId,
        productNum: selection[i].productNum,
        receiptNum:
          selection[i].outsourcedOrderDetailProcessList[j].qualifiedNum,
        originalCarrier: selection[i].originalCarrier,
        originalCarrierCount: selection[i].originalCarrierCount,
        newCarrier: selection[i].newCarrier,
        newCarrierCount: selection[i].newCarrierCount,
        processNames: selection[i].processNames,
        remark: "",
        technologicalProcessId:
          selection[i].outsourcedOrderDetailProcessList[j]
            .technologicalProcessId,
        technologyVersion:
          selection[i].outsourcedOrderDetailProcessList[j].technologyVersion,
        technologicalProcessDetailId:
          selection[i].outsourcedOrderDetailProcessList[j]
            .technologicalProcessDetailId,
        processId: selection[i].outsourcedOrderDetailProcessList[j].processId,
        processAlias:
          selection[i].outsourcedOrderDetailProcessList[j].processAlias,
        processCode:
          selection[i].outsourcedOrderDetailProcessList[j].processCode,
        processStepNumber:
          selection[i].outsourcedOrderDetailProcessList[j].processStepNumber,
        unbind: selection[i].unbind
      };
      form.value.detailInfo.push(newDetail);
    }
    //页面显示内容，一个批次一行
    const detail = {
      outsourceDetailId: selection[i].id,
      productDescription: selection[i].productDescription,
      lotCode: selection[i].lotCode,
      productNum: selection[i].productNum,
      receiptNum:
        selection[i].outsourcedOrderDetailProcessList[
          selection[i].outsourcedOrderDetailProcessList.length - 1
        ].qualifiedNum,
      newCarrier: selection[i].newCarrier,
      remark: "",
      processAlias: selection[i].processNames,
      unbind: selection[i].unbind
    };
    form.value.details.push(detail);
  }
};

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate(async (valid) => {
    if (valid) {
      var flag = true;
      if (form.value.details.length == 0) {
        flag = false;
        proxy.$modal.msgError("收回明细不能为空");
      }
      // if (form.value.details.findIndex(v => v.newCarrier == null || v.newCarrier == '') >= 0) {
      //   flag = false
      //   proxy.$modal.msgError("收回明细中载具箱号不能为空")
      // }
      // for (let i = 0; i < form.value.details.length; i++) {
      // 	if (form.value.details[i].receiptNum <= 0) {
      // 		flag = false;
      // 		proxy.$modal.msgError("第" + (i + 1) + "行收回数量应大于0");
      // 		return;
      // 	}
      // 	}

      // 判断是否按炉结算
      const checkRes = await checkFurnace(form.value.details);
      if (!checkRes.data) {
        flag = false
        proxy.$modal.msgError(checkRes.msg)
      }
      if (flag) {
        form.value.isSubmit = 1;
        form.value.submitTime = proxy.moment().format("YYYY-MM-DD HH:mm:ss");
        handleChangeRemark();
        if (form.value.id != null) {
          updateReceipt(form.value).then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            visible.value = false;
            emit("handleSaveSuccess");
          });
        } else {
          addReceipt(form.value).then((response) => {
            proxy.$modal.msgSuccess("提交成功");
            visible.value = false;
            emit("handleSaveSuccess");
          });
        }
      }
    }
  });
}
/** 保存按钮 */
function saveForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      var flag = true;
      if (form.value.details.length == 0) {
        flag = false;
        proxy.$modal.msgError("收回明细不能为空");
      }
      // if (form.value.details.findIndex(v => v.newCarrier == null || v.newCarrier == '') >= 0) {
      //   flag = false
      //   proxy.$modal.msgError("收回明细中载具箱号不能为空")
      // }
      if (flag) {
        form.value.isSubmit = 0;
        handleChangeRemark();
        if (form.value.id != null) {
          updateReceipt(form.value).then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            visible.value = false;
            emit("handleSaveSuccess");
          });
        } else {
          addReceipt(form.value).then((response) => {
            proxy.$modal.msgSuccess("保存成功");
            visible.value = false;
            emit("handleSaveSuccess");
          });
        }
      }
    }
  });
}
//添加备注
function handleChangeRemark() {
  for (let i = 0; i < form.value.details.length; i++) {
    form.value.detailInfo.forEach((element) => {
      if (form.value.details[i].lotCode == element.lotCode) {
        element.remark = form.value.details[i].remark;
      }
    });
  }
}

//删除收回明细
function handleDeletedDetails(row) {
  //前端同时操作form.value的两个集合
  form.value.details.splice(form.value.details.indexOf(row), 1);
  var index = []
  for (let i = 0; i < form.value.detailInfo.length; i++) {
    if (form.value.detailInfo[i].lotCode == row.lotCode) {
      index.push(i)
    }
  }
  for (let i = index.length - 1; i >= 0; i--) {
    form.value.detailInfo.splice(index[i], 1);
  }
}

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