<script setup lang="ts">
import { shallowRef, ref, computed, reactive } from "vue"
import { useVModel } from "@vueuse/core"
import { useTask } from "/@/hooks/core"
import { httpPurchaseOrders } from "/@/api/invoice"
import { ElMessage } from "element-plus"

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

import { usePageSearch } from "/@/components/PageSearch";

import PaymentContentConfig from "./payment-config/content.config"
import PaymentSearchConfig from "./payment-config/search.config"


const props = defineProps<{ 
  visible: boolean; 
  companyNo: string; 
  supplierNo: string;
}>()

const emit = defineEmits(['confirm'])

const visible = useVModel(props, 'visible')
const hooks = { pageSearchHook: () => usePageSearch(undefined, undefined, PaymentSearchConfig) };


const orderTask = useTask<any>({ initialData: [],  root: true })


const options = [
  { label: '不为零', value: 0 },
  { label: '为零', value: 1 },
  { label: '不限', value: 2 }
]


// const amountType = ref(0)

const cgdParameter = reactive({
  amountType: 0,
  sequenceNo: '',
  goodNo: '',
  merge_code: ''
})


const cgdOrders = computed(() => {
  return orderTask.data.filter((item) => {
    const filters: Function[] = [] 
    if(cgdParameter.amountType === 0){ filters.push(() => Number(item.winv_fee) !== 0) }
    if(cgdParameter.amountType === 1){ filters.push(() => Number(item.winv_fee) === 0) }
    if(cgdParameter.sequenceNo){ filters.push(() => item.sequenceNo.indexOf(cgdParameter.sequenceNo) !== -1) }
    if(cgdParameter.goodNo){ filters.push(() => item.goodNo.indexOf(cgdParameter.goodNo) !== -1) }
    if(cgdParameter.merge_code){ filters.push(() => item.merge_code.indexOf(cgdParameter.merge_code) !== -1) }
    return filters.every(filter => filter())
  } )
})

const state = ref({
  selection: [],
  active: 0,
  payNo: []
})


function onNext(){
  if(state.value.selection.length === 0){
    ElMessage.warning('请选择至少一条数据')
    return
  }

  if(state.value.active === 0){
    const payNos = state.value.selection.map(({payNo}) => payNo)
    const isOld = payNos.some(payNo => {
      const date = payNo.slice(3, 9)
      return date < PURCHASE_OLD_APPLY_DATE
    })

    if(isOld){
      ElMessage.warning('请选择' + GET_DATE_NAME() + '之后的数据')
      return
    }

    state.value.payNo = payNos
    state.value.selection = []
    state.value.active = 1
    orderTask.run(httpPurchaseOrders({ payNo: state.value.payNo }))
    return
  }

  if(state.value.active === 1){
    const isNoHaveCategory = state.value.selection.some(({ cat_code }) => !cat_code)
    if(isNoHaveCategory){
      ElMessage.warning('只能选择有类目信息的采购单')
      return
    }

    emit('confirm', state.value.selection.map(item => ({ ...item, balance_amount: item.winv_fee  })) )
    visible.value = false
    return
  }
}

function onPrev(){
  state.value.active = 0
  state.value.selection = []
}


function handleClose(){
  state.value = {
    selection: [],
    active: 0,
    payNo: []
  }

  cgdParameter.amountType = 0
  cgdParameter.sequenceNo = ''
  cgdParameter.goodNo = ''
  cgdParameter.merge_code = ''
}
</script>

<template>
  <ElDialog class="relative" v-model="visible" title="选择采购单" center top="10px" @close="handleClose" :close-on-click-modal="false"
  :close-on-press-escape="false">
    <div class="flex flex-col">
      <div class="w-full flex justify-center mb-[10px]">
        <ElSteps class="w-[300px]" :active="state.active" align-center>
          <ElStep title="选择对账单" />
          <ElStep title="选择采购单" />
        </ElSteps>
      </div>

      <ElCard class="mb-[10px]"  v-if="state.active !== 0">
        <ElRow gutter="10" class="mb-[10px]">
          <ElCol :span="8" class="flex items-center">
            <div class="w-full flex">
              <p class="mr-[5px]" style="text-wrap: nowrap">未关联金额:</p>
              <ElSelect v-model="cgdParameter.amountType" size="small" style="width:100%">
                <ElOption 
                  v-for="opt in options" 
                  :value="opt.value" 
                  :label="opt.label" 
                />
              </ElSelect>
            </div>
          </ElCol>

          <ElCol :span="8">
            <ElInput v-model="cgdParameter.sequenceNo" placeholder="采购单编号" size="small" clearable />
          </ElCol>

          <ElCol :span="8">
            <ElInput v-model="cgdParameter.goodNo"  placeholder="商品编号" size="small" clearable  />
          </ElCol>
        </ElRow>

        <ElRow>
          <ElCol :span="8">
            <ElInput v-model="cgdParameter.merge_code"  placeholder="订单商品类目编号" size="small" clearable />
          </ElCol>
        </ElRow>
      </ElCard>

      <PageContainer
        isPageStart
        v-if="state.active === 0 && companyNo && supplierNo"
        :onlySelf="true"
        :hooks="hooks"
        :contentConfig="PaymentContentConfig"
        :searchConfig="PaymentSearchConfig"
        @content-select-change="values => state.selection = values"
        :otherParams="{ companyNo, supplierNo }"
        :notice="false"
      />

    <div v-else class="flex flex-col">
      <ElTable 
        border 
        size="small"
        max-height="500px"
        v-loading="orderTask.loading" 
        :data="state.active === 0 ? orderTask.data : cgdOrders" 
        @selection-change="values => state.selection = values"
      >
        <ElTableColumn type="selection" width="40px" fixed="left" />
        <ElTableColumn type="index" label="序号" width="50px" />
        <ElTableColumn label="采购单编号" prop="sequenceNo" width="160px" show-overflow-tooltip />
        <ElTableColumn label="采购单总额" prop="totalPrice" width="120px" show-overflow-tooltip />
        <ElTableColumn label="未关联金额" prop="winv_fee"  width="120px" show-overflow-tooltip />
        <ElTableColumn label="商品编号" prop="goodNo" width="160px" show-overflow-tooltip />
        <ElTableColumn label="商品名称" prop="goodName" min-width="160px" show-overflow-tooltip />
        <ElTableColumn label="开票商品名称" prop="inv_good_name" min-width="160px" show-overflow-tooltip />
        <ElTableColumn label="订单商品类目编号" prop="merge_code" min-width="140px" show-overflow-tooltip />
        <ElTableColumn label="订单商品类目名称" prop="cat_name" min-width="140px" show-overflow-tooltip />
        <ElTableColumn label="数量" prop="goodNum"  width="80px" show-overflow-tooltip />
        <ElTableColumn label="单价" prop="goodPrice"  width="80px" show-overflow-tooltip />
      </ElTable>
    </div>


      <div :class="state.active === 0 ? 'absolute bottom-[46px] right-[30px]' : 'mt-[10px] w-full flex justify-end'">
        <ElButtonGroup type="primary">
          <ElButton @click="onPrev" v-if="state.active === 1">
            上一步
          </ElButton>
          
          <ElButton @click="onNext">
            {{ state.active === 0 ? '下一步' : '保存' }}
          </ElButton>
        </ElButtonGroup>
      </div>
    </div>
  </ElDialog>  
</template>
