<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 { checkTypeOptions, payStatusOptions } from "/@/utils/status";
import { httpList } from "/@/api/purchase/ticketReturn";
import { useCompany } from "/@/hooks/core/useCompany";
import { SupplierQuery, DateRange } from "/@/components/BasicForm";
import { orderTypeCgOptions_2 } from "/@/utils/status"

import { PURCHASE_OLD_APPLY_DATE, getDateName } from "/@/utils/constants"

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

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

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

const formData = ref<Record<string, any>>({
  is_comon: '0',
  apply_name: "",
  currentValue: "",
  supplierNo: "",
  checkApi: "",
  timer: [],
  openTimer: []
});

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

const { currentCompany } = useCompany();

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

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

  const { code, message, data } = await httpList({
    status: "4",
    [currentKey.value]: currentValue,
    companyNo: currentCompany.value.companyNo,
    open_start: openTimer[0],
    open_end: openTimer[1],
    start: timer[0],
    end: timer[1],
    noRela: true,
    ...otherParams,
    page,
    size
  });

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

function handleConfirm() {
  const [order] = selects.value;
  const date = order.payNo.slice(3, 9)
  const isOld = Number(date) < Number(PURCHASE_OLD_APPLY_DATE)

  if(!isOld){
    ElMessage.warning('请选择' + getDateName() + '之前的数据')
    return
  }

  if (!order) return ElMessage.warning("请选择一个对账单");
  emit("choose", unref(order.hpNo));
  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 = {
      is_comon: '0',
      apply_name: "",
      currentValue: "",
      supplierNo: "",
      checkApi: "",
      openTimer: [],
      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="10">
        <el-col :span="8">
          <date-range prefix="申请" v-model="formData.timer" />
        </el-col>

        <el-col :span="8">
          <date-range prefix="开票" v-model="formData.openTimer" />
        </el-col>

        <el-col :span="8">
          <supplier-query v-model="formData.supplierNo" placeholder="卖出方公司名称" />
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-input clearable v-model="formData.currentValue" placeholder="关键字">
              <template #prepend>
                <el-select v-model="currentKey" style="width: 140px">
                  <el-option label="对账回票申请编码" value="hpNo" />
                  <el-option label="对账编码" value="payNo" />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-select style="width: 100%" v-model="formData.checkApi" placeholder="发票查验方式">
            <el-option v-for="opt in checkTypeOptions" :key="opt.value" :value="opt.value" :label="opt.label" />
          </el-select>
        </el-col>

        <el-col :span="4">
          <el-form-item>
            <el-input placeholder="申请人" v-model="formData.apply_name" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-select v-model="formData.is_comon" style="width: 155px" placeholder="业务类型" @change="() => handleSearch(false)">
            <el-option v-for="option in orderTypeCgOptions_2" :label="option.label" :value="option.value" />
          </el-select>
        </el-col>

        <el-col :span="4">
          <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 max-height="520px" v-loading="loading">
      <el-table-column type="selection" width="40" align="center"  fixed="left" />
      <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'" size="small">{{
    payStatusOptions.find(p => p.value === String(row.pay_status))
      ?.label
  }}</el-tag>

          <el-tag v-else-if="col.prop === 'checkApi'" size="small">{{
    checkTypeOptions.find(p => p.value === String(row.checkApi))?.label
  }}</el-tag>
          <el-tag v-else-if="col.prop === 'is_comon'">{{
          orderTypeCgOptions_2.find(p => p.value === row.is_comon)?.label
          }}</el-tag>

          <span v-else-if="col.prop === 'supplierName'">
            <ElTooltip placement="left" :content="'供应商编码:' + row.supplierNo">
              <IconifyIconOffline class="inline-block mr-[2px] cursor-pointer" icon="information-line" />
            </ElTooltip>
            {{ row.supplierName }}
          </span>

          <span v-else-if="col.prop === 'companyName'">
            <ElTooltip placement="left" :content="'业务公司编码:' + row.companyNo">
              <IconifyIconOffline class="inline-block mr-[2px] cursor-pointer" icon="information-line" />
            </ElTooltip>
            {{ row.companyName }}
          </span>

          <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" @current-change="requestPaymentList" :page-sizes="[15, 50, 100]"
        @size-change="handleSizeChange" layout="sizes, prev, pager, next" />

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

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