<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="materialsName">
              <el-input v-model="queryParams.materialsName" 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="warning" plain icon="Download" @click="handleExport" v-hasPermi="['materials:materialsInventory:export']">
              导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="materialsInventoryList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="材料名称" align="center" prop="materialsVo.materialsName" />
        <el-table-column label="入库登记" align="center">
          <el-table-column label="数量" align="center" prop="number">
            <template #default="scope">
              <span v-if="scope.row.outPut === '0'">{{ scope.row.number }}</span>
              <span v-else></span>
            </template>
          </el-table-column>
          <el-table-column label="签收人" align="center" prop="operator">
            <template #default="scope">
              <span v-if="scope.row.outPut === '0'">{{ scope.row.operator }}</span>
              <span v-else></span>
            </template>
          </el-table-column>
          <el-table-column label="日期" align="center" prop="outPutTime" width="160">
            <template #default="scope">
              <span v-if="scope.row.outPut === '0'">{{ parseTime(scope.row.outPutTime, '{y}年{m}月{d}日') }}</span>
              <span v-else></span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="出库登记" align="center">
          <el-table-column label="交接单位" align="center" prop="recipient" />
          <el-table-column label="数量" align="center" prop="number">
            <template #default="scope">
              <span v-if="scope.row.outPut === '1'">{{ scope.row.number }}</span>
              <span v-else></span>
            </template>
          </el-table-column>
          <el-table-column label="出库人" align="center" prop="operator">
            <template #default="scope">
              <span v-if="scope.row.outPut === '1'">{{ scope.row.operator }}</span>
              <span v-else></span>
            </template>
          </el-table-column>
          <el-table-column label="领用人" align="center" prop="shipper" />
          <el-table-column label="日期" align="center" prop="outPutTime" width="160">
            <template #default="scope">
              <span v-if="scope.row.outPut === '1'">{{ parseTime(scope.row.outPutTime, '{y}年{m}月{d}日') }}</span>
              <span v-else></span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="剩余处理" align="center">
          <el-table-column label="剩余量" align="center" prop="residue" />
          <el-table-column label="处理方式" align="center" prop="disposition" />
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-space wrap>
              <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['materials:materialsInventory:edit']">
                修改
              </el-button>
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['materials:materialsInventory:remove']">
                删除
              </el-button>
            </el-space>
          </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 :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="materialsInventoryFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="出入库状态" prop="outPut">
          <el-select v-model="form.outPut" clearable placeholder="请输入出入库状态">
            <el-option v-for="item in out_put_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="出/入库的数量" prop="number">
          <el-input v-model="form.number" placeholder="请输入出/入库的数量" />
        </el-form-item>
        <el-form-item label="出/入库操作时间" prop="outPutTime">
          <el-date-picker clearable v-model="form.outPutTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择出/入库操作时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="剩余库存数量" prop="residue">
          <el-input v-model="form.residue" placeholder="请输入剩余库存数量" />
        </el-form-item>
        <el-form-item label="操作人" prop="operator">
          <el-input v-model="form.operator" placeholder="请输入操作人" />
        </el-form-item>
        <el-form-item label="材料出入证明" prop="path">
          <el-input v-model="form.path" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="处理方式" prop="disposition">
          <el-input v-model="form.disposition" placeholder="请输入处理方式" />
        </el-form-item>
        <el-form-item label="交接单位" prop="recipient">
          <el-input v-model="form.recipient" placeholder="请输入交接单位" />
        </el-form-item>
        <el-form-item label="领用人" prop="shipper">
          <el-input v-model="form.shipper" placeholder="请输入领用人" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </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>
  </div>
</template>

<script setup name="MaterialsInventory" lang="ts">
import {
  addMaterialsInventory,
  delMaterialsInventory,
  getMaterialsInventory,
  listMaterialsInventory,
  updateMaterialsInventory
} from '@/api/materials/materialsInventory';
import { MaterialsInventoryForm, MaterialsInventoryQuery, MaterialsInventoryVO } from '@/api/materials/materialsInventory/types';
import { useUserStoreHook } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { out_put_type } = toRefs<any>(proxy?.useDict('out_put_type'));

// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const materialsInventoryList = ref<MaterialsInventoryVO[]>([]);
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 queryFormRef = ref<ElFormInstance>();
const materialsInventoryFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: MaterialsInventoryForm = {
  id: undefined,
  materialsId: undefined,
  projectId: currentProject.value.id,
  outPut: undefined,
  number: undefined,
  outPutTime: undefined,
  residue: undefined,
  operator: undefined,
  path: undefined,
  disposition: undefined,
  recipient: undefined,
  shipper: undefined,
  remark: undefined
};
const data = reactive<PageData<MaterialsInventoryForm, MaterialsInventoryQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    materialsId: undefined,
    projectId: currentProject.value.id,
    outPut: undefined,
    number: undefined,
    outPutTime: undefined,
    residue: undefined,
    operator: undefined,
    path: undefined,
    disposition: undefined,
    recipient: undefined,
    shipper: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键id不能为空', trigger: 'blur' }],
    materialsId: [{ required: true, message: '材料id不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const materialsOptions = ref([]);

/** 查询材料出/入库列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMaterialsInventory(queryParams.value);
  materialsInventoryList.value = res.rows;
  total.value = res.total;
  const materialsMap = new Map();
  res.rows.forEach((record: MaterialsInventoryVO) => {
    const { id, materialsName } = record.materialsVo;
    if (!materialsMap.has(id)) {
      materialsMap.set(id, { id, materialsName });
    }
  });
  materialsOptions.value = Array.from(materialsMap.values());
  loading.value = false;
};

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

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

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

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

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

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

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

/** 删除按钮操作 */
const handleDelete = async (row?: MaterialsInventoryVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除材料出/入库编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delMaterialsInventory(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'materials/materialsInventory/export',
    {
      ...queryParams.value
    },
    `materialsInventory_${new Date().getTime()}.xlsx`
  );
};
onMounted(() => {
  getList();
});
</script>
