<script setup lang="ts">
import { computed, reactive, ref } from "vue";

import { importOrderGoodColumns, importInvoiceGoodColumns, orderGoodColumns } from "./config/columns"
import { useDetail } from "/@/hooks/core/useDetail";
import BasicDescriptions from "/@/components/BasicDescriptions";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import ChooseGoodModal from "./components/ChooseGoodModal/index.vue"
import ChildGoodEditModal from "./components/ChildGoodEditModal.vue";

import { httpDetail, httpStatus } from "/@/api/invoiceInOut/inOutManager";
import { httpDetail as httpProductDetail } from "/@/api/invoiceInOut/productManager";
import { ElButton, ElCollapse, ElCollapseItem, ElForm, ElMessage, ElTable, ElTableColumn, ElTooltip } from "element-plus";
import ProductDetail from "/@/components/ProductDetail/index.vue"
import { useTask } from "/@/hooks/core";

import SealMonthPicker from "/@/components/SealMonthPicker/index.vue"
import { useUserInfo } from "/@/hooks/core/useUser";
import { addition } from "/@/utils/calc";

import BasicProducts from "/@/components/BasicProducts/index.vue"


const { title, collapses, id } = useDetail({ baseName: '出库', collapseLen: 5 });

const visible = ref(false)
const isJT = ref(false)
const productVisible= ref(false)
const productIndex = ref(0)
const productDetailTask = useTask()
const detailTask = useTask()

const { isSuperUser } = useUserInfo()
const state = reactive({ editVisible: false, index: -1, data: {} })

const loading = ref(false)
const formRef = ref<InstanceType<typeof ElForm> | null>(null)

const searchParameter = computed(() => {
  // 入库、入库红冲和出库红冲 只能选择真实成本的商品，出库类型可以选择预估成本商品
  if (!detailTask.data) return {}
  const baseParameter = {}
  return { ...baseParameter, good_type: String(detailTask.data?.goodType), status: '1', good_source: String(detailTask.data?.source) }
})

const total = computed(() => {
  const relaArrCopy = formData.value.goods.map(({ id, goodNum }) => ({ id, num: goodNum }))
  const mapId = {}
  let total = 0
  for (const item of relaArrCopy) {
    if (!mapId[item.id]) {
      mapId[item.id] = true
      const { num = '0'} = item
      total = addition(num, total)
    }
  }
  return total
})


const hasJT = computed(() => {
  const relaArrCopy = formData.value.goods.map(({ id, goodNum, isJT }) => ({ id, num: goodNum, isJT }))
  return relaArrCopy.some(({ isJT }) => isJT)
})

const notJTList = computed(() => {
  return formData.value.goods.filter(item => !item.isJT)
})

const formData = ref({ goods: [], month: '' })

const rules = {
  goods: [{ required: true, message: '请选择操作商品' }],
  month: [{ required: true, message: '请选择入账月份' }]
}

function handleGoodComfirm(values: any[]) {
  const ids = formData.value.goods.map(({ id }) => id)
  const list = []

  values.forEach(item => {
    if (!ids.includes(item.id)) { list.push(item) }
  })

  formData.value.goods = [...formData.value.goods, ...list,]
}

function handleChildGoodEdit(index: number) {
  state.index = index
  state.editVisible = true
  state.data = { ...formData.value.goods[index] }
}

function getSpanNumber(data, prop) {
  let length = Array.isArray(data) ? data.length : 0;
  if (length > 0) {
    let position = 0;
    let temp = data[0][prop];
    let result = [1];
    for (let i = 1; i < length; i++) {
      if (data[i][prop] == temp) {
        result[position] += 1;
        result[i] = 0;
      } else {
        position = i;
        result[i] = 1;
        temp = data[i][prop];
      }
    }
    return result;
  } else {
    return [0];
  }
}

function spanMethod({ row: _1, column: _2, rowIndex, columnIndex }: any) {
  if ([0, 1, 2, 3, 4 ,5, 9].includes(Number(columnIndex))) {
    let nameSpan = getSpanNumber(formData.value.goods, "id");
    return { rowspan: nameSpan[rowIndex], colspan: 1 };
  }
}

async function onSubmit() {
  try {
    await formRef.value.validate()
    
    const relaArrCopy = formData.value.goods.map(({ id, goodNum, unit_price, subunit_price }) => ({ 
      id, 
      unit_price,
      num: goodNum, 
      subunit_price, 
    }))

    const relaArr = []
    const mapId = {}

    for (const item of relaArrCopy) {
      if (!mapId[item.id]) {
        relaArr.push(item)
        mapId[item.id] = true
      }
    }

    if(Number(detailTask.data.balance_num) !== Number(total.value)){
      ElMessage.warning('操作数量必须等于待处理数量')
      return
    }

    const list = formData.value.goods.filter(item => !!item.num)

    if(list.length !== 0){
      ElMessage.warning('商品操作数量不能为空')
      return
    }

    loading.value = true
    const { code, message } = await httpStatus({ 
      relaArr, 
      manager_id: id.value,
      is_checkOrder: hasJT.value ? '1' : '0',
      fz_date: formData.value.month
    })
    loading.value = false

    if (code == 0) {
      ElMessage.success('操作完成')
      detailTask.run(httpDetail({ id: id.value }))
    } else {
      ElMessage.warning(message)
    }
  } catch (err) {
    console.log(err)
  }
}

function handleEditGood(index, data) {
  const { id } = formData.value.goods[index]
  formData.value.goods.forEach((item, index) => {
    if (item.id === id) {
      formData.value.goods[index].goodNum = data.goodNum
      const { goodNum, residue_stock } = data
      formData.value.goods[index].isJT = goodNum > residue_stock
      if (formData.value.goods[index].childNum) { 
        formData.value.goods[index].isJT = goodNum > residue_stock
        formData.value.goods[index].childActionNum = formData.value.goods[index].childNum * data.goodNum 
      }
    }
  })
}

function handleShowDetail(id, index){
  productVisible.value = true
  productIndex.value = index
  productDetailTask.run(httpProductDetail({ id }))
}

function handleDelete(index) {
  const { id } = formData.value.goods[index]
  formData.value.goods = formData.value.goods.filter((item) => item.id !== id)
}

id.value && detailTask.run(httpDetail({ id: id.value }))
</script>

<template>
  <div class="padding__container" v-loading="detailTask.loading">

    <ElCollapse v-model="collapses">
      <ElCollapseItem :title="title" name="1">
        <BasicDescriptions :columns="orderGoodColumns" :data="detailTask.data" v-if="detailTask.data" />
      </ElCollapseItem>

      <ElCollapseItem title="订单详情" name="2">
        <BasicDescriptions v-if="detailTask.data" :columns="importOrderGoodColumns" :data="detailTask.data" />
      </ElCollapseItem>

      <ElCollapseItem :title="'发票详情'" name="3">
        <BasicDescriptions v-if="detailTask.data" :columns="importInvoiceGoodColumns" :data="detailTask.data" />
      </ElCollapseItem>

      <ElCollapseItem title="商品信息" name="4" v-if="detailTask.data && detailTask.data.ProductRela.length !== 0">
        <!-- <ElTable size="small" border :data="detailTask.data.ProductRela">
          <ElTableColumn label="商品ID" prop="product_id" width="60px" show-overflow-tooltip />
          <ElTableColumn label="商品编号" prop="skuCode" show-overflow-tooltip />
          <ElTableColumn label="商品名称" prop="goodName" show-overflow-tooltip />
          <ElTableColumn label="操作数量" prop="num" width="80px" show-overflow-tooltip />
          <ElTableColumn label="操作人" prop="apply_name" width="80px" show-overflow-tooltip />
          <ElTableColumn label="创建时间" prop="create_time" show-overflow-tooltip />
          <ElTableColumn label="操作" width="100px">
            <template #="scope">
              <ElTooltip content="查看详情">
                <ElButton type="primary" link :icon="useRenderIcon('eye-view')"
                  @click="handleShowDetail(scope.row.product_id, scope.$index)" />
              </ElTooltip>
            </template>
          </ElTableColumn>
        </ElTable> -->
        <BasicProducts :ProductRela="detailTask.data.ProductRela" />
      </ElCollapseItem>



      <ElCollapseItem name="5" title="待处理信息"
        v-if="!isSuperUser && detailTask.data && (detailTask.data.status == '1' || detailTask.data.status == '4')"
        >
        <div class="w-full flex justify-between mb-[10px]">
          <p>待处理 {{ Number(detailTask.data.balance_num) }} / {{ total }}</p>
        </div>

        <ElForm ref="formRef" :rules="rules" :model="formData">
          <ElFormItem label="操作商品" prop="goods">
            <ElTable :span-method="spanMethod" border size="small" :data="formData.goods">
              <ElTableColumn label="商品ID" prop="id" width="60px" show-overflow-tooltip />
              <ElTableColumn label="商品编号" prop="skuCode" show-overflow-tooltip />
              <ElTableColumn label="商品名称" prop="goodName" show-overflow-tooltip />

              <ElTableColumn label="是否为计提" prop="residue_stock" width="80px" show-overflow-tooltip>
                <template #="{ row }">
                  {{ row.isJT ? '是' : '否'}}
                </template>
              </ElTableColumn>

              <ElTableColumn label="结存数" prop="residue_stock" width="80px" show-overflow-tooltip />
              <ElTableColumn label="操作数量" prop="goodNum" width="80px" show-overflow-tooltip />

              <ElTableColumn label="子商品编号" prop="childCode" show-overflow-tooltip />
              <ElTableColumn label="子商品比例" prop="childNum" show-overflow-tooltip />
              <ElTableColumn label="子商品操作数量" prop="childActionNum" width="110px" show-overflow-tooltip />

              <ElTableColumn width="70px" label="操作">
                <template #header>
                  <div class="w-full flex justify-between">
                    <span>操作</span>
                    <ElTooltip content="添加" placement="top">
                      <ElButton link size="small" type="primary" :icon="useRenderIcon('add')"
                        @click="isJT = false;visible = true" />
                    </ElTooltip>
                  </div>
                </template>

                <template #="{ $index }">
                  <ElTooltip content="编辑" placement="top">
                    <ElButton :icon="useRenderIcon('edits')" type="primary" size="small" link
                      @click="handleChildGoodEdit($index)" />
                  </ElTooltip>

                  <ElTooltip content="删除" placement="top">
                    <ElButton :icon="useRenderIcon('delete')" type="danger" size="small" link
                      @click="handleDelete($index)" />
                  </ElTooltip>
                </template>
              </ElTableColumn>
            </ElTable>
          </ElFormItem>

          <ElFormItem label="入账月份" prop="month">
            <SealMonthPicker placeholder="入账月份" v-model="formData.month" :company_code="detailTask.data.inv_seller_code" />
          </ElFormItem>
        </ElForm>

        <div class="flex w-full justify-end">
          <ElButton type="primary" @click="onSubmit">保存</ElButton>
        </div>
      </ElCollapseItem>
    </ElCollapse>

    <ChooseGoodModal v-model:visible="visible" :isJT="isJT" :otherSearchParameter="searchParameter"
      @submit="handleGoodComfirm" :skuCode="notJTList.length === 0 ? '' : notJTList[0].skuCode" />

    <ChildGoodEditModal :data="state.data" :index="state.index" v-model:visible="state.editVisible"
      @submit="handleEditGood" />

    <ElDialog center title="商品详情" v-model="productVisible" style="overflow: hidden">
      <div v-loading="productDetailTask.loading">
        <ProductDetail v-if="productDetailTask.data" :data="productDetailTask.data"
          :num="detailTask.data.ProductRela[productIndex].num"
          :time="detailTask.data.ProductRela[productIndex].create_time" />
      </div>
    </ElDialog>
  </div>
</template>
