<script setup lang="ts">
import { reactive, watch, nextTick, ref } from "vue"
import { invoiceTypeList, mapInvoiceTypeToLabel, useTypeOptions, mapUseTypeToLabel } from "/@/utils/status"
import { httpList, httpAdd } from "/@/api/invoiceSales/batchImportYunlong"
import { ElMessageBox, ElMessage } from "element-plus"
import { addition, division, subtraction } from "/@/utils/calc";
import InvoiceTitle from "./InvoiceTitle.vue"
import { useNav } from "/@/layout/hooks/nav";
import { useVModel } from "@vueuse/core"

const props = defineProps<{
  data: any[];
  visible: boolean;
  companyNo: string;
  sellerInvoiceTitle: any
  purchaserInvoiceTitle: any;
  startGroup: any
}>()


const emit = defineEmits(['updateGroup', 'updateSequenceNo', 'download', 'refresh', 'stop'])

const visible = useVModel(props, 'visible')
const { logout } = useNav();

const initialData = () => ({
  email: '',
  invtype: '',
  platform_type: '',
  orderArr: [],
  remark: ''
})

const state = reactive({
  tableloading: false,
  formloading: false,
  orderData: [],
  currentGroup: 1,
  groupCount: 0
})




const wating = () => new Promise((resolve) => setTimeout(() => { resolve(true) }, 2000))
const waitState = reactive({ visible: false, text: '', timer: 3 })

const isStop = ref(false)

const onWaitNext = (text: string, callback: Function) => {
  state.orderData = []
  const nextGroup = state.currentGroup + 1

  if (nextGroup > state.groupCount) {
    visible.value = false
    
    const isOk = props.data.every(item => String(item.status) === '2')

    if (isOk) {
      ElMessage.success('批量创建完成')
    } else {
      ElMessage.error('批量创建失败')
    }

    emit('stop', false)
    return
  } else {
    waitState.visible = true
    waitState.text = text
    waitState.timer = 3


    const id = setInterval(() => {
      if (waitState.timer !== 0) {
        waitState.timer -= 1
      } else {
        waitState.visible = false
        waitState.text = ''
        waitState.timer = 3
        window.clearInterval(id)
        if (isStop.value) {
          isStop.value = false
        } else {
          callback()
        }
      }

    }, 1000)
  }
}

const formData = ref({ ...initialData() })

async function setFormData(groupData: any[]) {
  formData.value = {
    email: groupData[0].email,
    invtype: mapInvoiceTypeToLabel[groupData[0].invtype],
    platform_type: mapUseTypeToLabel[groupData[0].platform_type],
    remark: [...new Set(groupData.map(({ poCode }) => poCode))].join(''),
    orderArr: []
  }

  /* 合并相同的订单 */
  const mapSequenceNo: Record<string, any[]> = {}
  for (const group of groupData) {
    const { sequenceNo, inv_fee } = group
    if (!mapSequenceNo[sequenceNo]) {
      mapSequenceNo[sequenceNo] = []
      mapSequenceNo[sequenceNo].push({ inv_fee })
    } else {
      mapSequenceNo[sequenceNo].push({ inv_fee })
    }
  }

  for (const sequenceNo of Object.keys(mapSequenceNo)) {
    formData.value.orderArr.push({
      sequenceNo,
      platform_type: formData.value.platform_type,
      inv_fee: mapSequenceNo[sequenceNo].reduce((prev, current) => Number(addition(prev, current.inv_fee)).toFixed(2), 0)
    })
  }

  const parameter = {
    inv_is: '1',
    status: '3',
    is_comon: "1",
    cat_status: '2',
    inv_status: '0',
    companyNo: props.companyNo,
    customerNo: "GS2404151642335170",
    platform_type: formData.value.platform_type,
    sequenceNo: formData.value.orderArr.map(({ sequenceNo }) => sequenceNo).join(','),
  }

  try {
    state.tableloading = true
    await wating()
    const result = await httpList(parameter)
    state.tableloading = false

    if (result.code == 0) {
      /* 搜索到的数组和组内数据数量不一致 */
      if (result.data.length !== formData.value.orderArr.length) {
        const sourceSequenceNo = result.data.map(({ sequenceNo }) => sequenceNo)
        const targetSequenceNo = formData.value.orderArr.map(({ sequenceNo }) => sequenceNo)
        const data = targetSequenceNo.filter(sequenceNo => !sourceSequenceNo.includes(sequenceNo))

        targetSequenceNo.filter(sequenceNo => !sourceSequenceNo.includes(sequenceNo)).forEach(sequenceNo => {
          emit('updateSequenceNo', { sequenceNo, group: state.currentGroup, remark: '查询不到订单', status: 3 })
        })

        data.forEach(sequenceNo => { formData.value.orderArr = formData.value.orderArr.filter(item => item.sequenceNo !== sequenceNo) })
      }

      const noPriceSequenceNos = []
      result.data.forEach(item => {
        const index = formData.value.orderArr.findIndex(({ sequenceNo }) => sequenceNo === item.sequenceNo)
        const target = formData.value.orderArr[index]
        item.current_inv_fee = target.inv_fee
        item.current_inv_num = Number(division(target.inv_fee, item.goodPrice)).toFixed(8)

        // 1.金额和未开票金额一致 数量为未开票数量
        if (

          (Number(item.current_inv_fee) === Number(item.winv_fee)) &&
          (Number(item.current_inv_num) !== Number(item.winv_num)) &&
          Math.abs(Number(subtraction(item.current_inv_num, item.winv_num))) <= 1 &&
          String(Number(item.current_inv_num)).indexOf('.') !== -1
        ) {
          item.current_inv_num = Number(item.winv_num).toFixed(8)
        }


        formData.value.orderArr[index].num = item.current_inv_num
        const { current_inv_fee, ainv_fee, inv_fee, apay_fee, sequenceNo, pay_tag_fee } = item
        
        const invTotal = addition(addition(current_inv_fee, ainv_fee), inv_fee)
        const payTotal = +  addition(pay_tag_fee, apay_fee)
        // console.log(
        //   '本次开票:' + current_inv_fee,
        //   '已开票金额:' + ainv_fee,
        //   '开票中金额:' + inv_fee
        // )

        //   '回款标签金额:' + pay_tag_fee,
        //   '已回款金额' + apay_fee
        // )

        // console.log('票金额:' + invTotal)
        // console.log('款金额:' + payTotal)


        if (invTotal > payTotal) {
          emit('updateSequenceNo', { sequenceNo, group: state.currentGroup, remark: '订单已开票金额+开票中金额+本次开票金额必须小于或等于已认款金额+回款标签金额', status: 3 })
          noPriceSequenceNos.push(sequenceNo)
        }
      })

      formData.value.orderArr = formData.value.orderArr.filter(({ sequenceNo }) => !noPriceSequenceNos.includes(sequenceNo))
      if (formData.value.orderArr.length === 0) {
        onWaitNext('创建失败', () => onNext())
        return
      }


      state.orderData = result.data
      state.formloading = true
      await wating()


      // console.log('参数：',formData.value)
      const { code, message, data } = await httpAdd({
        ...formData.value,
        companyType: '01',
        buyNo: "GS2404151642335170",
        companyNo: props.companyNo,
        exam_remark: '',
        is_comon: '1'
      })

      // const results = { code : 0, message: '', data:  {} }
      // const { code, message, data } = results

      // const {} = {};
      state.formloading = false

      if (code == 0) {
        // 创建成功, 更新状态，下一分组
        emit('updateGroup', { group: state.currentGroup, remark: '开票申请编号' + data.invNo, status: 2 })
        onWaitNext('创建成功', onNext)

      } else if (Number(code) >= 101 && Number(code) <= 140) {
        ElMessageBox.alert('下载当前导入进度后将会登出', '登录失效', { type: 'error' })
          .then(() => {
            emit('download')
            logout()
          })
          .catch(() => {
            emit('download')
            logout()
          })
        return
      } else {
        // 创建失败, 更新状态，下一分组
        emit('updateGroup', { group: state.currentGroup, remark: message, status: 3 })
        onWaitNext('创建失败', onNext)
      }
    } else if (Number(result.code)) {
      ElMessageBox.alert('下载当前导入进度后将会登出', '登录失效', { type: 'error' })
        .then(() => {
          emit('download')
          logout()
        })
        .catch(() => {
          emit('download')
          logout()
        })
      return
    } else {
      // 处理异常,写入备注
      emit('updateGroup', { group: state.currentGroup, remark: result.message, status: 3 })
      onWaitNext('创建失败', onNext)
    }
  } catch (error) {
    state.tableloading = false
    // 处理异常,写入备注
    emit('updateGroup', { group: state.currentGroup, remark: error.message, status: 3 })
    onWaitNext('创建失败', onNext)
  }
}

function onNext() {
  const nextGroup = state.currentGroup + 1
  if (nextGroup > state.groupCount) {
    /**
     * 已经完成
     *  1. 下载导入的文件
     *  2. 关闭模态框
     *  3. 刷新导入页
    */
    visible.value = false

    const isOk = props.data.every(item => String(item.status) === '2')

    console.log(props.data)


    if(isOk){
      ElMessage.success('批量创建完成')
    } else {
      ElMessage.error('批量创建失败')
    }

    return
  } else {
    /**
     * 进入下一组
     * 1. 更改导入页组的状态
    */
    emit('updateGroup', { group: nextGroup, status: 1, remark: '' })
  }

  state.currentGroup = nextGroup
  const currentGroupData = props.data.filter(({ group }) => group == state.currentGroup)
  setFormData(currentGroupData)
}

function onStop() {
  isStop.value = true
  visible.value = false
  waitState.visible = false
  emit('stop', true, state.currentGroup)
}


watch(() => visible.value, () => {
  if (!visible.value) return
  nextTick(() => {
    const groups = [...new Set(props.data.map(({ group }) => group))]
    const max = Number(groups[groups.length - 1])
    state.groupCount = max
    state.currentGroup = props.startGroup
    onNext()
  })
}, {
  immediate: true
})
</script>

<template>
  <ElDialog width="1200px" v-model="visible" title="开票申请创建" center top="10px" :show-close="false">

    <ElDialog width="400px" center append-to-body v-model="waitState.visible" :title="waitState.text"
      :show-close="false">
      <p class="font-bold text-center">当前第{{ state.currentGroup }}组 , {{ waitState.timer }}后创建下一组数据</p>
      <div class="w-full flex justify-end">
        <ElButton type="primary" @click="onStop">暂停创建</ElButton>
      </div>
    </ElDialog>

    <ElTag class="font-bold mb-[10px]">当前第 {{ state.currentGroup }} 组 , 共 {{ state.groupCount }} 组</ElTag>
    <ElForm v-loading="state.formloading">
      <ElRow :gutter="10">
        <!-- <ElCol :span="12">
          <ElFormItem label="销售方公司抬头">
            <div class="flex flex-col w-full">
              <ElInput 
                :modelValue="(sellerInvoiceTitle || {}).invoice_title" 
                class="mb-[10px]" 
                disabled 
              />

              <InvoiceTitle :detail="sellerInvoiceTitle || {}" />
            </div>
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="购买方公司抬头">
            <div class="flex flex-col w-full">
              <ElInput
                :modelValue="(purchaserInvoiceTitle || {}).invoice_title" 
                class="mb-[10px]" 
                disabled
              />
              <InvoiceTitle :detail="purchaserInvoiceTitle || {}" />
            </div>
          </ElFormItem>
        </ElCol> -->

        <ElCol :span="8">
          <ElFormItem label="发票类型">
            <ElSelect v-model="formData.invtype" class="w-full" disabled>
              <ElOption v-for="opt in invoiceTypeList" :value="opt.value" :label="opt.label" :key="opt.value" />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <ElCol :span="8">
          <ElFormItem label="电子邮箱">
            <ElInput v-model="formData.email" disabled />
          </ElFormItem>
        </ElCol>

        <ElCol :span="8">
          <ElFormItem label="平台类型">
            <ElSelect v-model="formData.platform_type" class="w-full" disabled>
              <ElOption v-for="opt in useTypeOptions" :value="opt.value" :label="opt.label" :key="opt.value" />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <ElFormItem label="发票备注">
            <ElInput v-model="formData.remark" disabled />
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElTable border size="small" v-loading="state.tableloading" :data="state.orderData">
        <ElTableColumn label="产品编号" width="120px" prop="goodNo" show-overflow-tooltip />

        <ElTableColumn label="商品名称" width="120px" prop="goodName" show-overflow-tooltip />

        <ElTableColumn label="开票商品名称" show-overflow-tooltip prop="inv_good_name" width="140px" />


        <ElTableColumn label="品牌" width="60px" prop="goodBrand" show-overflow-tooltip />

        <ElTableColumn label="单位" width="60px" prop="goodUnit" show-overflow-tooltip />


        <ElTableColumn label="单价" width="60px" prop="goodPrice" show-overflow-tooltip />

        <ElTableColumn label="数量" align="center">
          <ElTableColumn label="总计" width="80px" show-overflow-tooltip>
            <template #="{ row }">
              {{ Number(addition(Number(addition(row.inv_num, row.winv_num)).toFixed(2), row.current_inv_num)).toFixed(8)
              }}
            </template>
          </ElTableColumn>

          <ElTableColumn label="已核销" prop="inv_num" width="80px" show-overflow-tooltip />

          <ElTableColumn label="未核销" prop="winv_num" width="80px" show-overflow-tooltip />

          <ElTableColumn label="此次核销" prop="current_inv_num" width="80px" show-overflow-tooltip />
        </ElTableColumn>

        <ElTableColumn label="总价" width="80px" show-overflow-tooltip>
          <template #="{ row }">
            {{ Number(addition(Number(addition(row.inv_fee, row.winv_fee)).toFixed(2), row.current_inv_fee)).toFixed(2)
            }}
          </template>
        </ElTableColumn>

        <ElTableColumn label="关联发票信息" align="center">
          <ElTableColumn label="已核销金额" prop="inv_fee" width="100px" show-overflow-tooltip />

          <ElTableColumn label="未核销金额" prop="winv_fee" width="100px" show-overflow-tooltip />

          <ElTableColumn label="此次核销金额" prop="current_inv_fee" width="100px" show-overflow-tooltip />
        </ElTableColumn>
      </ElTable>
    </ElForm>
  </ElDialog>
</template>
