<script setup lang="ts">
import { ref, unref, reactive } from "vue";
import { ElMessage, ElTable } from "element-plus";
import { columns } from "../config/_details";
import { useResponseHandle } from "/@/hooks";
import { httpList } from "/@/api/purchase/orderRecord";
import { useCompany } from "/@/hooks/core/useCompany";
import { payStatusOptions, tagOptions } from "/@/utils/status";
import { BusinessQuery, DateRange } from "/@/components/BasicForm";

const emit = defineEmits(["choose"]);

const visible = ref(false);
const paymentList = ref<Array<Record<string, string>>>([]);
const selects = ref<Array<Record<string, string>>>([]);

const { currentCompany } = useCompany();

const pagination = reactive({
  total: 0,
  size: 15,
  page: 1,
  background: true
});

const formData = ref<Record<string, any>>({
  pay_status: "0",
  companyNo: "",
  currentValue: "",
  tag_id: "",
  timer: []
});

const tableRef = ref<InstanceType<typeof ElTable>>(null);
const currentKey = ref("payNo");
const loading = ref(false);
const responseHandle = useResponseHandle();

//初始化订单对账列表
async function requestPaymentList() {
  const { size, page } = pagination;
  loading.value = true;

  const { currentValue, timer, ...otherParams } = formData.value;

  const { code, message, data } = await httpList({
    pay_status: "0",
    status: "2",
    [currentKey.value]: currentValue,
    supplierNo: currentCompany.value.companyNo,
    startTime: timer[0],
    endTime: timer[1],
    ...otherParams,
    noRela: true,
    page,
    size
  });

  responseHandle({
    code,
    message,
    handler: () => {
      pagination.total = data.count;
      paymentList.value = data.list;
    }
  });
  loading.value = false;
}

function handleConfirm() {
  const [order] = selects.value;
  if (!order) return ElMessage.warning("请选择一个对账单");
  emit("choose", unref(order.payNo));
  visible.value = false;
}

function handleSelectionChange(values) {
  if (values.length > 1) {
    const value = values.pop();
    tableRef.value.clearSelection();
    tableRef.value.toggleRowSelection(value, true);
    selects.value = [value];
  } else {
    selects.value = [values[0]];
  }
}

function handleSizeChange() {
  pagination.page = 1;
  requestPaymentList();
}

function handleSearch(_isReset?: boolean) {
  if (_isReset) {
    formData.value = {
      pay_status: "0",
      companyNo: "",
      currentValue: "",
      tag_id: "",
      timer: []
    };
  }

  pagination.page = 1;
  requestPaymentList();
}

defineExpose({
  onDisplay: () => (visible.value = true)
});
</script>

<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visible"
    title="订单对账"
    center
    width="1040px"
    @open="() => requestPaymentList()"
  >
    <el-form size="small">
      <el-row :gutter="8">
        <el-col :span="8">
          <el-form-item>
            <el-input
              clearable
              v-model="formData.currentValue"
              placeholder="请输入"
            >
              <template #prepend>
                <el-select v-model="currentKey" style="width: 130px">
                  <el-option label="对账编码" value="payNo" />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <date-range v-model="formData.timer" />
        </el-col>

        <el-col :span="8">
          <business-query
            v-model="formData.companyNo"
            placeholder="买入方公司"
          />
        </el-col>

        <el-col :span="6">
          <el-form-item>
            <el-select
              w-80
              v-model="formData.pay_status"
              placeholder="付款状态"
            >
              <el-option value="0" label="未付款或部分付款" />
              <el-option value="1" label="未付款" />
              <el-option value="2" label="部分付款" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item>
            <el-select w-80 v-model="formData.tag_id" placeholder="标签状态">
              <el-option
                v-for="tag in tagOptions"
                :key="tag.value"
                :value="tag.value"
                :label="tag.label"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item>
            <el-button type="primary" @click="() => handleSearch()"
              >搜索</el-button
            >
            <el-button @click="() => handleSearch(true)">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-table
      border
      ref="tableRef"
      :data="paymentList"
      size="small"
      row-key="id"
      @selection-change="handleSelectionChange"
      mb-2
      v-loading="loading"
      max-height="520px"
    >
      <el-table-column type="selection" align="center" width="40" />
      <el-table-column
        v-for="(col, index) in columns"
        :key="index"
        v-bind="col"
        show-overflow-tooltip
      >
        <template #="{ row }">
          <el-tag v-if="col.prop === 'pay_status'">{{
            payStatusOptions.find(p => p.value === String(row.pay_status))
              ?.label
          }}</el-tag>

          <span v-else>{{ row[col.prop] }}</span>
        </template>
      </el-table-column>
    </el-table>

    <div flex>
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[15, 50, 100]"
        layout="sizes, prev, pager, next"
        @current-change="requestPaymentList"
        @size-change="handleSizeChange"
      />

      <div w-full flex justify-end mt-2>
        <el-button type="primary" size="small" @click="handleConfirm"
          >保存</el-button
        >
      </div>
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
:deep(.el-table__header) {
  .el-checkbox {
    display: none;
  }
}
</style>
