<template>
  <el-card class="hl-card" style="position: relative">
    <template #header>
      <span>新增页</span>
    </template>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="180px" v-loading="formLoading">
      <el-card class="hl-card-info">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">基础信息</span>
        </template>

        <el-row>
          <el-col :span="24">
            <el-row>
              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label=" 采购单号" prop="purchaseNo">
                      <el-input class="!w-265px" placeholder="系统自动生成" v-model="formData.purchaseNo" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="采购单类型" prop="purchaseType" :rules="formRules.purchaseType">
                      <el-select
v-model="formData.purchaseType" clearable class="!w-240px"
                        @change="handlePurchaseType">
                        <el-option
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PROJECT_PURCHASE_ORDER_TYPE)"
                          :key="dict.value" :label="dict.label" :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="结算币种" prop="currencyType">
                      <el-select v-model="formData.currencyType" clearable class="!w-240px">
                        <el-option
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_CURRENCY)" :key="dict.value"
                          :label="dict.label" :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="80">
                    <el-form-item label="备注" prop="description">
                      <el-input
class="!w-713px" type="textarea" v-model="formData.description" show-word-limit
                        maxlength="200" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="单据日期" prop="createTime">
                      <el-date-picker
class="!w-265px" v-model="formData.createTime" value-format="x" placeholder="单据日期"
                        disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item
label="物料需求计划编号"  prop="projectMaterialPlanNo"
                      :rules="formRules.projectMaterialPlanNo">
                      <div class="!w-265px">
                        <el-input
v-model="formData.projectMaterialPlanNo" @click.prevent="handleClick"
                          :readonly="!isEditing">
                          <template #append><el-button
:icon="Search"
                              @click="openProjectMaterialPlanDialog" /></template>
                        </el-input>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="税率(%)" prop="taxRatio">
                      <el-input class="!w-265px" v-model="formData.taxRatio" placeholder="税率" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="供应商" prop="supplierId" :rules="formRules.supplierId">
                      <SupplierSelect v-model="formData.supplierId" @update:new-value="handleSelectedSupplier" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="采购物料类型" prop="goodsType" :rules="formRules.goodsType">
                      <!-- {{ formData.purchaseType}}
                      {{formData.goodsType}} -->
                      <el-select
v-if="formData.purchaseType == 2 || formData.purchaseType == 3" disabled v-model="formData.goodsType"
                        placeholder="下拉选择2" clearable class="!w-240px">
                        <el-option
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PROJECT_PURCHASE_GOODS_TYPE)"
                          :key="dict.value" :label="dict.label" :value="dict.value" />
                      </el-select>
                      <el-select v-else  v-model="formData.goodsType" placeholder="下拉选择" clearable class="!w-240px">
                        <el-option
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PROJECT_PURCHASE_GOODS_TYPE)"
                          :key="dict.value" :label="dict.label" :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="采购合同号" prop="contractNo">
                      <el-input class="!w-265px" v-model="formData.contractNo" placeholder="采购合同号" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

            </el-row>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <div class="hl-footer text-center">
      <el-button @click="() => router.back()" size="large">取 消</el-button>
      <el-button @click="submitForm" type="success" size="large">保 存</el-button>
    </div>
  </el-card>
  <materialPlanDialog ref="projectMaterialPlanDialog" @success="handleSelectedProjectMaterialPlan" />
  <supplierDialog ref="projectSupplierDialog" @success="handleProjectSupplier" />
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import * as SupplierApi from '@/api/heli/supplier'
import * as PurchaseOrderNoApi from '@/api/heli/purchaseorderNo'
import { Search, Plus } from '@element-plus/icons-vue'
import materialPlanDialog from '@/views/heli/purchaseorder/materialPlanDialog.vue'
import { useTagsViewStore } from '@/store/modules/tagsView'
import supplierDialog from '@/views/heli/purchaseorder/supplierDialog.vue'
import SupplierSelect from '@/views/heli/hlvuestyle/supplierSelect.vue'
import * as materialPlanApi from "@/api/heli/materialplan";

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const router = useRouter()
const tagsViewStore = useTagsViewStore()

const currentTag = router.currentRoute.value
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  purchaseNo: undefined,
  supplierId: undefined,
  supplierName: undefined,
  contractNo: undefined,
  purchaseType: undefined,
  isPlan: true,
  projectMaterialPlanNo: '',
  projectMaterialPlanId: undefined,
  goodsType: undefined,
  currencyType: 1,
  taxRatio: 13,
  status: 1,
  createTime: new Date(),
  description: undefined
})
const formRules = reactive({
  supplierId: [{ required: true, message: '供应商不能为空', trigger: 'blur' }],
  purchaseType: [{ required: true, message: '采购单类型不能为空', trigger: 'blur' }],
  projectMaterialPlanNo: [{ required: true, message: '物料需求计划编号不能为空', trigger: 'blur' }],
  goodsType: [{ required: true, message: '采购物料不能为空', trigger: 'blur' }],
  currencyType: [{ required: true, message: '结算币种不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const handlePurchaseType = (val) => {
  if (val == 1) {
    formData.value.isPlan = false
  } else {
    formData.value.goodsType = 1
    formData.value.isPlan = true
    formData.value.projectMaterialPlanNo = ''
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const projectMaterialPlanDialog = ref()
const openProjectMaterialPlanDialog = () => {
  projectMaterialPlanDialog.value?.open()
}
const projectSupplierDialog = ref()
const openProjectSupplierDialog = () => {
  projectSupplierDialog.value?.open()
}
const isEditing = ref(false)
const handleClick = (event) => {
  openProjectMaterialPlanDialog()
}
const handleClickSupplier = (event) => {
  openProjectSupplierDialog()
}

const handleSelectedProjectMaterialPlan = (arr) => {
  if (arr) {
    formData.value.projectMaterialPlanNo = arr.projectMaterialPlanNo
    formData.value.projectMaterialPlanId = arr.id
    // formData.value.projectCode = arr.projectCode
    // formData.value.projectName = arr.projectName
    // formData.value.planNo = arr.planNo
  }
}

const handleProjectSupplier = (arr) => {
  if (arr) {
    console.log("arr==", arr);
    formData.value.supplierId = arr.id
    formData.value.supplierName = arr.name
  }
}

const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  if (
    formData.value.purchaseType == 1 &&
    (formData.value.projectMaterialPlanId == undefined ||
      formData.value.projectMaterialPlanNo == '')
  ) {
    message.alert('物料需求计划编号不能为空')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    // const data = formData.value as unknown as PurchaseOrderApi.PurchaseOrderVO
    const data = formData.value as unknown as PurchaseOrderNoApi.PurchaseOrderNoVO
    var plan = await materialPlanApi.getProjectMaterialPlanNo(data.projectMaterialPlanNo);
    console.log(plan)
    if (!plan){
      message.alert('该单号'+data.projectMaterialPlanNo+'不存在,请确认')
      return
    }
    var purchaseOrderId = await PurchaseOrderNoApi.createPurchaseOrderNo(data)
    router.push({ path: '/purchase/purchaseorderedit', query: { id: purchaseOrderId } })

    //this.$tab.closeOpenPage({path:"/purchase/add"});
    tagsViewStore.delVisitedView(currentTag)
    dialogVisible.value = false
  } finally {
    formLoading.value = false
    // router.push({ path: '/purchase/purchaseorderedit', query: { id: purchaseOrderId } })
    // tagsViewStore.delVisitedView(currentTag)
    //this.$tab.closePage();
  }
}

const supplierInit = ref()
onMounted(async () => {
  supplierInit.value = await SupplierApi.getSimpList()
})

//接收供应商传递的数据
const handleSelectedSupplier = (newValue: any) => {
  formData.value.supplierId = newValue?.id
}
</script>
