<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="借用人" prop="jyUser">
        <el-input
          v-model="queryParams.jyUser"
          placeholder="请输入借用人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="借用部门" prop="jyBm">
        <el-input
          v-model="queryParams.jyBm"
          placeholder="请输入借用部门"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="借用类型" prop="jyType">
        <el-select
          v-model="queryParams.jyType"
          placeholder="请选择借用类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.HELI_BORROW_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用途" prop="jyYt">
        <el-select
          v-model="queryParams.jyYt"
          placeholder="请选择用途"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.HELI_USE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="物料名称" prop="jyMaster">
        <el-input
          v-model="queryParams.jyMaster"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          @click="openForm('create')"-->
<!--          v-hasPermi="['heli:master:create']"-->
<!--        >-->
<!--          <Icon icon="ep:plus" class="mr-5px" /> 新增-->
<!--        </el-button>-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          @click="handleExport"-->
<!--          :loading="exportLoading"-->
<!--          v-hasPermi="['heli:master:export']"-->
<!--        >-->
<!--          <Icon icon="ep:download" 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" show-summary :summary-method="getSummaries">
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="借用人" align="center" prop="jyUsers" >
<!--        <template #default="scope">-->
<!--          {{ userList.find((user) => user.id === scope.row.jyUser)?.nickname }}-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="借用部门" align="center" prop="jyBms" >
<!--        <template #default="scope">-->
<!--          {{deptList.find((dept)=>dept.id==scope.row.jyBm)?.name}}-->
<!--        </template>-->
      </el-table-column>
      <el-table-column
        label="单据日期"
        align="center"
        prop="jyDate"
        :formatter="dateFormatter1"
        width="180px"
      />
      <el-table-column label="借用类型" align="center" prop="jyType" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.HELI_BORROW_TYPE" :value="scope.row.jyType" />
        </template>
      </el-table-column>
      <el-table-column label="用途" align="center" prop="jyYt">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.HELI_USE" :value="scope.row.jyYt" />
          </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="num" />
      <el-table-column label="借出数量" align="center" prop="quantityLent" />
      <el-table-column label="借用物料名称" align="center" prop="jyMasters" width="160">
<!--        <template #default="scope">-->
<!--          {{materialList.find((material)=>material.id==scope.row.jyMaster)?.name}}-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="备注" align="center" prop="rem" />
<!--      <el-table-column label="操作" align="center" width="140">-->
<!--        <template #default="scope">-->
<!--          <el-button-->
<!--            link-->
<!--            type="primary"-->
<!--            @click="openForm('update', scope.row.id)"-->
<!--            v-hasPermi="['heli:master:update']"-->
<!--          >-->
<!--            编辑-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            link-->
<!--            type="danger"-->
<!--            @click="handleDelete(scope.row.id)"-->
<!--            v-hasPermi="['heli:master:delete']"-->
<!--          >-->
<!--            删除-->
<!--          </el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MasterForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import {dateFormatter, dateFormatter1} from '@/utils/formatTime'
import download from '@/utils/download'
import * as MasterApi from '@/api/heli/master'
import MasterForm from './MasterForm.vue'
import {DICT_TYPE, getStrDictOptions} from "@/utils/dict";
import * as UserApi from "@/api/system/user";
import * as MaterialApi from "@/api/heli/material";
import * as DeptApi from "@/api/system/dept";

defineOptions({ name: 'Master' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const userList = ref<any[]>([]) // 用户列表
const materialList = ref<any[]>([]) // 物料列表
const deptList = ref<any[]>([]) // 部门列表
const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  createTime: [],
  jyBm: undefined,
  jyYt: undefined,
  rem: undefined,
  jyMaster: undefined,
  jyUser: undefined,
  jyType: undefined,
  num: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MasterApi.getMasterPage(queryParams)
    list.value = data.list
    list.value.map(item=>{
      if (item.jyType=="4"){
        item.quantityLent= Number(-Math.abs(item.num));
      }else if (item.jyType=="1"){
        item.quantityLent= Number(item.num);
      }else {
        item.quantityLent=0
      }
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

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

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

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

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MasterApi.exportMaster(queryParams)
    download.excel(data, '借用主.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const getSummaries = (param: SummaryMethodProps) => {
  const summaryField = ["quantityLent"];
  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 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);
}
/** 初始化 **/
onMounted(async () => {
  getList()

  userList.value = await UserApi.getSimpleUserList()
  materialList.value = await MaterialApi.getSimpList()
  deptList.value = await DeptApi.getSimpleDeptList()
})
</script>
