<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 { SupplierQuery, DateRange } from "/@/components/BasicForm";
import { invStatusOptions } from "../../orderRecordQuery/config/_options";
import { orderTypeCgOptions_2 } from "/@/utils/status";
import { PURCHASE_OLD_APPLY_DATE, getDateName } from "/@/utils/constants"


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

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

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

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

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

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

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

  const { code, message, data } = await httpList({
    status: "2",
    inv_status: "0",
    // is_comon: "0",
    [currentKey.value]: currentValue,
    companyNo: currentCompany.value.companyNo,
    startTime: timer[0],
    endTime: timer[1],
    ...otherParams,
    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("请选择一个对账单");
  const date = order.payNo.slice(3, 9)
  const isOld = Number(date) < Number(PURCHASE_OLD_APPLY_DATE)

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

  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 = {
      is_comon: '0',
      inv_status: "0",
      supplierNo: "",
      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">
          <supplier-query
            v-model="formData.supplierNo"
            placeholder="卖出方公司"
          />
        </el-col>

        <el-col :span="6">
          <el-form-item>
            <el-select
              w-80
              v-model="formData.inv_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="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="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"   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 === 'inv_status'">{{
            invStatusOptions.find(p => p.value === String(row.inv_status))
              ?.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>

          <el-tag v-else-if="col.prop === 'is_comon'">
            {{ orderTypeCgOptions_2.find(p => p.value == row.is_comon)?.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>
