<script setup lang="ts">
import { watch, ref, reactive, computed } from "vue"
import { httpInvoiceDetail, httpRelationDetail } from "/@/api/invoice"
import { useTask } from "/@/hooks/core"
import { ElMessage } from "element-plus"
import DataTable from "./data-table.vue"

const props = defineProps<{ code: string }>()
const emit = defineEmits(['refresh'])

const statusOptions = [
  { value: '0', label: '待关联' },
  { value: '1', label: '正在关联' },
  { value: '2', label: '已关联' },
]

const state = reactive({
  positive: {
    ok: [],
    no: []
  }, // 正数 - 明细 - 全部数据
  negative: { no: [] }, // 负数-明细
  result: [], // 关联结果
  notRelation: [], // 无需关联
  selection: []
})

const currentNegative = computed(() => state.negative.no.find(({ relationStatus }) => relationStatus == '1') || {})

const relationTask = useTask({ success(){
  emit('refresh')
}})


const invoiceDetailTask  = useTask<any>({ initialData: [], success(data = []) {
  let positive = []
  const negative = []


  data = data.map((item) => ({
    ...item,
    relationStatus: '0'
  }))

  data.forEach(item => {
    if(Number(item.total_amount) < 0){
      negative.push(item)
    }else{
      positive.push(item)
    }
  })

  const negativeCateCodes = negative.map(({cat_code}) => cat_code)

  let _positive =[]
  let notRelation =[]

  positive.forEach(item => {
    if(negativeCateCodes.includes(item.cat_code)){
      _positive.push(item)
    }else{
      notRelation.push(item)
    }
  })


  negative[0].relationStatus = '1'
  state.positive.no = _positive
  state.negative.no = negative
  state.notRelation = notRelation
}})

const refreshInvoiceDetail = () => invoiceDetailTask.run(httpInvoiceDetail({ code: props.code  }))

function onRelation(row){
  const currentRelationIndex = state.negative.no.findIndex(({relationStatus}) => relationStatus === '1')

  // 正数明细添加到结果集 更改关联状态
  state.negative.no[currentRelationIndex] = {
    ...state.negative.no[currentRelationIndex],
    ...Object.keys(row).reduce((prev, currentKey) => ({ ...prev, ['n_' + currentKey]: row[currentKey] }), {}),
    relationStatus: '2',
  }

  // 删除掉正数明细集合里关联的数据
  const positiveIndex = state.positive.no.findIndex((item) => item.id === row.id)
  state.positive.no.splice(positiveIndex, 1)



  // 找到所有的待关联数据的索引
  const indexes = state.negative.no.filter(({ relationStatus }) => relationStatus == '0' ||  relationStatus == '1').map((_,index) => index)

  if(indexes.length === 0){
    // 已全部关联 -> 提交
    const data = state.negative.no.map(({id, n_id}) => ({
      main_id: n_id,
      voice_id: id
    }))

    relationTask.run(httpRelationDetail({ data }))
  } else {
    // 找到离当前关联数据最近的一条待关联数据
    const index = state.negative.no.findIndex(item => item.relationStatus == '0')
    state.negative.no[index].relationStatus = '1'
  }
}

function onUnRelation(index){
  // 将当前正在关联的取消
  const currentRelationIndex = state.negative.no.findIndex(({relationStatus}) => relationStatus === '1')
  state.negative.no[currentRelationIndex].relationStatus = '0'


  // 将正在关联的状态更新到取消关联的数据, 并将原正数数据

  const negative = {}
  const positive = {}

  Object.keys(state.negative.no[index]).forEach(key => {
    if(key.indexOf('n_') !== -1){
      const [_, currentKey] = key.split('n_')
      positive[currentKey] = state.negative.no[index][key]
    }else{
      negative[key] =  state.negative.no[index][key]
    }
  })


  state.negative.no[index] = { ...negative, relationStatus: '1' }
  state.positive.no.push({ ...positive })

  // 排序
  state.positive.no.sort((a,b) => a.id - b.id)
}


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

function tableRowClassName({ row }){
  if(row.relationStatus == '1') return 'success-row'
}
</script>


<template>
  <div class="flex flex-col border border-[#ebeef5]" v-loading="invoiceDetailTask.loading || relationTask.loading">
    <div class="flex border-b-1 border-[#ebeef5]">
      <div class="flex-1 border-r-1 border-[#ebeef5] p-[5px] overflow-hidden">
        <h3 class="font-bold">无需关联</h3>
        <DataTable :data="state.notRelation" />
      </div>
      
      <div class="flex-1 p-[5px] overflow-hidden">
        <h3 class="font-bold">可关联明细</h3>
        <DataTable
          :cat_code="currentNegative.cat_code"
          :data="state.positive.no" 
          @relation="onRelation"
          isSelection
          colorRow
        />
      </div>
    </div>


    <div class="flex">
      <ElTable 
        class="mt-[10px] custom-detail-table" 
        border 
        size="small" 
        :data="state.negative.no"
        :row-class-name="tableRowClassName"
      >
        <ElTableColumn label="负数明细">
          <ElTableColumn label="明细ID" prop="id" min-width="60px" show-overflow-tooltip />
          <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="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 />
        </ElTableColumn>
        
        <ElTableColumn label="状态" width="90px">
          <template #="{ row }">
            <ElTag>
              {{ statusOptions.find(item => item.value === row.relationStatus)?.label || '--' }}
            </ElTag>
          </template>
        </ElTableColumn>
        
        <ElTableColumn label="正数明细">
          <ElTableColumn label="明细ID" prop="n_id" min-width="60px" show-overflow-tooltip />
          <ElTableColumn label="发票明细类目编号" prop="n_cat_code" min-width="140px" show-overflow-tooltip />
          <ElTableColumn label="货物或应税劳务、服务名称" prop="n_good_name" min-width="180px" show-overflow-tooltip />
          <ElTableColumn label="数量" prop="n_num" width="80px" show-overflow-tooltip />
          <ElTableColumn label="单价" prop="n_unit_price" width="120px" show-overflow-tooltip />
          <ElTableColumn label="金额" prop="n_amount" width="80px" show-overflow-tooltip />
          <ElTableColumn label="税率" prop="n_tax" width="80px" show-overflow-tooltip />
          <ElTableColumn label="税额" prop="n_tax_amount" width="80px" show-overflow-tooltip />
          <ElTableColumn label="税后总额" prop="n_total_amount" width="120px" show-overflow-tooltip />
        </ElTableColumn>


        <ElTableColumn fixed="right" label="操作" width="75px">
        <template #="{ row, $index }">
           <ElPopconfirm title="是否确认解除关联" v-if="row.relationStatus === '2'" @confirm="onUnRelation($index)">
              <template #reference>
                <ElButton
                  link
                  size="small" 
                  type="primary" 
                >解除关联</ElButton>
              </template>
           </ElPopconfirm>
        </template>
      </ElTableColumn>
      </ElTable>
    </div>
  </div>
</template>
