<template>
  <div class="w-full h-full flex flex-col">
    <div class="flex-1 overflow-y-auto">
      <FoldingPanel :title="Object.keys(formVal).length > 0 ? '修改商机' : '新建商机'">
        <template #foldContainer>
          <CustomerForm ref="formFormRef" :formJson="formJson" :formValue="formVal"></CustomerForm>
        </template>
      </FoldingPanel>

      <template v-for="(item, index) in businessItemProductList">
        <FoldingPanel :title="`相关产品(${index + 1})`">
          <template #foldingRight>
            <div class="flex items-center">
              <van-button icon="plus" color="#FF8B32" size="mini" class="relatedAddButton" @click="addBusinessItemProductList()">添加</van-button>
              <van-button icon="plus" color="#075985" size="mini" class="relatedAddButton" @click.stop="resetBusinessItemProductList(index)" v-if="businessItemProductList.length == 1">重置</van-button>
              <van-button icon="plus" color="#EE0A24" size="mini" class="relatedAddButton" @click.stop="deleteBusinessItemProductList(index)" v-if="businessItemProductList.length > 1">删除</van-button>
            </div>
          </template>
          <template #foldContainer>
            <NewAndModifiedRelatedProducts :form="item" />
          </template>
        </FoldingPanel>
      </template>
    </div>
    <div class="mar-20px ">
      <van-button type="primary" @click="onSubmit" class="w-full">
        {{ Object.keys(formVal).length > 0 ? '确定修改' : '确定添加' }}
      </van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onActivated } from 'vue';
import { useLifecycle } from '@hooks/useCommon.js';
import { GET_BUSINESS_OPPORTUNITY_DETAILS, NEW_BUSINESS_OPPORTUNITY_EDITING } from "@hooks/useApi"
import { defaultRelatedProductDataFields } from "@utility/defaultData"
import dayjs from 'dayjs';
import requests from "@common/requests";
import useToast from "@hooks/useToast"
import CustomerForm from '@components/common/formForm/formView.vue'
import FoldingPanel from '@components/common/foldingPanel.vue';
import NewAndModifiedRelatedProducts from '@pages/pageComponents/product/newAndModifiedRelatedProducts.vue'
import useRouterStore from "@store/useRouterStore.js";

const router = useRouterStore()
const props = defineProps({
  formJson: { required: true },
  formValue: { required: true },
});

const { toastText, toastSuccess, toastFail, toastLoading } = useToast()
const formFormRef = ref(null)
const formVal = ref({})
const businessItemProductList = ref([{...defaultRelatedProductDataFields}])

function onSubmit() {
  formFormRef.value.getJsonData().then((res) => {
    if(!res.data) {
      return
    }
    const newList = businessItemProductList.value.filter(item => item.productId)
    const flagVal = judgmentaAmounteEqual(res.data, newList)
    if(flagVal) {
      return
    }
    newList.forEach((item) => {
      item.typeName = item.productType
      delete item.id
    })
    const newForm = {
      ...props.formValue,
      ...res.data,
      expectedTransactionDate: res.data.expectedTransactionDate ? dayjs(new Date(res.data.expectedTransactionDate)).format('YYYY-MM-DD') : '',
      businessItemProductList: newList ? JSON.stringify(newList) : []
    }
    toastLoading('保存中', 0)
    requests.post(NEW_BUSINESS_OPPORTUNITY_EDITING, { ...newForm }).then(() => {
      toastSuccess('保存成功')
      setTimeout(() => {
        router.navigateBack({
          success: () => {
            router.eventEmit('moduleListRefreshData', {})
          }
        })
      }, 2000)
    }).catch((err) => {
      toastFail('保存失败:' + err.msg)
    })
  })
}

function judgmentaAmounteEqual(mob, arr) {
  if(!arr || arr.length <= 0) {
    return false;
  }
  let flag = false;
  const amounte = +mob.amountOfMoney || 0;
  const totalAmounte = arr.reduce((pre, cur) => pre + (+cur.totalPrice || 0), 0);

  console.log(amounte, totalAmounte)

  if (amounte != totalAmounte) {
    toastText(`商机金额${amounte > totalAmounte ? '大于' : '小于'}产品总金额，${amounte > totalAmounte ? '保存中...' : '请修改'}`)
    flag = true;
  }

  return (amounte > totalAmounte) ? false : flag;
}

function addBusinessItemProductList() {
  businessItemProductList.value.push({ ...defaultRelatedProductDataFields })
}

function resetBusinessItemProductList(index) {
  businessItemProductList.value.splice(index, 1, { ...defaultRelatedProductDataFields })
}

function deleteBusinessItemProductList(index) {
  businessItemProductList.value.splice(index, 1)
}

function getBusinessOpportunityDetails(row) {
  const { id } = row
  if(!id) {
    businessItemProductList.value = [{...defaultRelatedProductDataFields}]
    return
  }
  requests.post(GET_BUSINESS_OPPORTUNITY_DETAILS, { id }).then(({ data }) => {
    const { businessItemProducts } = data
    businessItemProductList.value = businessItemProducts.length > 0 ? businessItemProducts : [{...defaultRelatedProductDataFields}]
    console.log(businessItemProductList.value, '<==== businessItemProductList.value')
  })
}

useLifecycle({
  load: () => {
    formVal.value = props.formValue
    getBusinessOpportunityDetails(formVal.value)
  },
  init: () => {
    formVal.value = props.formValue
    getBusinessOpportunityDetails(formVal.value)
  }
});

onActivated(() => {
  
})
</script>

<style lang='scss' scoped>
/* 样式代码 */
</style>