<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="表单编号" prop="formCode">
              <el-input v-model="queryParams.formCode" placeholder="请输入表单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工程名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入工程名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="材料名称" prop="materialName">
              <el-input v-model="queryParams.materialName" placeholder="请输入设备材料名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订货单位" prop="orderingUnit">
              <el-input v-model="queryParams.orderingUnit" placeholder="请输入订货单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供货单位" prop="supplierUnit">
              <el-input v-model="queryParams.supplierUnit" placeholder="请输入供货单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="领料单位" prop="issueUnit">
              <el-input v-model="queryParams.issueUnit" placeholder="请输入领料单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="保管单位" prop="storageUnit">
              <el-input v-model="queryParams.storageUnit" placeholder="请输入保管单位" clearable @keyup.enter="handleQuery" />
            </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>
        </el-card>
      </div>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['materials:materialIssue:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['materials:materialIssue:remove']"
              >删除</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="materialIssueList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="表单编号" align="center" prop="formCode" />
        <el-table-column label="工程名称" align="center" prop="projectName" />
        <el-table-column label="设备材料名称" align="center" prop="materialName" />
        <el-table-column label="订货单位" align="center" prop="orderingUnit" />
        <el-table-column label="供货单位" align="center" prop="supplierUnit" />
        <el-table-column label="领料单位" align="center" prop="issueUnit" />
        <el-table-column label="保管单位" align="center" prop="storageUnit" />
        <el-table-column label="缺陷情况" align="center" prop="defectDescription" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['materials:materialIssue:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['materials:materialIssue:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="dialog.title"
      v-model="dialog.visible"
      width="800px"
      append-to-body
    >
      <el-form ref="materialIssueFormRef" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="表单编号" prop="formCode">
              <el-input v-model="form.formCode" placeholder="请输入表单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入工程名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备材料名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入设备材料名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订货单位" prop="orderingUnit">
              <el-input v-model="form.orderingUnit" placeholder="请输入订货单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供货单位" prop="supplierUnit">
              <el-input v-model="form.supplierUnit" placeholder="请输入供货单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领料单位" prop="issueUnit">
              <el-input v-model="form.issueUnit" placeholder="请输入领料单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保管单位" prop="storageUnit">
              <el-input v-model="form.storageUnit" placeholder="请输入保管单位" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="缺陷情况" prop="defectDescription">
              <el-input v-model="form.defectDescription" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div class="detail">
              <div class="detail-header">
                <span>数量验收</span>
                <el-button type="primary" link @click="addItem" icon="Plus">添加一行</el-button>
              </div>
              <div v-for="(item, index) in form.itemList" :key="index" class="detail-item">
                <el-row>
                  <el-col :span="12">
                    <el-form-item
                      :label="index === 0 ? '名称' : ''"
                      :prop="`itemList.${index}.name`"
                      :rules="[{ required: true, message: '名称不能为空', trigger: 'blur' }]"
                    >
                      <el-input v-model="item.name" placeholder="请输入名称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      :label="index === 0 ? '规格' : ''"
                      :prop="`itemList.${index}.specification`"
                      :rules="[{ required: true, message: '规格不能为空', trigger: 'blur' }]"
                    >
                      <el-input v-model="item.specification" placeholder="请输入规格" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      :label="index === 0 ? '单位' : ''"
                      :prop="`itemList.${index}.unit`"
                      :rules="[{ required: true, message: '单位不能为空', trigger: 'blur' }]"
                    >
                      <el-input v-model="item.unit" placeholder="请输入单位" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      :label="index === 0 ? '库存' : ''"
                      :prop="`itemList.${index}.stockQuantity`"
                      :rules="[{ required: true, message: '库存不能为空', trigger: 'blur' }]"
                    >
                      <el-input v-model="item.stockQuantity" placeholder="请输入库存" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      :label="index === 0 ? '领取' : ''"
                      :prop="`itemList.${index}.issuedQuantity`"
                      :rules="[{ required: true, message: '领取数量不能为空', trigger: 'blur' }]"
                    >
                      <el-input v-model="item.issuedQuantity" placeholder="请输入领取数量" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      :label="index === 0 ? '剩余' : ''"
                      :prop="`itemList.${index}.remainingQuantity`"
                      :rules="[{ required: true, message: '剩余数量不能为空', trigger: 'blur' }]"
                    >
                      <el-input v-model="item.remainingQuantity" placeholder="请输入剩余数量" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item :label="index === 0 ? '备注' : ''" prop="remark">
                      <el-input v-model="item.remark" placeholder="请输入内容" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12" v-if="form.itemList.length > 1">
                    <div class="item-actions">
                      <el-button type="danger" link @click="removeItem(index)" icon="Delete">删除</el-button>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合格证文件" prop="certCountFileId">
              <file-upload :isShowTip="false" v-model="form.certCountFileId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出厂报告文件" prop="reportCountFileId">
              <file-upload :isShowTip="false" v-model="form.reportCountFileId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="技术资料文件" prop="techDocCountFileId">
              <file-upload :isShowTip="false" v-model="form.techDocCountFileId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="厂家资质文件" prop="licenseCountFileId">
              <file-upload :isShowTip="false" v-model="form.licenseCountFileId" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <span style="color: #ff0000ab; margin-bottom: 10px; display: block"
              >注意：请上传doc/xls/ppt/txt/pdf/png/jpg/jpeg/zip格式文件</span
            > </el-col
          ><el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <wordllssue ref="wordllssueRef"></wordllssue>
  </div>
</template>

<script setup name="MaterialIssue" lang="ts">
import { listMaterialIssue, getMaterialIssue, delMaterialIssue, addMaterialIssue, updateMaterialIssue } from '@/api/materials/materialIssue';
import { MaterialIssueVO, MaterialIssueQuery, MaterialIssueForm } from '@/api/materials/materialIssue/types';
import { useUserStoreHook } from '@/store/modules/user';
import wordllssue from './word/index.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);

const materialIssueList = ref<MaterialIssueVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const wordllssueRef = ref<InstanceType<typeof wordllssue>>();
const queryFormRef = ref<ElFormInstance>();
const materialIssueFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const getInitFormData = () => {
  return {
    id: undefined,
    projectId: currentProject.value?.id,
    materialSource: '2',
    formCode: undefined,
    projectName: undefined,
    materialName: undefined,
    orderingUnit: undefined,
    supplierUnit: undefined,
    issueUnit: undefined,
    storageUnit: undefined,
    defectDescription: undefined,
    certCount: undefined,
    certCountFileId: undefined,
    reportCount: undefined,
    reportCountFileId: undefined,
    techDocCount: undefined,
    techDocCountFileId: undefined,
    licenseCount: undefined,
    licenseCountFileId: undefined,
    remark: undefined,
    itemList: [
      {
        id: undefined,
        specification: undefined,
        unit: undefined,
        stockQuantity: undefined,
        issuedQuantity: undefined,
        remainingQuantity: undefined,
        name: undefined,
        remark: undefined
      }
    ]
  };
};
const initFormData: MaterialIssueForm = {};
const data = reactive<PageData<MaterialIssueForm, MaterialIssueQuery>>({
  form: getInitFormData(),
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProject.value?.id,
    materialSource: '2',
    formCode: undefined,
    projectName: undefined,
    materialName: undefined,
    orderingUnit: undefined,
    supplierUnit: undefined,
    issueUnit: undefined,
    storageUnit: undefined,
    defectDescription: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键id不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询物料领料单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMaterialIssue(queryParams.value);
  materialIssueList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

/** 表单重置 */
const reset = () => {
  form.value = getInitFormData();
  materialIssueFormRef.value?.resetFields();
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: MaterialIssueVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加物料领料单';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: MaterialIssueVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getMaterialIssue(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改物料领料单';
};

/** 提交按钮 */
const submitForm = () => {
  materialIssueFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateMaterialIssue(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addMaterialIssue(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

// 添加数量验收条目
const addItem = () => {
  form.value.itemList.push({
    id: undefined,
    specification: undefined,
    unit: undefined,
    stockQuantity: undefined,
    issuedQuantity: undefined,
    remainingQuantity: undefined,
    name: undefined,
    remark: undefined
  });
};

// 删除数量验收条目
const removeItem = (index: number) => {
  if (form.value.itemList.length > 1) {
    form.value.itemList.splice(index, 1);
  } else {
    proxy?.$modal.msgWarning('至少需要保留一条数量验收记录');
  }
};
/** 删除按钮操作 */
const handleDelete = async (row?: MaterialIssueVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除物料领料单编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delMaterialIssue(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
const handleView = (row) => {
  // 查看详情
  wordllssueRef.value?.openDialog(row);
};
onMounted(() => {
  getList();
});
</script>
<style scoped lang="scss">
.detail {
  border-bottom: 1px solid #ececec;
  border-top: 1px solid #ececec;
  margin: 10px 0;
  padding: 10px 0;

  &-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    font-weight: bold;
    color: #1eaaff;
  }

  &-item {
    padding: 10px;
    margin-bottom: 15px;
    border-radius: 4px;
    background-color: #f8f9fa;
    position: relative;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.item-actions {
  display: flex;
  justify-content: flex-end;
  padding-top: 6px;
}
</style>
