<template>
  <a-modal v-model:open="open" title="添加商品" @ok="handleOk" centered @cancel="onCancel" :maskClosable="false" :keyboard="false" :confirmLoading="confirmLoading">
    <a-form
        :model="data"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        ref="refForm"
    >
      <a-form-item
          label="供应商"
          name="providerId"
          :rules="[{ required: true, message: '请选择供应商' }]"
      >
        <a-select v-model:value="data.providerId">
          <a-select-option v-for="provider in providers" :value="provider.providerId">{{provider.name}}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
          label="产品id"
          name="pid"
          :rules="[{ required: true, message: '请输入产品id' }]"
      >
        <a-input v-model:value="data.pid" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>

import {computed, onMounted, reactive, ref} from "vue";
import {FetchProviderArticleDetail, FindProviders} from "@/api/provider.js";
import {message} from "ant-design-vue";

onMounted(()=>{
  loadProviders()
})

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:visible', 'reload'])

const open = computed({
  get(){
    return props.visible
  },
  set(value){
    emits('update:visible', value)
  }
})

const handleOk = ()=>{
  if(refForm.value){
    refForm.value.validate().then(values=>{
      confirmLoading.value = true
      FetchProviderArticleDetail(data.providerId, data.pid).then(res=>{
        if(res.code === 200){
          message.success("添加成功")
        }else{
          message.error(res.msg)
        }
      }).catch(err => {
        message.error("添加失败")
        console.log(err)
      }).finally(()=>{
        confirmLoading.value = false
        emits('update:visible', false)
      })
    })
  }else{
    message.error('refForm未获取')
  }
}

const data = reactive({
  pid: '',
  providerId: '',
})

const providers = ref([])


const loadProviders = ()=>{
  FindProviders({}).then(res=>{
    if(res.code !== 200) {
      message.error('获取供应商列表失败')
      console.log(res)
    }else{
      providers.value = res.data
    }
  }).catch(err=>{
    message.error('获取供应商列表失败')
    console.log(err)
  })
}

const refForm = ref(null)

const onCancel=()=>{
  if (refForm.value){
    refForm.value.resetFields()
  }
}

const confirmLoading = ref(false)
</script>

<style scoped>

</style>