<template>
  <div class="page-container list-container">
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <el-button type="danger" size="small" icon="Delete" :disabled="multiple" @click="handleDelete"
        v-hasPermi="['business:collection:remove']">删除</el-button>

      <el-dropdown trigger="click">
        <el-button type="primary" size="small">
          其它<el-icon class="el-icon--right"><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="Download" @click="handleExport" v-hasPermi="['business:collection:export']">
              导出</el-dropdown-item>
            <el-dropdown-item icon="Upload" @click="handleImport"
              v-hasPermi="['business:collection:import']">导入</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <!-- 搜索区 -->
    <el-form class="list-search-container" size="small" :model="queryParams" ref="queryRef" :inline="true"
      label-width="68px">
      <el-form-item label="客户名称：" prop="companyName">
        <el-input v-model="queryParams.companyName" style="width: 150px" placeholder="请输入客户名称" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="合同编号：" prop="contractNo">
        <el-input v-model="queryParams.contractNo" style="width: 150px" placeholder="请输入合同编号" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item prop="applierTime" label="审核时间：">
        <el-date-picker v-model="queryParams.dateFilter" type="daterange" clearable format="YYYY - MM - DD "
          value-format="YYYY-MM-DD" range-separator="至" start-placeholder="业务日期" end-placeholder="业务日期"
          style="width: 100%;"></el-date-picker>
      </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>

    <!-- 列表区 -->
    <!-- 
      :summary-method="getSummaries" -->
    <el-table v-loading="loading" :data="orderList" size="small" show-summary :summary-method="getSummaries" border
      height="100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column v-if="getShowStatus(2)" label="客户" prop="companyName" min-width="250" align="center" />
      <el-table-column v-if="getShowStatus(3)" label="合同编号" prop="contractNo" min-width="150" align="center" />
      <el-table-column v-if="getShowStatus(4)" label="实际付款时间" prop="actuallyDate" width="100" align="center">
        <template #default="scope">
          {{
          scope.row.actuallyDate
          ? moment(scope.row.actuallyDate).format("YYYY-MM-DD")
          : ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="审核时间" prop="verifyDate" width="80" align="center">
        <template #default="scope">
          {{
          scope.row.verifyDate
          ? moment(scope.row.verifyDate).format("YYYY-MM-DD")
          : ""
          }}
        </template>
      </el-table-column>
      <el-table-column v-if="getShowStatus(5)" label="收款时间" prop="paymentCause" align="center" />
      <!-- <el-table-column label="支出科目" prop="paymentSubject" align="center" /> -->
      <el-table-column v-if="getShowStatus(8)" width="80" label="收款金额" prop="arriveAmount" header-align="center"
        align="right">
        <template #default="scope">
          <span>{{ rowNum(scope.row.arriveAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="getShowStatus(9)" label="申请人" prop="applierName" min-width="100" align="center" />
      <el-table-column v-if="getShowStatus(11)" label="审核状态" prop="status" min-width="90" align="center">
        <template #header>
          <!-- <el-badge v-if="unVerifiedNum > 0 && verifiable" is-dot>审核状态</el-badge> -->
          <div>审核状态</div>
        </template>
        <template #default="scope">
          <span v-if="scope.row.status === 0" style="color: #cd853f">未审核</span>
          <span v-else-if="scope.row.status === 1" style="color: #32cd32">审核通过</span>
          <span v-else-if="scope.row.status === 2" style="color: #dc143c">审核不通过</span>
        </template>
      </el-table-column>
      <el-table-column v-if="getShowStatus(12)" label="支付状态" min-width="90" prop="arriveStatus" align="center">
        <template #default="scope">
          <span v-if="scope.row.arriveStatus === 0" style="color: #dc143c">未支付</span>
          <span v-else-if="scope.row.arriveStatus === 1" style="color: #32cd32">已支付</span>
          <span v-else-if="scope.row.arriveStatus === 2" style="color: #cd853f">部分支付</span>
        </template>
      </el-table-column>
      <el-table-column v-if="getShowStatus(14)" label="到账日期" prop="actuallyDate" align="center">
        <template #default="scope">
          {{ (scope.row.arriveDate) }} {{scope.row.arriveTime}}
        </template>
      </el-table-column>
      <el-table-column v-if="getShowStatus(13)" label="备注" prop="remark" align="center" min-width="100" />
      <el-table-column label="操作" width="80" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" link @click="handleView(scope.row.id)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <contract-form ref="contractRef" :get-list="getList" />
    <import-excel-dialog ref="importExcelDialogRef" :get-list="getList" />
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
  </div>
</template>

<script setup name="Collection">
  import contractForm from "./form";
  import {
    listCollection,
    delCollection,
    exportCllection,
  } from "@/api/business/financial/collection";
  import importExcelDialog from "./importExcelDialog.vue";
  const { proxy } = getCurrentInstance();
  /** 字典数组区 */
  /** 查询 对象 */

  const orderList = ref([]);
  const loading = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const showRows = ref([2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14]);
  const importExcelDialogRef = ref(null);
  const rows = ref([
    {
      key: 2,
      label: "客户名称",
    },
    {
      key: 3,
      label: "合同编号",
    },
    {
      key: 4,
      label: "收款日期",
    },
    {
      key: 5,
      label: "收款时间",
    },
    {
      key: 9,
      label: "申请人",
    },
    {
      key: 11,
      label: "审核状态",
    },
    {
      key: 12,
      label: "支付状态",
    },
    {
      key: 14,
      label: "确认到账时间",
    },
    {
      key: 13,
      label: "备注",
    },
  ]);

  const { contract_verify_status } = proxy.useDict("contract_verify_status");
  const { contract_status } = proxy.useDict("contract_status");
  /** 查询对象 */
  const queryParams = ref({
    pageNum: 1,
    orderByColumn: "create_time",
    pageSize: 20,
  });

  /***********************  方法区  ****************************/
  onActivated(() => {
    // 你的逻辑
    getList();
  });
  /** 查询company列表 */
  function getList() {
    console.log(1111, queryParams.value);
    loading.value = true;
    listCollection(queryParams.value).then((response) => {
      orderList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

  function getSummaries(param) {
    const { columns, data } = param;
    const sums = [];
    let indexOf;
    columns.forEach((column, index) => {
      if (column.label != "收款金额") {
        return;
      }
      indexOf = index;
      const values = [];

      data.map((item) => {
        if (item.arriveStatus == 1) {
          if (item.arriveAmount) {
            values.push(item.arriveAmount);
          }
        }
      });

      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = ` ${values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!Number.isNaN(value)) {
            return Number(Number(prev) + value).toFixed(2);
          } else {
            return Number(prev).toFixed(2);
          }
        }, 0)}`;
      }
    });
    sums[indexOf] = numberToCurrencyNo(sums[indexOf]);

    return sums;
  }

  function numberToCurrencyNo(value) {
    if (!value) return 0;
    // 获取整数部分
    const intPart = Math.trunc(value);

    // 整数部分处理，增加,
    const intPartFormat = intPart
      .toString()
      .replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
    // 预定义小数部分

    let floatPart = "";
    // 将数值截取为小数部分和整数部分
    const valueArray = value.toString().split(".");
    if (valueArray.length === 2) {
      // 有小数部分

      floatPart = valueArray[1].toString(); // 取得小数部分
      return intPartFormat + "." + floatPart;
    }
    return intPartFormat + floatPart;
  }

  function rowNum(num) {
    num = num.toLocaleString(); // 3,000
    if (num.indexOf(".") == -1) {
      num = num + ".00"; //3,000.00
    } else if (num.charAt(num.indexOf(".") == num.length - 2)) {
      num = num + "0";
    }
    return num;
  }

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

  /** 重置按钮操作 */
  function resetQuery() {
    // proxy.resetForm("queryRef");
    queryParams.value = {
      pageNum: 1,
      pageSize: 20,
      nonpayment: true,
    };
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  function handleView(id) {
    proxy.$refs.contractRef.open(id);
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal
      .confirm("是否确认删除选中的数据项？")
      .then(function () {
        return delCollection(_ids);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功！");
      })
      .catch(() => { });
  }

  function handleAlter(row) {
    const id = row.id || ids.value;
    proxy.$refs.contractRef.openSimple(id, "alterOrder");
  }

  function handleDissolution() {
    const row = orderList.value.find((item) => item.id === ids.value[0]);
    proxy.$modal
      .confirm("是否确认解除合同？")
      .then(function () {
        return dissolutionOrder(row);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功！");
      })
      .catch(() => { });
  }

  /** 导出按钮操作 */
  function handleExport() {
    exportCllection(queryParams.value);
  }

  function handleImport() {
    importExcelDialogRef.value.open();
  }

  function getShowStatus(key) {
    const index = showRows.value.findIndex((l) => l === key);
    return index >= 0;
  }

  getList();
</script>