<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="name" :inline="true">
            <el-form-item label="名称" prop="name">
              <el-input v-model="queryParams.name" 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="['system:repertoryDetails:add']">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="repertoryDetailsList">
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="规格" align="center" prop="specification" />
        <el-table-column label="物料编码" align="center" prop="materialCode" />
        <el-table-column label="原始数量" align="center" prop="originalQuantity" />
        <el-table-column label="变更原因" align="center" prop="changeReasons" />
        <el-table-column label="变更数量" align="center" prop="changeQuantity" />
        <el-table-column label="操作状态" align="center" prop="operationStatus">
          <template #default="scope">
            <dict-tag :options="operation_status" :value="scope.row.operationStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作人" align="center" prop="operationName" />
        <el-table-column label="操作人联系电话" align="center" prop="operationPhone" />
      </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="repertoryDetailsFormRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="库存ID" prop="repertoryId">
          <el-input v-model="form.repertoryId" placeholder="请输入库存ID" />
        </el-form-item>
        <el-form-item label="数据来源ID" prop="materialsorderId">
          <el-input v-model="form.materialsorderId" placeholder="请输入数据来源ID" />
        </el-form-item> -->
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="变更原因" prop="changeReasons">
          <el-input v-model="form.changeReasons" placeholder="请输入变更原因" />
        </el-form-item>
        <el-form-item label="变更数量" prop="changeQuantity">
          <el-input v-model="form.changeQuantity" placeholder="请输入变更数量" />
        </el-form-item>
        <el-form-item label="操作人" prop="operationName">
          <el-input v-model="form.operationName" placeholder="请输入操作人" />
        </el-form-item>
        <el-form-item label="操作状态" prop="operationStatus">
          <el-select v-model="form.operationStatus" placeholder="请选择操作状态">
            <el-option v-for="item in operation_s" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="operationPhone">
          <el-input v-model="form.operationPhone" 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="RepertoryDetails" lang="ts">
import {
  listRepertoryDetails,
  getRepertoryDetails,
  delRepertoryDetails,
  addRepertoryDetails,
  updateRepertoryDetails
} from '@/api/materials/repertoryDetails';
import { RepertoryDetailsVO, RepertoryDetailsQuery, RepertoryDetailsForm } from '@/api/materials/repertoryDetails/types';
import { useUserStoreHook } from '@/store/modules/user';
import { useRoute } from 'vue-router';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const operation_s = ref([]);
const repertoryDetailsList = ref<RepertoryDetailsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const total = ref(0);
const { operation_status } = toRefs(proxy?.useDict('operation_status'));
const queryFormRef = ref<ElFormInstance>();
const repertoryDetailsFormRef = ref<ElFormInstance>();
// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const route = useRoute();

const initFormData: RepertoryDetailsForm = {
  id: undefined,
  projectId: currentProject.value?.id,
  repertoryId: undefined,
  materialsorderId: undefined,
  materialCode: undefined,
  originalQuantity: undefined,
  changeReasons: undefined,
  changeQuantity: undefined,
  finalNumber: undefined,
  operationStatus: undefined,
  operationName: undefined,
  operationPhone: undefined
};
const data = reactive<PageData<RepertoryDetailsForm, RepertoryDetailsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProject.value?.id,
    repertoryId: undefined,
    materialsorderId: undefined,
    materialCode: undefined,
    name: undefined,

    id: undefined,
    originalQuantity: undefined,
    changeReasons: undefined,
    changeQuantity: undefined,
    finalNumber: undefined,
    operationStatus: undefined,
    operationName: undefined,
    operationPhone: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    operationPhone: [
      { required: true, message: '请输入电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ]
  }
});

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

/** 查询物资-库存列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRepertoryDetails(queryParams.value);
  repertoryDetailsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  operation_s.value = operation_status.value.slice(-2);
  console.log('🚀 ~ handleAdd ~ operation_s.value:', operation_s.value, operation_status);

  dialog.visible = true;
  dialog.title = '添加物资-库存';
};

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

/** 提交按钮 */
const submitForm = () => {
  repertoryDetailsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.repertoryId = route.query.id as string;
      await addRepertoryDetails(form.value).finally(() => (buttonLoading.value = false));
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

watch(
  () => route.query.id,
  (nid: string, oid) => {
    console.log(nid);
    queryParams.value.repertoryId = nid;
    form.value.repertoryId = nid;
    getList();
  }
);

onMounted(() => {
  queryParams.value.repertoryId = route.query.id as string;
  form.value.repertoryId = route.query.id as string;
  getList();
});

//监听项目id刷新数据
const listeningProject = watch(
  () => currentProject.value?.id,
  (nid, oid) => {
    queryParams.value.projectId = nid;
    form.value.projectId = nid;
    getList();
  }
);

onUnmounted(() => {
  listeningProject();
});
</script>
