<script setup lang="ts">
import { watch, shallowReactive, computed, reactive, shallowRef, ref, nextTick } from "vue"
import { httpInvoiceDetail, httpRelation, httpUnRelation, httpOldRelation, httpOldUnRelation } from "/@/api/invoice"
import { multiplication, addition, subtraction, division } from "/@/utils/calc";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { useTask, useTasks } from "/@/hooks/core"
import { ElMessage } from "element-plus"


import Modal from "./modal.vue"
import OrderModal from "./order-modal.vue"
import PayModal from "./pay-modal.vue"

const emit = defineEmits(['refresh'])
const props = withDefaults(defineProps<{
  code: string;
  payNo?: string;
  invNo?: string;
  invNumber: string;
  multiplePayNos?: boolean;
  mode?: 'sale' | 'purchase';
  companyNo?: string;
  supplierNo?: string
}>(), { mode: 'purchase' });


const state = shallowReactive({
  index: 0,  // 当前修改项索引
  count: 0,  // 当前发票明细总条数
  total: 0, // 当前订单总金额
})

const modalState = reactive({
  visible: false,
  index: -1,
  data: {},
})

const orders = ref([])
const payState = reactive({ visible: false })
const orderModalVisible = shallowRef(false)

// const instance = getCurrentInstance()
const currentInvoiceItem = computed(() => {
  const list = (invoiceDetailTask.data || [])
  const item =  list[state.index] || {}
  return item
})

// 判断是否已经关联完了
const isRelated = computed(() => {
  const { mode } = props
  if(mode === 'sale' && currentInvoiceItem.value.status != '0') return true
  if(mode === 'purchase' && currentInvoiceItem.value.status == '1') return true
  return false
})


/* 计算差值 = 当前发票明细总金额 - 订单总金额*/
const difference = computed(() => {
  const money = Number(subtraction(currentInvoiceItem.value.total_amount, state.total)).toFixed(2)
  return {
    mode: Number(money) === 0 ? 'ok' : Number(money) > 0 ? 'down' : 'up',
    money: Number.isNaN(money) || money === 'NaN' ? 0 : Math.abs(Number(money))
  }
})

function refreshOrders(orderInfo: any = []) {
  orders.value = orderInfo.map((item) => ({
      id: item.id,
      goodNum: item.num,
      itemId: item.itemId,
      goodNo: item.spuCode,
      sequenceNo: item.code,
      cat_code: item.cat_code,
      cat_name: item.cat_name,
      goodName: item.good_name,
      goodPrice: item.good_price,
      balance_amount: item.balance_amount,
      open_amount: item.total_amount,
      merge_code: item.cat_code,
  }))

  calcTaxAfterAmount()
}

// 创建关联
const relationTask = useTask<any>()

// 订单相关处理
const orderDetailTask = useTask<any>({ initialData: [], root: false, success({ list = [] } = {}){
  orderDetailTask.data = list.map(item => {
    const { goodNum = 0, goodPrice = 0, ...rest } = item
    return { ...rest, goodNum, goodPrice ,openAmount: Number(multiplication(Number(goodPrice).toFixed(2), goodNum)).toFixed(2) }
  })
  calcTaxAfterAmount()
}})



const isInitail = ref(true)
// 发票明细相关处理
const invoiceDetailTask  = useTask<any>({ initialData: [], success(data = []) {   
  state.count = data.length 


  invoiceDetailTask.data = data.map(item => ({
    ...item,
    tax_price: (!Number(item.total_amount) || !Number(item.num)) ? '' : Number(division(item.total_amount, item.num)).toFixed(2)
  }))

  if(isInitail.value){
    let index = invoiceDetailTask.data.findIndex((item) => item.status == '0' || item.status == '2')
    if(index === -1) index = 0
    state.index = index
    const { OrderInfo = [] } = invoiceDetailTask.data[state.index]
    refreshOrders(OrderInfo)
    isInitail.value = false
  }
}})

// 解除关联
const unRelationTask = useTask({
  success: async () => {
    ElMessage.success('解除成功')
    // 刷新发票明细
    await refreshInvoiceDetail()
    // 刷新绑定的订单信息
    const item = ((invoiceDetailTask.data || [])[state.index]) || {}
    const { OrderInfo } = item
    refreshOrders(OrderInfo)
  }
})


const refreshInvoiceDetail = () => invoiceDetailTask.run(httpInvoiceDetail({ code: props.code  }))
const taskState = useTasks(orderDetailTask, invoiceDetailTask, relationTask, unRelationTask)


/* 计算税后金额 */
const calcTaxAfterAmount = () =>  state.total = orders.value.reduce((prev, current) => Number(addition(current.open_amount, prev)).toFixed(2), 0)
function onUpdate(data: any, index: number){
  modalState.visible = true
  modalState.index = index
  modalState.data = data
}

/** 修改订单项 */
function handleOrderItemUpdate(open_amount: number, goodNum: number ,index: number){
  orders.value[index].open_amount = open_amount
  calcTaxAfterAmount()
}

/** 添加订单项 */
function handleOrderUpdate(list: any[] = []){
  const payNos = orders.value.map(({sequenceNo}) => sequenceNo)
  const newList = []

  list.forEach(item => {
    if(!payNos.includes(item.sequenceNo)){ newList.push({ ...item, open_amount: item.winv_fee }) }
  })

  nextTick(() => {
    orders.value = [...orders.value, ...newList]
    calcTaxAfterAmount()
  })
}
 

/** 切换到下一条发票明细 */
async function toNext(){
  const { money, mode } = difference.value
  if(orders.value.length === 0){
    ElMessage.error(`至少添加一条数据！`)
    return
  }

  if(state.total <= 0){
    ElMessage.error(`金额不能为零！`)
    return
  }

  if(mode !== 'ok' && props.mode !== 'sale' && currentInvoiceItem.value.status != '1'){
    ElMessage.error(`发票明细税后金额与当前订单税后金额不符,${mode === 'up' ? '超出' : '还差'} ${money} 元`)
    return
  }

  if(!isRelated.value){
    const newOrders =  orders.value.filter(({id}) => !id)
    const orderArr = newOrders.map(({ goodNo, sequenceNo, goodNum, open_amount, goodPrice, goodName }) => ({
      total_amount: open_amount,
      good_price: goodPrice,
      good_name: goodName,
      code: sequenceNo,
      spuCode: goodNo,
      num: goodNum,
      remark: ''
    }))

    const itemId = currentInvoiceItem.value.id
    const result: any = await relationTask.run(props.multiplePayNos ? httpRelation({ orderArr, itemId }) : httpOldRelation({ orderArr, itemId }))

    if(result.code == '0'){
      if(state.index + 1 === invoiceDetailTask.data.length){
        emit('refresh')
      }else{
        state.total = 0
        orders.value = []
        state.index = state.index + 1
        const item = ((invoiceDetailTask.data || [])[state.index]) || {}
        const { OrderInfo = [] } = item
        refreshOrders(OrderInfo)
      }
    }else{
      ElMessage.warning(result.message)
    }
  }else{
    if(state.index + 1 === invoiceDetailTask.data.length){
      emit('refresh')
    }else{
      state.total = 0
      orders.value = []
      state.index = state.index + 1
      const item = ((invoiceDetailTask.data || [])[state.index]) || {}
      const { OrderInfo = [] } = item
      refreshOrders(OrderInfo)
    }
  }
}


async function toPrev(){
  await refreshInvoiceDetail()
  state.index = state.index - 1
  const item = ((invoiceDetailTask.data || [])[state.index]) || {}
  const { OrderInfo = [] } = item
  refreshOrders(OrderInfo)
}
  

const onUnRelation = ({ id }, $index) => {
  if(!id){
    orders.value.splice($index, 1)
    calcTaxAfterAmount()
  }else{
    unRelationTask.run(props.multiplePayNos ?  httpUnRelation({ id }) : httpOldUnRelation({ id }))
  }
}

const handleAddPayment = () => {
  props.multiplePayNos ? (payState.visible = true) : (orderModalVisible.value = true)
};

watch(() => props.code, () => {
  if(!props.code) return
  refreshInvoiceDetail()
},{
  immediate: true
})
</script>

<template>
  <div class="flex flex-col" v-loading="taskState.loading">
    <div class="flex justify-between mb-[10px]">
      <p>
        <span style="font-weight:700">发票明细：</span>
        第 {{ state.index + 1 }} 条/共 {{ state.count }} 条,
        共 {{ currentInvoiceItem.total_amount }} 元
      </p>

      <ElButtonGroup size="small" type="primary">
        <ElButton @click="toPrev" :icon="useRenderIcon('arrow-left-s-line')" v-if="state.index !== 0">
          上一条
        </ElButton>


          <ElButton @click="toNext" v-if="state.index + 1 !== invoiceDetailTask.data.length">
            下一条
            <IconifyIconOffline icon="arrow-right-s-line" />
          </ElButton>

        <ElButton v-else @click="toNext">提交</ElButton>
      </ElButtonGroup>
    </div>

    <ElTable border size="small" :data="[currentInvoiceItem]">
      <ElTableColumn label="发票明细类目编号" prop="cat_code" min-width="140px" show-overflow-tooltip />
      <ElTableColumn label="货物或应税劳务、服务名称" prop="good_name" min-width="180px" show-overflow-tooltip />
      <ElTableColumn label="数量" prop="num" width="80px" show-overflow-tooltip />
      <ElTableColumn label="单价(含税)" prop="tax_price" width="120px" show-overflow-tooltip />
      <ElTableColumn label="金额" prop="amount" width="80px" show-overflow-tooltip />
      <ElTableColumn label="税率" prop="tax" width="80px" show-overflow-tooltip />
      <ElTableColumn label="税额" prop="tax_amount" width="80px" show-overflow-tooltip />
      <ElTableColumn label="税后总额" prop="total_amount" width="120px" show-overflow-tooltip />
    </ElTable>

    <div class="flex justify-between my-[10px]">
      <p>
        <span style="font-weight:700">关联采购单明细：</span>
        共 {{ orders.length }} 条, 共 {{state.total}} 元
        <span v-if="difference.mode == 'down'" style="color: #e6a23c"> 
          ，还差 {{ difference.money }} 元
        </span>

        <span v-if="difference.mode == 'up'" style="color: #f56c6c"> 
          ，超出 {{ difference.money }} 元
        </span>
      </p>
    </div>

    <ElTable class="mb-[50px]" border size="small" :data="orders">
      <ElTableColumn type="index" label="序号" width="60px" />
      <ElTableColumn :label="`${mode === 'sale' ? '销售单' : '采购单'}编号`" prop="sequenceNo" width="160px" 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="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 />
      <ElTableColumn label="未关联金额" prop="balance_amount"  width="80px" show-overflow-tooltip />
      <ElTableColumn label="开票金额" prop="open_amount"  width="120px" show-overflow-tooltip />
      <ElTableColumn label="操作" width="80px" fixed="right">
        <template #header>
          <div class="flex justify-between items-center">
            <p>操作</p>
            <ElTooltip content="添加采购单" placement="top"  v-if="!isRelated">
              <ElButton
                link 
                type="primary" 
                :icon="useRenderIcon('add')"
                @click="handleAddPayment"
              />
            </ElTooltip>
          </div>
        </template>
        
        <template #="{ row, $index }">
          <ElTooltip content="修改" placement="top" v-if="!isRelated && !row.id">
            <ElButton type="primary" link :icon="useRenderIcon('edits')" @click="onUpdate(row, $index)" />
          </ElTooltip>

          <ElPopconfirm
              :title="`${row.id ? '是否确认解除关联?' : '是否删除该数据'}`"
              @confirm="onUnRelation(row,$index)"
            >
              <template #reference>
                <ElButton type="primary" link :icon="useRenderIcon('delete')" />
              </template>
          </ElPopconfirm>
        </template>
      </ElTableColumn>
    </ElTable>


    <Modal
      @update="handleOrderItemUpdate"
      v-model:visible="modalState.visible"
      :index="modalState.index"
      :data="modalState.data"
    />

    <OrderModal 
      v-model:visible="orderModalVisible"
      @confirm="handleOrderUpdate"
      :payNo="payNo"
      :invNo="invNo"
      :mode="mode"
    />

    <PayModal 
      v-model:visible="payState.visible"
      @confirm="handleOrderUpdate"
      :supplierNo="supplierNo"
      :companyNo="companyNo"
    />
  </div>
</template>
