<template>
<el-card class="hl-card">
  <template #header>
    <span>采购单审批</span>
  </template>
  <ContentWrap class="borderxx">
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="130px">
      <el-form-item label="项目编号" prop="projectCode">
        <el-input v-model="queryParams.projectCode" placeholder="项目编号" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="客户简称" prop="brief">
        <el-input v-model="queryParams.brief" placeholder="客户简称" clearable @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item label="子项目名称" prop="projectSubName">
        <el-input v-model="queryParams.projectSubName" placeholder="请输入子项目名称" clearable @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>

      <el-form-item label="图号" prop="blueprintNo">
        <el-input v-model="queryParams.blueprintNo" placeholder="图号" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="零件名称" prop="materialName">
        <el-input v-model="queryParams.materialName" placeholder="零件名称" clearable @keyup.enter="handleQuery"
                  class="!w-240px" />
      </el-form-item>
      <el-form-item label="责任人" prop="ownerName">
        <el-input v-model="queryParams.ownerName" placeholder="责任人" clearable @keyup.enter="handleQuery"
                  class="!w-240px" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HELI_DOCUMENT_STATUS).filter(item=>item.value==1 || item.value==2)" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="采购单类型" prop="goodType">
        <el-select v-model="queryParams.goodsType" placeholder="请选择采购单类型" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PART_PURCHASE_ORDER_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierName">
        <el-input v-model="queryParams.supplierName" placeholder="供应商" clearable @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item label="工序" prop="procedureName">
        <el-input v-model="queryParams.procedureName" placeholder="工序" clearable @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item style="margin-left:15px">
        <el-button @click="handleQuery" type="primary">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>

      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" class="hl-table" show-summary :summary-method="getSummaries">
      <el-table-column label="序号" type="index" align="center" fixed min-width="70px" />
      <el-table-column label="送审日期" align="center" prop="createTime" min-width="150px"         :formatter="dateFormatter1"/>
      <el-table-column label="客户简称" align="center" prop="brief" min-width="100px"  />
      <el-table-column label="子项目编码" align="center" prop="projectSubCode" min-width="250px" />
      <el-table-column label="图号" align="center" prop="blueprintNo" min-width="120px" />
      <el-table-column label="零件名称" align="center" prop="boomName" min-width="180px" />
      <el-table-column label="规格" align="center" prop="boomSpec" min-width="120px" />
      <el-table-column label="工序" align="center" prop="procedureName" min-width="120px" />
      <el-table-column label="需求数量" align="center" prop="boomAmount" min-width="100px" />
      <el-table-column label="采购数量" align="center" prop="purchaseAmount" min-width="100px" fixed="right" />
      <el-table-column label="供应商" align="center" prop="supplierName" min-width="150px" fixed="right"/>
      <el-table-column label="单价" align="center" prop="unitPrice" min-width="100px"  fixed="right"/>
      <el-table-column label="总价" align="center" prop="estimatedPrice" min-width="100px" fixed="right" />
      <el-table-column label="责任人" align="center" prop="duEmpName" min-width="100px" fixed="right"/>
      <el-table-column label="要求到货日期" align="center" prop="requireTime" min-width="150px"  :formatter="dateFormatter1"/>
      <el-table-column label="操作" align="center" fixed="right" min-width="180">
        <template #default="scope">
          <el-button
            v-if="scope.row.status != 2"
            link
            type="primary"
            @click="approve(scope.row.id)"
          >
            审核
          </el-button>
          <el-button link type="danger" @click="reject(scope.row.id)"     v-if="scope.row.status != 2">
            驳回
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

</el-card>

</template>

<script setup lang="ts">
import {DICT_TYPE, getIntDictOptions} from '@/utils/dict'
import * as MaterialPlanApi from '@/api/heli/materialplan'
import * as PartPurchaseOrderApi from "@/api/heli/partpurchaseorder";
import {dateFormatter1} from "@/utils/formatTime";
import {approvals, review} from "@/api/heli/partpurchaseorder";
defineOptions({ name: 'MaterialPlan' })
const router = useRouter()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  id: undefined,
  purchaseNo: undefined,
  projectId: undefined,
  projectPlanId: undefined,
  submitUserId: undefined,
  projectName: undefined,
  projectSubName: undefined,
  supplierName:undefined,
  submitTime: [],
  auditor: undefined,
  auditTime: [],
  goodsType: 2,
  description: undefined,
  createTime: [],
  matType:0,
  status:1,
  projectCode:undefined,
  blueprintNo:undefined,
  materialName:undefined,
  brief:undefined,
  ownerName:undefined,
  procedureName:undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PartPurchaseOrderApi.getPartCheckPages(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
const approve = async (id:number) => {
  await PartPurchaseOrderApi.approvals(id)
  message.success("审批成功");
  getList();
}
const reject = async (id:number) => {
  await PartPurchaseOrderApi.rejects(id)
  message.success("驳回成功");
  getList();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const getSummaries = (param: SummaryMethodProps) => {
  const summaryField = ["estimatedPrice"];
  console.log(param)
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    if (!summaryField.includes(column.property)) {
      sums[index] = '';
      return;
    }
    const values = data.map(item => Number(item[column.property]));
    if (!values.every(value => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return floatAdd(prev, curr);
        } else {
          return prev;
        }
      }, 0);
      const thousandsField = [];
      if (thousandsField.includes(column.property)) {
        sums[index] = thousandsFormat(sums[index]);
      }
    } else {
      sums[index] = '';
    }
  });
  // const sumValue = computed(() => {
  //   return list.value.reduce((sum, item) => sum + item.quantityLent, 0);
  // });
  // const sums = ['合计','','','','','','','',sumValue];
  return sums;
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
const floatAdd = (a, b) => {
  var c, d, e;
  if (undefined === a || null === a || "" === a || isNaN(a)) { a = 0; }
  if (undefined === b || null === b || "" === b || isNaN(b)) { b = 0; }
  try {
    c = a.toString().split(".")[1].length;
  } catch (f) {
    c = 0;
  }
  try {
    d = b.toString().split(".")[1].length;
  } catch (f) {
    d = 0;
  }
  e = Math.pow(10, Math.max(c, d));
  return (floatMul(a, e) + floatMul(b, e)) / e;
};
const floatMul = (a, b) => {
  var c = 0,
    d = a.toString(),
    e = b.toString();
  try {
    c += d.split(".")[1].length;
  } catch (f) {}
  try {
    c += e.split(".")[1].length;
  } catch (f) {}
  return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
}
/** 添加/修改操作 */

const openForm = (type: string, id?: number) => {

  switch (type) {
    case 'create':
      router.push({ path: '/purchase/materialplanadd', query: { id: id } })
      break;
    case 'update':
      router.push({ path: '/purchase/materialplanedit', query: { id: id } })
      break;
    case 'detail':
      router.push({ path: '/purchase/PartPurchaseCheckDetail', query: { id: id , type: type} })
      // window.open(`/purchase/PartPurchaseCheckDetail?id=${id}&type=${encodeURIComponent(type)}`, '_self');
      break;
    case 'check':
      router.push({ path: '/purchase/PartPurchaseCheckDetail', query: { id: id , type: type} })
      // window.open(`/purchase/PartPurchaseCheckDetail?id=${id}&type=${encodeURIComponent(type)}`, '_self');
      break;
    default:
      break;
  }

}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MaterialPlanApi.delMaterialPlan(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}


const userInit = ref()
/** 初始化 **/
onMounted(async () => {
  //用户列表数据
  // userInit.value = await UserApi.getSimpleUserList()
  getList()
})
</script>
