<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="batchId">
              <el-input v-model="queryParams.batchId" placeholder="请输入批次ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供货商ID" prop="supplierId">
              <el-input v-model="queryParams.supplierId" placeholder="请输入供货商ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供货商" prop="supplier">
              <el-input v-model="queryParams.supplier" placeholder="请输入供货商" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备材料名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入设备材料名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供货来源(字典)" prop="supply">
              <el-input v-model="queryParams.supply" placeholder="请输入供货来源(字典)" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="queryParams.specification" placeholder="请输入规格型号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="特征描述" prop="signalment">
              <el-input v-model="queryParams.signalment" placeholder="请输入特征描述" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="queryParams.materialCode" placeholder="请输入物料编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="计划到场时间" prop="arrivalTime">
              <el-date-picker clearable v-model="queryParams.arrivalTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择计划到场时间" />
            </el-form-item>
            <el-form-item label="计划完成时间" prop="finishTime">
              <el-date-picker clearable v-model="queryParams.finishTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择计划完成时间" />
            </el-form-item>
            <el-form-item label="计量单位" prop="unit">
              <el-input v-model="queryParams.unit" placeholder="请输入计量单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="计划数量" prop="plan">
              <el-input v-model="queryParams.plan" placeholder="请输入计划数量" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="实际数量" prop="realQuantity">
              <el-input v-model="queryParams.realQuantity" 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-row :gutter="20">
      <!-- 流程分类树 -->
      <el-col :lg="4" :xs="24" style="">
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5" :offset="0"
                ><el-button type="primary" size="default" @click="addBatch" icon="FolderAdd" plain>新增</el-button></el-col
              >
              <el-col :span="1.5" :offset="0"><el-button type="danger" size="default" @click="" icon="FolderDelete" plain>删除</el-button></el-col>
            </el-row>
          </template>

          <el-input v-model="queryParams.batchNumber" placeholder="请输入批次号" @input="getBatchList" prefix-icon="Search" clearable />
          <el-tree
            ref="batchTreeRef"
            class="mt-2"
            node-key="id"
            :data="batchOptions"
            :props="{ label: 'batchNumber', children: 'children' }"
            :expand-on-click-node="false"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          ></el-tree>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getBatchList"
          />
        </el-card>
      </el-col>
      <el-col :lg="20" :xs="24">
        <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="['cailiaoshebei:cailiaoshebei:add']">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="Edit"
                  :disabled="single"
                  @click="handleUpdate()"
                  v-hasPermi="['cailiaoshebei:cailiaoshebei:edit']"
                  >修改</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="Delete"
                  :disabled="multiple"
                  @click="handleDelete()"
                  v-hasPermi="['cailiaoshebei:cailiaoshebei:remove']"
                  >删除</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['cailiaoshebei:cailiaoshebei:export']"
                  >导出</el-button
                >
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="cailiaoshebeiList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="供货商ID" align="center" prop="supplierId" /> -->
            <el-table-column label="供货商" align="center" prop="supplier" />
            <el-table-column label="设备材料名称" align="center" prop="name" />
            <el-table-column label="供货来源" align="center" prop="supply">
              <template #default="scope">
                <dict-tag :options="supply" :value="scope.row.supply" />
              </template>
            </el-table-column>
            <el-table-column label="规格型号" align="center" prop="specification" />
            <el-table-column label="特征描述" align="center" prop="signalment" />
            <el-table-column label="物料编码" align="center" prop="materialCode" width="200" />
            <!-- <el-table-column label="计划到场时间" align="center" prop="arrivalTime" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.arrivalTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="计划完成时间" align="center" prop="finishTime" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column> -->
            <el-table-column label="计量单位" align="center" prop="unit" />
            <el-table-column label="计划数量" align="center" prop="plan" />
            <el-table-column label="实际数量" align="center" prop="realQuantity" />
            <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="Edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['cailiaoshebei:cailiaoshebei:edit']"
                  ></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['cailiaoshebei:cailiaoshebei:remove']"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改物资-材料设备对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="cailiaoshebeiFormRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="批次ID" prop="batchId">
          <el-input v-model="form.batchId" placeholder="请输入批次ID" disabled />
        </el-form-item>
        <el-form-item label="供货商ID" prop="supplierId">
          <el-input v-model="form.supplierId" placeholder="请输入供货商ID" />
        </el-form-item>
        <el-form-item label="供货商" prop="supplier">
          <el-input v-model="form.supplier" placeholder="请输入供货商" />
        </el-form-item>
        <el-form-item label="设备材料名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备材料名称" />
        </el-form-item>
        <el-form-item label="供货来源" prop="supply">
          <el-select v-model="form.supply" value-key="value" placeholder="请选择供货来源" clearable filterable @change="">
            <el-option v-for="item in supply" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="特征描述" prop="signalment">
          <el-input v-model="form.signalment" placeholder="请输入特征描述" />
        </el-form-item>
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
        </el-form-item>
        <!-- <el-form-item label="计划到场时间" prop="arrivalTime">
          <el-date-picker clearable v-model="form.arrivalTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择计划到场时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划完成时间" prop="finishTime">
          <el-date-picker clearable v-model="form.finishTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择计划完成时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="计量单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入计量单位" />
        </el-form-item>
        <el-form-item label="计划数量" prop="plan">
          <el-input v-model="form.plan" placeholder="请输入计划数量" />
        </el-form-item>
        <!-- <el-form-item label="实际数量" prop="realQuantity">
          <el-input v-model="form.realQuantity" placeholder="请输入实际数量" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" 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="Cailiaoshebei" lang="ts">
import {
  listCailiaoshebei,
  getCailiaoshebei,
  delCailiaoshebei,
  addCailiaoshebei,
  updateCailiaoshebei,
  listBatch,
  getBatch
} from '@/api/materials/cailiaoshebei';
import { CailiaoshebeiVO, CailiaoshebeiQuery, CailiaoshebeiForm } from '@/api/materials/cailiaoshebei/types';
import { useUserStoreHook } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { supply } = toRefs<any>(proxy?.useDict('supply'));
// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);

const cailiaoshebeiList = ref<CailiaoshebeiVO[]>([]);
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 batchOptions = ref<any[]>([]);

const queryFormRef = ref<ElFormInstance>();
const cailiaoshebeiFormRef = ref<ElFormInstance>();

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

const initFormData: CailiaoshebeiForm = {
  id: undefined,
  batchId: undefined,
  supplierId: undefined,
  supplier: undefined,
  name: undefined,
  supply: undefined,
  specification: undefined,
  signalment: undefined,
  materialCode: undefined,
  arrivalTime: undefined,
  finishTime: undefined,
  unit: undefined,
  plan: undefined,
  realQuantity: undefined,
  projectId: currentProject.value.id,
  remark: undefined
};
const data = reactive<PageData<CailiaoshebeiForm, CailiaoshebeiQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    batchId: undefined,
    supplierId: undefined,
    supplier: undefined,
    name: undefined,
    projectId: currentProject.value.id,
    batchNumber: undefined,
    supply: undefined,
    specification: undefined,
    signalment: undefined,
    materialCode: undefined,
    arrivalTime: undefined,
    finishTime: undefined,
    unit: undefined,
    plan: undefined,
    realQuantity: 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 listCailiaoshebei(queryParams.value);
  cailiaoshebeiList.value = res.rows;

  loading.value = false;
};

//查询批次列表
const getBatchList = async () => {
  const res = await listBatch(queryParams.value);
  batchOptions.value = res.rows;
  total.value = res.total;
  try {
    queryParams.value.batchId = res.rows[0].id;
    form.value.batchId = res.rows[0].id;
  } catch (error) {
    queryParams.value.batchId = '';
    form.value.batchId = '';
  }
  getList();
};

/** 节点单击事件 */
const handleNodeClick = (data: any) => {
  queryParams.value.batchId = data.id;
  form.value.batchId = data.id;
  console.log('🚀 ~ handleNodeClick ~ form.value:', form.value);
  if (data.id === '0') {
    queryParams.value.batchId = '';
  }
  getList();
};

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

/** 表单重置 */
const reset = () => {
  const preservedBatchId = form.value.batchId; // 先保存当前的 batchId
  form.value = { ...initFormData, batchId: preservedBatchId }; // 重置但保留
  cailiaoshebeiFormRef.value?.resetFields();
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: CailiaoshebeiVO[]) => {
  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?: CailiaoshebeiVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getCailiaoshebei(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改物资-材料设备';
};

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

/** 新增批次 */
const addBatch = async () => {
  await proxy?.$modal.confirm('是否确认新增批次？').finally(() => (loading.value = false));
  const res = await getBatch({
    projectId: currentProject.value.id
  });
  console.log('🚀 ~ addBatch ~ res:', res);
  proxy?.$modal.msgSuccess('新增成功');
  await getList();
};

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

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'cailiaoshebei/cailiaoshebei/export',
    {
      ...queryParams.value
    },
    `cailiaoshebei_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getBatchList();
});
</script>
