<script setup lang="ts">
import { computed, reactive, ref } from "vue";
import { cg_order_type_options, tax_list } from "/@/utils/status"
import { ElButton, ElCol, ElForm, ElFormItem, ElMessage, ElOption, ElSelect, ElTooltip } from "element-plus"
import { httpCompanies } from "/@/api/invoiceInOut/productManager"
import RemoteSelect from "/@/components/RemoteSelect";
import InvoiceTitle from "./InvoiceTitle.vue";
import { rules } from "./rules"

import { UnitInput } from "/@/components/Input"

import { convertInvoiceTitle, convertInvoiceTitleData, convertPurchaseInvoiceTitleData, createInitalData } from "./shared"

import { useCurrentCompany, useTask } from "/@/hooks/core"
import { useRouter } from "vue-router"

import ChooseGoodModal from "./ChooseGoodModal/index.vue"
import ChildGoodEditModal from "./ChildGoodEditModal.vue";


import { httpInvoiceList } from "/@/api/InvoiceSales/invoiceApply";
import { httpAdd } from "/@/api/invoiceInOut/productManager";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import QueryCategory from "./query-category.vue";

import dayjs from "dayjs";

const { current } = useCurrentCompany()

const rulesRef = computed(() => ({
  ...rules,
  skuCode: [
    {
      required: formData.value.good_source == "1",
      message: "请输入商品编号",
      trigger: "change"
    }
  ]
}))

const router = useRouter()
const formRef = ref<InstanceType<typeof ElForm> | null>(null)

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



const createTask = useTask({ success(){ router.push('/invoiceInOut/productManager') } })
const formData = ref(createInitalData())

const sellerInvoiceTitle = ref<Record<string, string>>({});
const purchaserInvoiceTitle = ref<Record<string, string>>({});

async function submit(){
  if(formData.value.is_combind === '1' && formData.value.childArr.length === 0){
    ElMessage.warning('请选择至少一个子商品')
    return
  }

  if(formData.value.is_combind === '0'){
    formData.value.childArr = []
  }


  if(formData.value.subunit_price > formData.value.unit_price){
    ElMessage.warning('成本税后单价必须大于或等于成本税前单价')
    return
  }

  try{
    await formRef.value?.validate()
    createTask.run( httpAdd({
      ...formData.value,
      skuCode: formData.value.good_source == '1' ? formData.value.skuCode : generateNumber(),
      childArr: formData.value.childArr.map(({ child_id, child_num }) => ({ child_id, child_num }))
    }))

  }catch(err){
    console.log(err)
  }
}

function handleInvoiceTitle(_isSeller: boolean, invoiceTitle: Record<string, string> ) {
  if (!_isSeller) {
    invoiceTitle = state.companies.find(item => item.company_license === formData.value.buyer_code)
    formData.value.buyer_name = invoiceTitle.company_name
  } else{
    formData.value.seller_name = invoiceTitle.name
  }

  if (!invoiceTitle) {
    if (_isSeller) { return (sellerInvoiceTitle.value = {}); }
    return (purchaserInvoiceTitle.value = {});
  }

  _isSeller
    ? (sellerInvoiceTitle.value = convertInvoiceTitleData(convertInvoiceTitle(invoiceTitle)))
    : (purchaserInvoiceTitle.value = convertPurchaseInvoiceTitleData(invoiceTitle));
}


const setSellerInvoiceTitle = handleInvoiceTitle.bind(null, true);
const setPurchaserInvoiceTitle = handleInvoiceTitle.bind(null, false);


function handleSubmit(list: any[]){
  const currentIds = formData.value.childArr.map(({ id }) => id)
  const appends: any[] = []

  for(const item of list){
    if(currentIds.includes(item.id)){ continue }
    appends.push(item)
  }

  formData.value.childArr = [ ...formData.value.childArr, ...appends ]
}


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

(async function initialData(){
  const result = await httpCompanies({ size: 10000 })
  if(result.code == 0){
    state.companies = [...result.data.list]
    const item = state.companies.find(item => item.companyNo === current.value.companyNo)
    formData.value.buyer_code = item.company_license
    setPurchaserInvoiceTitle(item)
  }
})()


function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值，含最小值 
}

function generateNumber(){
  let date = dayjs(new Date()).format('YY-MM-DD HH:mm:ss')
  date = date.replace(/-/g, '')
  date = date.replace(/:/g, '')
  date = date.replace(/ /g, '')
  let ms = String(dayjs().get('millisecond'))
  if(ms.length === 2){ ms = '0' + ms }
  if(ms.length === 1){ ms = '00' + ms }
  
  let prefix = formData.value.is_combind == '0' ? 'PKU' : 'PSU'
  const randomSuffix = getRandomIntInclusive(10, 99)
  const code = prefix + date + ms + randomSuffix
  return code
}


function handleGoodSourceChange(value){
  if(value == '2') formData.value.skuCode = ''
}
</script>

<template>
  <ElForm ref="formRef" :rules="rulesRef" :model="formData" v-loading="createTask.loading">
    <ElRow :gutter="10">
      <ElCol :span="12">
        <ElFormItem label="购买方公司" prop="buyer_code">
          <ElSelect style="width: 100%" placeholder="购买方公司" v-model="formData.buyer_code"
            @change="setPurchaserInvoiceTitle" disabled>
            <ElOption v-for="item in state.companies" :label="item.company_name" :value="item.company_license" />
          </ElSelect>
        </ElFormItem>
        <InvoiceTitle :detail="purchaserInvoiceTitle" />
      </ElCol>
      
      <ElCol :span="12">
        <ElFormItem label="销售方公司" prop="seller_code">
          <RemoteSelect style="width: 100%" request-prop="name" :api="httpInvoiceList" response-val-prop="registercode"
            placeholder="销售方公司抬头" v-model:value="formData.seller_code" response-label-prop="name"
            @item-change="setSellerInvoiceTitle" />
        </ElFormItem>
        <InvoiceTitle :detail="sellerInvoiceTitle" />
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="商品来源" prop="good_source">
          <ElSelect @change="handleGoodSourceChange" v-model="formData.good_source" placeholder="商品来源"
            style="width: 100%">
            <ElOption label="采销商品" value="1" />
            <ElOption label="非采销商品" value="2" />
          </ElSelect>
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="组合类型" prop="is_combind">
          <ElSelect style="width: 100%" v-model="formData.is_combind">
            <ElOption label="非组合商品" value="0" />
            <ElOption label="组合商品" value="1" />
          </ElSelect>
        </ElFormItem>
      </ElCol>


      <ElCol :span="6">
        <ElFormItem label="订单商品类型" prop="good_type">
          <ElSelect v-model="formData.good_type" placeholder="订单商品类型" style="width: 100%">
            <ElOption v-for="opt in cg_order_type_options" :value="opt.value" :label="opt.label" />
          </ElSelect>
        </ElFormItem>
      </ElCol>


      <ElCol :span="6">
        <ElFormItem label="成本状态" prop="basic_status">
          <ElSelect v-model="formData.basic_status" placeholder="成本状态">
            <ElOption label="真实成本" value="1" />
            <ElOption label="预估成本" value="2" />
          </ElSelect>
        </ElFormItem>
      </ElCol>

      <ElCol :span="12">
        <ElFormItem label="发票商品名称" prop="inv_good_name">
          <ElInput v-model="formData.inv_good_name" placeholder="发票商品名称" />
        </ElFormItem>
      </ElCol>


      <ElCol :span="12">
        <ElFormItem label="订单商品名称" prop="goodName">
          <ElInput v-model="formData.goodName" placeholder="订单商品名称" />
        </ElFormItem>
      </ElCol>


      <ElCol :span="6">
        <ElFormItem label="商品编号" prop="skuCode">
          <ElInput placeholder="商品编号" v-model="formData.skuCode" :disabled="formData.good_source == '2'" />
        </ElFormItem>
      </ElCol>


      <ElCol :span="6">
        <ElFormItem label="单位" prop="unit">
          <ElInput v-model="formData.unit" placeholder="单位" />
        </ElFormItem>
      </ElCol>


      <ElCol :span="6">
        <ElFormItem label="规格" prop="spec">
          <ElInput v-model="formData.spec" placeholder="规格" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="重量" prop="unit_weight">
          <UnitInput unit="g" v-model="formData.unit_weight" placeholder="重量" :KeepDecimals="3" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="发票类型" prop="inv_type">
          <ElSelect v-model="formData.inv_type" placeholder="发票类型" style="width: 100%">
            <ElOption label="普票" value="0" />
            <ElOption label="专票" value="1" />
          </ElSelect>
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="成本税前单价" prop="subunit_price">
          <UnitInput 
            unit="元" 
            v-model="formData.subunit_price"
            placeholder="成本税前单价"
            :KeepDecimals="8" 
          />
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="成本税后单价" prop="unit_price">
          <UnitInput
            unit="元" 
            v-model="formData.unit_price"
            placeholder="成本税后单价"
            :KeepDecimals="8"
          />
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="商品代码" prop="good_code">
          <ElInput v-model="formData.good_code" placeholder="商品代码" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="12">
        <ElFormItem label="进项税目" prop="cat_code">
          <QueryCategory v-model="formData.cat_code" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="进项税率" prop="cat_tax">
          <ElSelect v-model="formData.cat_tax" placeholder="进项税率">
            <ElOption v-for="tax in tax_list" v-bind="tax" />
          </ElSelect>
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="分光" prop="spectral">
          <ElInput v-model="formData.spectral" placeholder="分光" style="width: 100%" />
        </ElFormItem>
      </ElCol>
    </ElRow>

    <ElRow v-if="formData.is_combind == '1'">
      <ElCol :span="24">
        <ElFormItem label="子商品">
          <ElTable border size="small" :data="formData.childArr">
            <ElTableColumn label="比例" prop="child_num" width="60px" />

            <ElTableColumn label="商品编号" prop="skuCode" />
            <ElTableColumn label="商品类型" prop="good_type">
              <template #="{ row }">
                <ElTag size="small">
                  {{ cg_order_type_options.find(item => item.value == row.good_type)?.label }}
                </ElTag>
              </template>
            </ElTableColumn>

            <ElTableColumn label="商品名称" prop="goodName" />

            <ElTableColumn width="80px">
              <template #header>
                <div class="w-full flex justify-between">
                  <p>操作</p>
                  <ElButton link size="small" type="primary" :icon="useRenderIcon('add')"
                    @click="state.visible = true" />
                </div>
              </template>

              <template #="{ $index }">
                <ElTooltip content="删除" placement="top">
                  <ElButton link size="small" type="danger" :icon="useRenderIcon('delete')"
                    @click="formData.childArr.splice($index, 1)" />
                </ElTooltip>

                <ElTooltip content="编辑" placement="top">
                  <ElButton link size="small" type="primary" :icon="useRenderIcon('edits')"
                    @click="handleChildGoodEdit($index)" />
                </ElTooltip>
              </template>
            </ElTableColumn>
          </ElTable>
        </ElFormItem>
      </ElCol>
    </ElRow>

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

    <ChooseGoodModal v-model:visible="state.visible" @submit="handleSubmit" />

    <ChildGoodEditModal v-model:visible="state.editVisible" :index="state.index" :data="state.data"
      @submit="(index, data) => formData.childArr[index] = { ...data }" />
  </ElForm>
</template>
