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

import { importInvoiceGoodColumns, importOrderGoodColumns, 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 { httpJTDetail, httpCheckAccrue, httpDetail } from "/@/api/invoiceInOut/inOutManager";
import { ElForm, ElFormItem, ElMessage, ElOption, ElSelect } from "element-plus";
import { useTask } from "/@/hooks/core";



import SealMonthPicker from "/@/components/SealMonthPicker/index.vue"
import { UnitInput } from "/@/components/Input";
import { useUserInfo } from "/@/hooks/core/useUser";
import { httpProductDetail } from "/@/api/invoiceInOut/inventoryCheck";
import ProductDetail from "/@/components/ProductDetail/index.vue"
import { addition, multiplication } from "/@/utils/calc";

const { title, collapses, id } = useDetail({ baseName: '计提出库明细处理', collapseLen: 5 });

const visible = ref(false)


const { isSuperUser } = useUserInfo()

const orderDetailTask = useTask({ success(data){
  console.log(data, '🚀~~');
} })


const detailTask = useTask({ success({ manager_id }){
  orderDetailTask.run(httpDetail({ id: manager_id }))
} })

const productIndex = ref(0)
const productVisible = ref(false)
const productDetailTask = 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 {}
  const basicParameter = detailTask.data.type == '2' ? { basic_status: '1'  } : { basic_status: '1' }
  return { ...basicParameter, good_type: detailTask.data?.Manager.goodType }
})

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

const rules = {
  goods: [{ required: true, message: '请选择操作商品' }],
  checkFee: [{ required: true, message: '请输入调整金额' }],
  is_CheckOrder: [{ 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]
  calcCheckFee()
}

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, 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 httpCheckAccrue({ 
      status: '2', 
      id: id.value, 
      idArr: relaArr,
      checkFee: formData.value.checkFee, 
      isAddCheck: formData.value.is_CheckOrder 
    })
    
    loading.value = false

    if (code == 0) {
      ElMessage.success('操作完成')
      detailTask.run(httpJTDetail({ 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)
}

function calcCheckFee(){
  let checkFee = '0'

  formData.value.goods.forEach(item => {
    checkFee += Number(Number(item.goodNum * item.subunit_price).toFixed(2)).toFixed(2)
  })

  formData.value.checkFee = checkFee
}

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


watch(() =>formData.value.goods, () => {
  if(!detailTask.data) return
  let total = 0
  formData.value.goods.forEach(item => { total = addition(multiplication(item.goodNum, item.subunit_price), total) })
}, {
  deep: true,
  immediate: true
})

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

<template>
  <div class="padding__container" v-loading="detailTask.loading || orderDetailTask.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>

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

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

          <ElCollapseItem title="商品信息" name="4" v-if="detailTask.data && detailTask.data.status != '1'">
            <ElTable size="small" border :data="orderDetailTask.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" 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>
          </ElCollapseItem>

          <!-- && detailTask.data.type == '1' -->
          <ElCollapseItem title="出入库信息确认" name="2"
            v-if="detailTask.data && detailTask.data.status == '1' && !isSuperUser">
            <ElForm ref="formRef" :rules="rules" :model="formData" label-width="140px">
              <ElFormItem label="关联凭证" prop="goods">
                <ElTable :span-method="spanMethod" border size="small" :data="formData.goods">
                  <ElTableColumn label="商品ID" prop="id" width="60" show-overflow-tooltip />
                  <ElTableColumn label="商品编号" prop="skuCode" show-overflow-tooltip />
                  <ElTableColumn label="商品名称" prop="goodName" show-overflow-tooltip />
                  <ElTableColumn label="账面数量" prop="total_stock" show-overflow-tooltip />
                  <ElTableColumn label="目标商品比例" prop="spbl" show-overflow-tooltip />
                  <ElTableColumn label="关联数量" prop="goodNum" show-overflow-tooltip />
                  <ElTableColumn label="税前单价" prop="subunit_price" show-overflow-tooltip />
                  <ElTableColumn label="税后总价" prop="unit_price" width="140px" 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="checkFee">
                <UnitInput disabled v-model='formData.checkFee' unit="元" placeholder="调整费用" />
              </ElFormItem>

              <ElFormItem label="是否添加至调整单" prop="is_CheckOrder">
                <ElSelect v-model="formData.is_CheckOrder">
                  <ElOption label="是" value="1" />
                  <ElOption label="否" value="2" />
                </ElSelect>
              </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" />

    <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.Manager[productIndex].num" />
      </div>
    </ElDialog>
  </div>
</template>
