<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 type="primary" icon="Finished" @click="submitForm">
            确认收回
          </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" v-model="form.formDate" type="date" value-format="YYYY-MM-DD"
                :clearable="false" style="width: 100%">
              </el-date-picker>
              <el-input v-model="form.formDate" v-else readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="外协商名称" prop="supplierName">
              <el-input v-if="editStatus" v-model="form.supplierName" readonly placeholder="请输入外协商名称">
                <template #append>
                  <el-button icon="Search" @click="handleShowDialogSuppliers" />
                </template>
              </el-input>
              <span v-else>{{ form.supplierName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注" prop="remark">
              <el-input v-model.trim="form.remark" v-if="editStatus" />
              <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="form.supplierName != ''" :disabled="!editStatus"
          @click="handleShowDialogOutSourceDetails">
          添加收回明细
        </el-button>
        <el-button type="primary" icon="Check" :disabled="ids && ids.length == 0" @click="handlePass">批量审核</el-button>
        <el-button type="danger" icon="Close" :disabled="ids && ids.length == 0" @click="handleFail">批量取消审核</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" width="48" align="center" :selectable="handleAllowSelected" />
            <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="originalCarrier"
              width="320"
            /> -->
            <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="200" />
            <el-table-column label="收回数量" align="center" prop="receiptNum" width="104" />
            <el-table-column label="确定数量" align="center" prop="auditNum" width="104">
              <template #default="scope">
                <el-input-number v-if="scope.row.productionDeptId == 0" v-model="scope.row.auditNum" :min="0"
                  controls-position="right" style="text-align: center" />
                <el-input v-model="scope.row.auditNum" v-else readonly />
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark">
              <template #default="scope">
                <el-input v-model.trim="scope.row.remark" v-if="editStatus" />
                <el-input v-model="scope.row.remark" v-else readonly />
              </template>
            </el-table-column>
            <el-table-column label="审核状态" align="center" prop="status" width="200">
              <template #default="scope">
                <el-switch v-model="scope.row.status" style="
                    --el-switch-on-color: #13ce66;
                    --el-switch-off-color: #ff4949;
                  " :active-value="1" :inactive-value="0" active-text="已审核" inactive-text="未审核"
                  :disabled="scope.row.productionDeptId != 0 || (scope.row.isApproved === 0 && scope.row.processInspecionList && scope.row.processInspecionList.length > 0) || scope.row.isProvedForCheck === 1 || scope.row.isCheckout === 1"
                  @change="handleChangeAuditStatus(scope.row)" />
              </template>
            </el-table-column>
            <el-table-column label="反选" align="center" width="100">
              <template #default="scope">
                <el-button
                  :disabled="scope.row.productionDeptId != 0 || (scope.row.isApproved === 0 && scope.row.processInspecionList && scope.row.processInspecionList.length > 0) || scope.row.isProvedForCheck === 1 || scope.row.isCheckout === 1"
                  icon="delete" link type="danger" @click="handleDelReturnReceiveDetail(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <!-- 收回明细选择 -->
    <dialog-outsource-details ref="dialogOutsourceDetailsRef"
      :multiple-selected="handleMultipleSelectedOutsourceDetails" />
    <!-- 外协商选择 -->
    <dialog-suppliers ref="dialogSuppliersRef" :single-selected="handleSingleSelectedSuppliers" />
  </el-drawer>
</template>
<script setup>
import {
  getReceipt,
  addReceipt,
  updateReceipt,
  checkFurnace
} from "@/api/business/returnReceipt";
import { getP2NeedCheckProcess } from '@/api/business/p2'
import dialogOutsourceDetails from "./DialogOutsourceDetails";
import dialogSuppliers from "./DialogSuppliers";
const emit = defineEmits(["handleSaveSuccess"]);
const { proxy } = getCurrentInstance();
/** 表单抽屉 页变量 */
const loading = ref(false);
const visible = ref(false);
const editStatus = ref(false);
const processList = ref([])
const ids = ref([])
const selected = ref([])
const webHost = import.meta.env.VITE_APP_BASE_API;
const form = ref({});

/****************************  方法区  ****************************/
/** 打开抽屉 */
const open = (row) => {
  reset();
  visible.value = true;
  getP2NeedCheck()
  if (row) {
    loading.value = true;
    editStatus.value = row.editStatus;
    getReceipt(row.id).then((response) => {
      form.value = response.data;
      loading.value = false;
    });
  } else {
    editStatus.value = true;
  }
};

/** 取消按钮 */
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: []
  };
  proxy.resetForm("formRef");
};
/***************************** 外协商对话框相关 *****************************/
//打开外协商选择对话框
const handleShowDialogSuppliers = () => {
  proxy.$refs.dialogSuppliersRef.open();
};
//外协商选择带回
const handleSingleSelectedSuppliers = (selection) => {
  console.log(selection);
  //如果收回明细已存在，切换外协商名字，删除添加的收回明细
  if (selection.id != form.value.supplierId && form.value.details.length > 0) {
    form.value.details = [];
  }
  form.value.supplierId = selection.id;
  form.value.supplierName = selection.name;
};
/***************************** 外协明细对话框相关 *****************************/
// 打开外协明细选择对话框
const handleShowDialogOutSourceDetails = () => {
  var info = {};
  info.outsourceDetailIds = form.value.details.map(
    (item) => item.outsourceDetailId
  );
  info.supplierId = form.value.supplierId;
  proxy.$refs.dialogOutsourceDetailsRef.open(info);
};
function handlePass() {
  form.value.details.forEach(item => {
    ids.value.forEach(id => {
      if (item.outsourceDetailId == id) {
        item.status = 1
      }
    });
  });
}
function handleFail() {
  form.value.details.forEach(item => {
    ids.value.forEach(id => {
      if (item.outsourceDetailId == id) {
        item.status = 0
      }
    });
  });
}
// 外协明细选择带回
const handleMultipleSelectedOutsourceDetails = (selection) => {
  for (let i = 0; i < selection.length; i++) {
    for (let j = 0; j < selection[i].processes.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].processes[j].qualifiedNum
          ? selection[i].processes[j].qualifiedNum
          : 0,
        originalCarrier: selection[i].originalCarrier,
        originalCarrierCount: selection[i].originalCarrierCount,
        newCarrier: selection[i].newCarrier,
        newCarrierCount: selection[i].newCarrierCount,
        processNames: selection[i].processNames,
        remark: "",
        technologicalProcessId:
          selection[i].processes[j].technologicalProcessId,
        technologyVersion: selection[i].processes[j].technologyVersion,
        technologicalProcessDetailId:
          selection[i].processes[j].technologicalProcessDetailId,
        processId: selection[i].processes[j].processId,
        processAlias: selection[i].processes[j].processAlias,
        processCode: selection[i].processes[j].processCode,
        processStepNumber: selection[i].processes[j].processStepNumber,
        productionDeptId: selection[i].productionDeptId,
        status: 0,
        auditNum: 0,
      };
      console.log(newDetail)
      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].processes[selection[i].processes.length - 1].qualifiedNum
          ? selection[i].processes[selection[i].processes.length - 1].qualifiedNum
          : 0,
      newCarrier: selection[i].newCarrier,
      remark: "",
      processAlias: selection[i].processNames,
      productionDeptId: selection[i].productionDeptId,
      status: 0,
      auditNum: 0,
    };
    console.log(detail)
    form.value.details.push(detail);
  }
};
//审核状态按钮
function handleChangeAuditStatus(row) {
  console.log(row);
}
/**复选框选中数据 */
function handleSelectionChange(selection) {
  selected.value = selection
  console.log(selection)
  ids.value = selection.map((item) => item.outsourceDetailId);
  console.log(ids.value)
}
function handleAllowSelected(row) {

  return !(row.productionDeptId != 0 || (row.isApproved === 0 && row.processInspecionList && row.processInspecionList.length > 0) || row.isProvedForCheck === 1 || row.isCheckout === 1)
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate(async (valid) => {
    if (valid) {
      var flag = true;
      var confirmFlag = false;
      for (let i = 0; i < form.value.details.length; i++) {
        var tempList = form.value.details.filter((item) => {
          return item.lotId == form.value.details[i].lotId;
        });
        //如果外协填入收回数量，则判断确定数量不能大于收回数量
        // if (form.value.details[i].receiptNum > 0) {
        // 	if (form.value.details[i].auditNum > form.value.details[i].receiptNum) {
        // 		flag = false
        // 		proxy.$modal.msgError('第' + (i + 1) + '行确定数量不能大于收回数量')
        // 	}
        // } else {
        //外协没填收回数量
        //外协没填收回数量，第一行工序确定数量不能超过产品数量，第二行工序确定数量不能超过上一道序的确定数量
        var index = tempList.indexOf(form.value.details[i]);
        // if (index > 0 && form.value.details[i].auditNum > tempList[index - 1].auditNum) {
        // 	flag = false
        // 	proxy.$modal.msgError('第' + (i + 1) + '行确定数量不能超过上一道序的确定数量')
        // }
        // if (form.value.details[i].auditNum > form.value.details[i].productNum) {
        // 	flag = false
        // 	proxy.$modal.msgError('第' + (i + 1) + '行确定数量不能大于产品数量' + form.value.details[i].productNum)
        // }
        // }
        if (form.value.details[i].auditNum == 0) {
          flag = false
          proxy.$modal.msgError('第' + (i + 1) + '行确定数量不能为0')
          // confirmFlag = true;
        }
      }
      if (form.value.details.length == 0) {
        flag = false;
        proxy.$modal.msgError("收回明细不能为空");
      }

      if (form.value.id == null && form.value.details.findIndex(v => (v.newCarrier == null || v.newCarrier == '')) >= 0) {
        console.log(form.value.details)
        flag = false
        proxy.$modal.msgError("收回明细中载具箱号不能为空")
      }

      // 判断是否按炉结算
      const checkRes = await checkFurnace(form.value.details);
      if (!checkRes.data) {
        flag = false
        proxy.$modal.msgError(checkRes.msg)
      }
      if (flag) {
        //赋值(因为收回明细是一个批次一条，所以后端传回来两个集合，一个页面显示，一个后端保存)
        handleSetAuditStatus();
        // if (confirmFlag) {
        //   proxy.$modal
        //     .confirm("存在填写确定数量为0的工序，确定要收回吗？")
        //     .then(function () {
        //       form.value.processes = processList.value
        //       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");
        //         });
        //       }
        //     })
        //     .catch((error) => {
        //       proxy.$modal.msg("取消确认");
        //     });
        // } else {
        form.value.processes = processList.value
        if (form.value.id != null) {
          console.log(form.value);
          updateReceipt(form.value).then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            visible.value = false;
            emit("handleSaveSuccess");
          });
        } else {
          console.log(form.value);
          addReceipt(form.value).then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            visible.value = false;
            emit("handleSaveSuccess");
          });
        }
      }
    }
    // }
  });
}
//反选操作
function handleDelReturnReceiveDetail(row) {
  console.log(row);
  if (form.value.id) {
    if (row.productionDeptId != 0) {
      proxy.$modal.msgError("该批次已外协序检或已周转，不能删除");
    } else {
      proxy.$modal
        .confirm(
          "是否确认删除选中的数据项,如果删除，同时删除该批次下所有工序？"
        )
        .then(function () {
          form.value.details = form.value.details.filter((item) => {
            return item.lotCode != row.lotCode;
          });
          //修改存进数据库的数据
          let 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);
          }
        });
    }
  } else {
    form.value.details.splice(form.value.details.indexOf(row), 1);
    //修改存进数据库的数据
    let 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);
    }
  }
  console.log(form.value)
}
//审核状态，备注，确定数量赋值
function handleSetAuditStatus() {
  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;
        element.status = form.value.details[i].status;
        element.auditNum = form.value.details[i].auditNum;
      }
    });
  }
}

function getP2NeedCheck() {
  getP2NeedCheckProcess("Y").then(res => {
    processList.value = res.rows.map(v => v.prcode.trim())
  })
}
/** 暴露给父组件的方法 */
defineExpose({
  open,
});
</script>
