<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";



const { title, collapses, id } = useDetail({ baseName: '入库', collapseLen: 5 });
const visible = ref(false)

// httpList


const { isSuperUser } = useUserInfo()
const productDetailTask = useTask()

const detailTask = useTask({ success(data) {
  const { ProductRela } = data
  const { product_id } = ProductRela[0]
  productDetailTask.run(httpProductDetail({ id: product_id }))
}})


const productDetail = computed(() => {
  if (detailTask.data && detailTask.data.ProductRela){
    return detailTask.data.ProductRela[0]
  }
  return {}
})



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


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

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


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 = [...list,  ...formData.value.goods]
}

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, 7].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, num: goodNum, unit_price, subunit_price }))

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

    loading.value = true
    const { code, message } = await httpStatus({ relaArr, manager_id: id.value })
    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
      if(formData.value.goods[index].childNum){ formData.value.goods[index].childActionNum = formData.value.goods[index].childNum * data.goodNum }
    }
  })
}

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="productDetailTask.data && detailTask.data.status == '2'">
            <ProductDetail 
              :data="productDetailTask.data" 
              :num="productDetail?.num" 
              :time="productDetail?.create_time"
            />
          </ElCollapseItem>

          <ElCollapseItem 
            title="出入库信息确认" 
            name="5"
            v-if="!isSuperUser && detailTask.data && detailTask.data.status == '1' || detailTask.data.status == '4'">
            <ElForm ref="formRef" :rules="rules" :model="formData">
              <ElFormItem label="操作商品" prop="goods">
                <ElTable :span-method="spanMethod" border size="small" :data="formData.goods">
                  <ElTableColumn label="商品编号" prop="skuCode" show-overflow-tooltip />
                  <ElTableColumn label="商品名称" prop="goodName" show-overflow-tooltip />
                  <ElTableColumn label="操作数量" prop="goodNum" show-overflow-tooltip />
                  <ElTableColumn label="子商品编号" prop="childCode" show-overflow-tooltip />
                  <ElTableColumn label="销售方公司纳税识别号" width="140px" prop="seller_code" show-overflow-tooltip />
                  <ElTableColumn label="子商品比例" prop="childNum" show-overflow-tooltip />
                  <ElTableColumn label="子商品操作数量" prop="childActionNum" 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="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')" @click="handleDelete($index)" type="danger"
                          size="small" link />
                      </ElTooltip>
                    </template>
                  </ElTableColumn>
                </ElTable>
              </ElFormItem>

              <ElFormItem label="入账月份" prop="month">
                <SealMonthPicker 
                  placeholder="入账月份"
                  v-model="formData.month" 
                  :company_code="detailTask.data.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" 
      :otherSearchParameter="searchParameter" 
      @submit="handleGoodComfirm" 
    />

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