<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" 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="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="batchNumber"
            :data="batchOptions"
            :props="{ label: 'batchNumber', 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.approvalPlan" />
              </div> </template
          ></el-tree>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getBatchList"
            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">
                <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="供货商" 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" width="150" v-if="form.approvalPlan == 'draft'">
              <template #default="scope"
                ><el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['cailiaoshebei:cailiaoshebei:edit']"
                  >修改</el-button
                ><el-button link type="primary" icon="View" @click="handleDelete(scope.row)" v-hasPermi="['cailiaoshebei:cailiaoshebei:remove']"
                  >详情</el-button
                >
              </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="计划到场时间" prop="arrivalTime">
          <el-date-picker clearable v-model="form.arrivalTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择计划到场时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划完成时间" prop="finishTime">
          <el-date-picker clearable v-model="form.finishTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择计划完成时间">
          </el-date-picker>
        </el-form-item>
        <div v-for="(item, index) in selectValue" :key="index">
          <el-divider content-position="center"
            ><el-text tag="b">{{ item }}</el-text></el-divider
          >
          <el-form-item label="单价" prop="unitPrice">
            <el-input v-model="form.listOfMaterialInventory[index].unitPrice" type="number" placeholder="请输入单价" />
          </el-form-item>
          <el-form-item label="数量" prop="num">
            <el-input v-model="form.listOfMaterialInventory[index].num" type="number" placeholder="请输入数量" />
          </el-form-item>
          <el-form-item label="合同号" prop="contractNum">
            <el-input v-model="form.listOfMaterialInventory[index].contractNum" placeholder="请输入合同号" />
          </el-form-item>
          <el-form-item label="预估供应周期" prop="estimatedCycle">
            <el-input v-model="form.listOfMaterialInventory[index].estimatedCycle" type="number" placeholder="请输入预估供应周期" />
          </el-form-item>
          <el-form-item label="供货公司" prop="supplierCompany">
            <el-input v-model="form.listOfMaterialInventory[index].supplierCompany" placeholder="请输入供货公司" disabled />
          </el-form-item>
        </div>
      </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>
    <!-- 详情弹框 -->
    <el-dialog :title="dialog.title" v-model="dialog.details" width="800px" append-to-body>
      <div class="block_box">
        <span>主要信息</span>

        <el-form label-width="130px">
          <el-row :gutter="20" justify="space-around">
            <el-col :span="12">
              <el-form-item label="批次号">
                {{ form?.batchNumber }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供货商">
                {{ form?.supplier }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备材料名称">
                {{ form?.name }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="规格型号">
                {{ form?.specification }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供货方式">
                <dict-tag :options="supply" :value="form.supply" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="特征描述">
                {{ form?.signalment }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物料编码">
                {{ form?.materialCode }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划到场时间">
                {{ form?.arrivalTime }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划完成时间">
                {{ form?.finishTime }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计量单位">
                {{ form?.unit }}
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="计划数量">
                {{ form?.plan }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="block_box" v-for="(item, index) in selectValue" v-if="form?.listOfMaterialInventory.length">
        <span>{{ item }}-物资清单列表</span>
        <el-form label-width="130px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="单价">
                {{ form?.listOfMaterialInventory[index].unitPrice }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数量">
                {{ form?.listOfMaterialInventory[index].num }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同号">
                {{ form?.listOfMaterialInventory[index].contractNum }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预估供应周期">
                {{ form?.listOfMaterialInventory[index].estimatedCycle }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供货公司">
                {{ item }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Cailiaoshebei" lang="ts">
import {
  listCailiaoshebei,
  getCailiaoshebei,
  delCailiaoshebei,
  addCailiaoshebei,
  updateCailiaoshebei,
  listBatch,
  getBatch,
  delBatch
} from '@/api/materials/suppliesprice';
import { CailiaoshebeiVO, CailiaoshebeiQuery, CailiaoshebeiForm } from '@/api/materials/suppliesprice/types';
import { listContractor } from '@/api/project/contractor';
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 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 batchOptions = ref<any[]>([]);
const { wf_business_status } = toRefs<any>(proxy?.useDict('wf_business_status'));
const batchNumber = ref('');

const queryFormRef = ref<ElFormInstance>();
const cailiaoshebeiFormRef = ref<ElFormInstance>();
// 中间数组变量供 el-select 使用
const selectValue = ref<string[]>([]);
const dialog = reactive<DialogOption>({
  visible: false,
  details: false,

  title: ''
});

const initFormData: any = {
  id: undefined,
  batchNumber: undefined,
  supplierId: undefined,
  supplier: undefined,
  name: undefined,
  supply: undefined,
  specification: undefined,
  signalment: undefined,
  approvalPlan: undefined,

  materialCode: undefined,
  arrivalTime: undefined,
  finishTime: undefined,
  unit: undefined,
  plan: undefined,
  realQuantity: undefined,
  projectId: currentProject.value.id,
  approvalProject: undefined,

  listOfMaterialInventory: [],
  remark: undefined
};
const data = reactive<PageData<any, any>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    batchNumber: undefined,
    supplierId: undefined,
    supplier: undefined,
    name: undefined,
    projectId: currentProject.value.id,
    supply: undefined,
    specification: undefined,
    signalment: undefined,
    materialCode: undefined,
    arrivalTime: undefined,
    finishTime: undefined,
    unit: undefined,
    plan: undefined,
    realQuantity: undefined,
    listOfMaterialInventory: [],
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }]
  }
});

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

/** 查询物资-材料设备列表 */
const getList = async () => {
  if (!queryParams.value.batchNumber) return;

  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);
  console.log('🚀 ~ getBatchList ~ res:', res);
  batchOptions.value = res.rows;
  total.value = res.total;
  try {
    queryParams.value.batchNumber = res.rows[0].batchNumber;
    batchTreeRef.value.setCurrentKey(res.rows[0].batchNumber);
    form.value.batchNumber = res.rows[0].batchNumber;
    form.value.approvalPlan = res.rows[0].approvalPlan;
  } catch (error) {
    form.value.batchNumber = '';
  }

  getList();
};

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

const searchBatchList = () => {
  queryParams.value.batchNumber = batchNumber.value;
  getBatchList();
};

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

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

/** 搜索按钮操作 */
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 handleUpdate = async (row?: CailiaoshebeiVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getCailiaoshebei(_id);
  Object.assign(form.value, res.data);
  selectValue.value = (form.value.supplier as string).split(',');
  if (!form.value.listOfMaterialInventory.length) {
    form.value.listOfMaterialInventory = selectValue.value.map((item) => {
      return {
        supplierCompany: item,
        estimatedCycle: '',
        contractNum: '',
        num: '',
        unitPrice: ''
      };
    });
  }
  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;
      await updateCailiaoshebei(form.value).finally(() => (buttonLoading.value = false));
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 详情按钮操作 */
const handleDelete = async (row?: CailiaoshebeiVO) => {
  reset();
  dialog.details = true;
  const _id = row?.id || ids.value[0];
  const res = await getCailiaoshebei(_id);
  Object.assign(form.value, res.data);
  selectValue.value = (form.value.supplier as string).split(',');
  if (!form.value.listOfMaterialInventory.length) {
    form.value.listOfMaterialInventory = selectValue.value.map((item) => {
      return {
        supplierCompany: item,
        estimatedCycle: '',
        contractNum: '',
        num: '',
        unitPrice: ''
      };
    });
  }
  dialog.title = '物资供应总计划详情';
};

/** 审核按钮操作 */
const handleAudit = async () => {
  if (!form.value.batchNumber) {
    proxy?.$modal.msgError('请选择批次');
    return;
  }

  proxy?.$tab.closePage(proxy.$route);
  proxy?.$tab.openPage('/materials-management/suppliesprice/indexEdit', '审核物资供应总计划', {
    id: form.value.batchNumber,
    approvalPlan: form.value.approvalPlan + '_materialsPlans',
    type: 'update'
  });
};

/** 查询供货商列表 */
const supplierOptions = ref([]);
const getSupplierList = async () => {
  const res = await listContractor({
    projectId: currentProject.value.id,
    pageNum: 1,
    pageSize: 10000
  });
  supplierOptions.value = res.rows;
};

onMounted(() => {
  getBatchList();
  getSupplierList();
});

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

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;
}
.block_box {
  border: 1px solid #9eccfa;
  border-radius: 6px;
  padding: 10px 20px 20px 10px;
  margin: 15px;

  > span {
    color: #409eff;
    font-weight: 700;
    font-size: 14px;
    margin-bottom: 10px;
    display: block;
  }
}
</style>
