<template>
  <div class="p-2">
    <el-row :gutter="20">
      <!-- 流程分类树 -->
      <el-col style="" :span="5">
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5" :offset="0"
                ><el-button
                  type="primary"
                  v-hasPermi="['cailiaoshebei:materialbatchdemandplan:add']"
                  size="default"
                  @click="handleAdd"
                  icon="FolderAdd"
                  plain
                  >新增</el-button
                ></el-col
              >
              <el-col :span="1.5" :offset="0"
                ><el-button
                  type="danger"
                  size="default"
                  v-hasPermi="['cailiaoshebei:batchPlan:remove']"
                  @click="handleDeleteBatch"
                  icon="FolderDelete"
                  plain
                  >删除</el-button
                ></el-col
              >
            </el-row>
          </template>

          <el-input v-model="batchNumber" placeholder="请输入批次号" @input="searchBatchList" prefix-icon="Search" clearable />
          <el-tree
            ref="batchTreeRef"
            class="mt-2"
            node-key="id"
            :data="batchOptions"
            :props="{ label: 'planCode', children: 'children' }"
            :expand-on-click-node="false"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                {{ node.label }}
                <dict-tag :options="wf_business_status" :value="data.status" />
              </div>
            </template>
          </el-tree>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.batchData.pageNum"
            v-model:limit="queryParams.batchData.pageSize"
            @pagination="getList"
            layout="prev, pager, next,jumper"
          />
        </el-card>
      </el-col>
      <el-col :span="19">
        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5" v-if="form.mrpBaseBo.status == 'draft'">
                <el-button type="primary" plain icon="Edit" @click="handleUpdata" v-hasPermi="['cailiaoshebei:cailiaoshebei:add']">修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button plain type="warning" icon="Finished" @click="handleAudit()" v-hasPermi="['out:monthPlan:remove']">审核</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="name" />
            <el-table-column label="质量标准" align="center" prop="qs" />
            <el-table-column label="规格型号" align="center" prop="specification" />
            <el-table-column label="计量单位" align="center" prop="unit" width="80" />
            <el-table-column label="需求数量" align="center" prop="demandQuantity" />
            <el-table-column label="需求到货时间" align="center" prop="arrivalTime" width="250" />
            <el-table-column label="备注" align="center" prop="remark" />
          </el-table>
          <pagination
            v-show="mainTotal > 0"
            :total="mainTotal"
            v-model:page="queryParams.mainData.pageNum"
            v-model:limit="queryParams.mainData.pageSize"
            @pagination="getMainList"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改物资-材料设备对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1250px" append-to-body>
      <el-form :model="form" ref="cailiaoshebeiFormRef" :rules="rules" label-width="80px" :inline="false">
        <el-divider>基础信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8" :offset="0">
            <el-form-item label="物资类别" prop="mrpBaseBo.matCat">
              <el-input v-model="form.mrpBaseBo.matCat" placeholder="请输入物资类别" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="编制日期" prop="mrpBaseBo.preparedDate">
              <el-date-picker v-model="form.mrpBaseBo.preparedDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择编制日期" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="计划编号" prop="mrpBaseBo.planCode">
              <el-input v-model="form.mrpBaseBo.planCode" placeholder="请输入计划编号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider>主要信息</el-divider>
        <el-table :data="form.planList">
          <el-table-column prop="name" align="center" label="物资名称">
            <template #default="scope">
              <el-input v-model="scope.row.name" placeholder="请输入物资" />
            </template>
          </el-table-column>
          <el-table-column prop="specification" align="center" label="规格型号" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.specification" placeholder="请输入规格型号" />
            </template>
          </el-table-column>
          <el-table-column prop="unit" align="center" label="单位" width="130">
            <template #default="scope">
              <el-input v-model="scope.row.unit" placeholder="请输入单位" />
            </template>
          </el-table-column>
          <el-table-column prop="demandQuantity" align="center" label="数量" width="130">
            <template #default="scope">
              <el-input v-model="scope.row.demandQuantity" placeholder="请输入数量" type="number" min="0" />
            </template>
          </el-table-column>
          <el-table-column prop="qs" align="center" label="质量标准" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.qs" placeholder="请输入质量标准" />
            </template>
          </el-table-column>
          <el-table-column prop="arrivalTime" align="center" label="需求到货时间">
            <template #default="scope">
              <el-date-picker v-model="scope.row.arrivalTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择" style="width: 140px" />
            </template>
          </el-table-column>
          <el-table-column prop="remark" align="center" label="备注" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
          <el-table-column prop="remark" align="center" label="操作" width="150">
            <template #default="scope">
              <el-button @click="addRow" type="success" icon="Plus" circle size="small" />
              <el-button @click="delRow(scope.$index)" type="danger" icon="Delete" circle size="small" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitTransferForm">确 定</el-button>
          <el-button @click="cancel">取 消 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Cailiaoshebei" lang="ts">
import { getCailiaoshebei, updateCailiaoshebei, listBatch, getBatch, delBatch, listSelectCailiaoshebei } from '@/api/materials/batchPlan';
import { CailiaoshebeiVO, CailiaoshebeiQuery, CailiaoshebeiForm } from '@/api/materials/batchPlan/types';
import { useUserStoreHook } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const batchTreeRef = ref<any>(null);
const cailiaoshebeiList = ref<CailiaoshebeiVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const mainTotal = ref(0);
const batchOptions = ref<any[]>([]);
const { wf_business_status } = toRefs<any>(proxy?.useDict('wf_business_status'));
const route = useRoute();
const queryFormRef = ref<ElFormInstance>();
const cailiaoshebeiFormRef = ref<ElFormInstance>();

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

const initFormData: any = {
  mrpBaseBo: {
    id: undefined,
    preparedDate: undefined,
    planCode: undefined,
    matCat: undefined,
    status: undefined,
    projectId: currentProject.value?.id
  },

  planList: [
    {
      id: undefined,
      name: undefined,
      specification: undefined,
      unit: undefined,
      demandQuantity: undefined,
      qs: undefined,
      arrivalTime: undefined,
      remark: undefined
    }
  ]
};
const data = reactive({
  form: { ...initFormData },
  queryParams: {
    batchData: {
      pageNum: 1,
      pageSize: 10,
      planCode: undefined,

      projectId: currentProject.value?.id
    },
    mainData: {
      pageNum: 1,
      pageSize: 10,
      mrpBaseId: undefined,
      projectId: currentProject.value?.id
    }
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    'mrpBaseBo.preparedDate': [{ required: true, message: '计划日期不能为空', trigger: 'blur' }],
    'mrpBaseBo.planCode': [{ required: true, message: '计划编码不能为空', trigger: 'blur' }],
    'mrpBaseBo.matCat': [{ required: true, message: '物资分类不能为空', trigger: 'blur' }]
  }
});
const batchNumber = ref('');
const { queryParams, form, rules } = toRefs(data);

/** 查询物资-材料设备列表 */
const getList = async (type?: string) => {
  loading.value = true;
  const res = await listBatch(queryParams.value.batchData);
  batchOptions.value = res.rows;
  if (res.rows && res.rows.length > 0 && !queryParams.value.mainData.mrpBaseId) {
    batchTreeRef.value.setCurrentKey(res.rows[0].id);
    queryParams.value.mainData.mrpBaseId = res.rows[0].id;
    form.value.mrpBaseBo.status = res.rows[0].status;
  }
  total.value = res.total;
  loading.value = false;
  if (type === 'search') return;
  getMainList();
};

/** 节点单击事件 */
const handleNodeClick = (data: any) => {
  queryParams.value.mainData.mrpBaseId = data.id;
  form.value.mrpBaseBo.status = data.status;

  getMainList();
};

const getMainList = async () => {
  if (!queryParams.value.mainData.mrpBaseId) return;

  const res = await getBatch(queryParams.value.mainData);
  cailiaoshebeiList.value = res.rows;
  mainTotal.value = res.total;
};

const searchBatchList = async () => {
  queryParams.value.batchData.planCode = batchNumber.value;
  getList('search');
};

//删除
const delRow = (index: number) => {
  if (form.value.planList.length <= 1) return proxy?.$modal.msgWarning('请至少保留一项');
  form.value.planList.splice(index, 1);
};

//新增
const addRow = () => {
  form.value.planList.push({
    name: undefined,
    specification: undefined,
    unit: undefined,
    demandQuantity: undefined,
    qs: undefined,
    arrivalTime: undefined,
    remark: undefined
  });
};

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

/** 表单重置 */
const reset = () => {
  const status = form.value.mrpBaseBo.status;
  form.value = { ...initFormData, status }; // 重置但保留
  cailiaoshebeiFormRef.value?.resetFields();
  form.value.mrpBaseBo.projectId = currentProject.value?.id;
  form.value.planList = [
    {
      name: undefined,
      specification: undefined,
      unit: undefined,
      demandQuantity: undefined,
      qs: undefined,
      arrivalTime: undefined,
      remark: undefined
    }
  ];
};

// /** 搜索按钮操作 */
// 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 handleUpdata = () => {
  reset();
  getCailiaoshebei(queryParams.value.mainData.mrpBaseId).then((res: any) => {
    form.value.mrpBaseBo = res.data.mrpBaseBo;
    const allowedKeys = Object.keys(initFormData.planList[0]);
    form.value.planList = res.data.planList.map((item) => {
      return allowedKeys.reduce((obj, key) => {
        obj[key] = item[key] ?? undefined;
        return obj;
      }, {});
    });

    console.log(form.value);
  });
  dialog.visible = true;
  dialog.title = '修改物资-需求';
};

/** 提交数据 */
const submitTransferForm = async () => {
  const result = validateAndClean(form.value.planList);
  if (!result.valid) {
    proxy?.$modal.msgError('验证失败,主要信息存在部分字段缺失的数据项');
    return;
  }
  cailiaoshebeiFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.planList = result.data;
      await updateCailiaoshebei(form.value).finally(() => (buttonLoading.value = false));
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除批次 */
const handleDeleteBatch = async () => {
  const _ids = batchTreeRef.value.getCurrentNode()?.id;
  await proxy?.$modal.confirm('是否确认删除批次编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delBatch(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  queryParams.value.mainData.mrpBaseId = undefined;
  await getList();
};

//检测主要信息填写状况
function validateAndClean(arr) {
  // 过滤掉全空的数据项
  const cleanedArr = arr.filter((item) => !Object.values(item).every((v) => v === '' || v == null));
  let hasFullItem = false; // 是否有一条全填数据

  for (const item of cleanedArr) {
    const keys = Object.keys(item).filter((k) => k !== 'remark' && k !== 'id');
    const allFilled = keys.every((k) => item[k] !== '' && item[k] != null);
    if (allFilled) {
      hasFullItem = true; // 有一条全填
    }
    const allEmpty = Object.values(item).every((v) => v === '' || v == null);
    // 如果不是全填，也不是全空（部分填） → 直接返回失败
    if (!allFilled && !allEmpty) {
      return { valid: false, data: cleanedArr };
    }
  }
  // 如果没有至少一条全填，返回失败
  if (!hasFullItem) {
    return { valid: false, data: cleanedArr };
  }
  return { valid: true, data: cleanedArr };
}

/** 审核按钮操作 */
const handleAudit = async () => {
  if (!form.value.mrpBaseBo.status) {
    proxy?.$modal.msgError('请选择批次号');
    return;
  }
  proxy?.$tab.closePage(route);
  proxy?.$tab.openPage('/materials-management/batchPlan/indexEdit', '审核物资设备批次需求计划', {
    id: queryParams.value.mainData.mrpBaseId,
    status: form.value.mrpBaseBo.status + '_batchRequirements',
    type: 'update'
  });
};

onMounted(() => {
  getList();
  // getSupplierList();
});

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

    form.value.mrpBaseBo.projectId = nid;

    getList();
  }
);

onUnmounted(() => {
  listeningProject();
});
</script>
<style scoped lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
