<script setup lang="ts">
import { computed, reactive, ref } from "vue";
import { httpCompanies } from "/@/api/invoiceInOut/productManager"
import { createInitalData } from "./shared"
import { useTask } from "/@/hooks/core"
import { useRouter } from "vue-router"


import ChooseGoodModal from "./ChooseGoodModal/index.vue"
import { NumberInput } from "/@/components/Input"

import { rules } from "./shared"
import BasicDescriptions from "/@/components/BasicDescriptions";
import { goodColumns } from "../config/columns";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";


import { httpAdd } from "/@/api/invoiceInOut/inventoryCheck";

import { batchCreateTempalte } from "./BatchCreateModal/columns-config"

import { 
  ElFormItem,
  ElTooltip,
  ElButton, 
  ElInput, 
  ElForm, 
  ElCol,
  ElSelect,
  ElOption,
  ElMessage
} from "element-plus"


const detail = ref<any>(null)

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

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

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

const reComputedNumber = computed(() => {
  const ykNum = (detail.value?.residue_stock - Number(formData.value.check_num)) || 0;
  const  yKPrice =  ykNum * detail.value?.subunit_price || 0

  if(Number(yKPrice) === 0 && formData.value.check_type == '2'){
    formData.value.check_type = ''
  }

  return {
    ykNum,
    yKPrice: ykNum * detail.value?.subunit_price || 0
  }
})


const formData = ref(createInitalData())
const createTask = useTask({ 
  success(){ 
    ElMessage.success('创建成功!');
    router.push('/invoiceInOut/inventoryCheck'); 
  } 
})

async function submit(){
  try{
    await formRef.value?.validate()
    createTask.run(httpAdd(formData.value))
  }catch(err){
    console.log(err)
  }
}


function handleSubmit(list: any[]){
  detail.value = list[0]
  formData.value.product_id = list[0].id
}

function handleChoose(){
  detail.value = null
  formData.value.product_id = ''
}

(async function initalData(){
  const result = await httpCompanies({ size: 10000 })
  if(result.code == 0){ state.companies = [...result.data.list] }
})()
</script>

<template>
  <ElForm
    ref="formRef"
    :rules="rules" 
    :model="formData" 
    v-loading="createTask.loading"
    label-width="140px"
  >
    <ElRow>
      <ElCol :span="24">
        <ElFormItem label="商品信息" prop="product_id">
          <ElInput  v-if="!detail" placeholder="商品信息" @click="state.visible = true"  />

          <div class="flex items-start"  v-if="detail">
            <BasicDescriptions  :data="detail"  :columns="goodColumns" />

            <ElTooltip content="重新选择" placement="top">
               <ElButton 
                  link 
                  type="info"
                  :icon="useRenderIcon('close-circle-line')" 
                  @click="handleChoose" 
                />
            </ElTooltip>
          </div>
        </ElFormItem>
      </ElCol>

      <ElCol :span="24">
        <ElFormItem label="盘点数量" prop="check_num">
          <NumberInput v-model="formData.check_num" placeholder="盘点数量" />
        </ElFormItem>
      </ElCol>

      <ElCol :span="24">
        <ElFormItem label="盈亏数量" prop="ykNum">
         {{ reComputedNumber.ykNum }}
        </ElFormItem>
      </ElCol>

      <ElCol :span="24">
        <ElFormItem label="盈亏金额" prop="ykPrice">
          <!-- =(账面数量-盘点数量) * 税前单价 -->
          {{ reComputedNumber.yKPrice }}
        </ElFormItem>
      </ElCol>

      <ElCol :span="24">
        <ElFormItem label="结果类型" prop="check_type">
          <ElSelect v-model="formData.check_type" placeholder="结果类型">
            <ElOption
              :disabled="reComputedNumber.yKPrice == 0"
              label="调整单" 
              value="2" 
            />

            <ElOption 
              label="前期数据导入" 
              value="1" 
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>

      <ElCol :span="24">
        <ElFormItem label="调整单入账月份" prop="fz_date">
          <ElDatePicker
            type="month"
            placeholder="入账月份" 
            v-model="formData.fz_date"
            :disabledDate="disabledDate"
            value-format="YYYY-MM"
          />
        </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" />
  </ElForm>
</template>
