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

import { 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 { ElForm, ElMessage } from "element-plus";
import { useTask } from "/@/hooks/core";

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


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

const visible = ref(false)

const detailTask = useTask()

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 {}
  return detailTask.data.type == '2' ? { basic_status: '1'  } : { basic_status: '2' }
})

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

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

const disabledTomorrow = (time) => {
  const now = new Date();
  return time.getTime() > now.setHours(0, 0, 0, 0);
};

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 }) => ({ id, num: goodNum }))

    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">
    <ElTabs>
      <ElTabPane :label="title">
        <ElCollapse v-model="collapses">
          <ElCollapseItem :title="title" name="1">
            <BasicDescriptions
              :columns="orderGoodColumns" 
              :data="detailTask.data" 
              v-if="detailTask.data"
            />
          </ElCollapseItem>

          <!-- && detailTask.data.type == '1' -->
          <ElCollapseItem 
            title="出入库信息确认" 
            name="2" 
            v-if="detailTask.data && detailTask.data.status == '1'"
          >
            <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')"
                          type="danger"
                          size="small"
                          link
                          @click="handleDelete($index)"
                        />
                      </ElTooltip>
                    </template>
                  </ElTableColumn>
                </ElTable>
              </ElFormItem>

              <ElFormItem label="入账月份" prop="month">
                  <SealMonthPicker  placeholder="入账月份" :company_code="detailTask.data.buyer_code"  />
              </ElFormItem>
            </ElForm>

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

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