<!-- 商品发布 - 基础设置 -->
<template>
  <ContentWrap v-loading="formLoading">
    <el-form
      ref="formRef"
      :disabled="isDetail"
      :model="formData"
      :rules="rules"
      label-width="120px"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="客商性质" prop="customerNature">
            <el-select v-model="formData.customerNature" placeholder="请选择客商性质" class="w-80!">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PMS_SUPPLIER_NATURE)"
                :key="dict.id"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商名称" prop="name">
<!--            <el-input v-model="formData.name" placeholder="请输入供应商名称" class="w-80!" />-->
            <lang-input v-model="formData.name" placeholder="请输入供应商名称" class="w-80!"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商分类" prop="classification">
            <el-select v-model="formData.classification" placeholder="请选择分类" class="w-80!">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SUPPLIER_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="公司类型" prop="type">
            <el-select v-model="formData.type" placeholder="请选择公司类型" class="w-80!">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SUPPLIER_COMPANY_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
<!--        <el-col :span="8">-->
<!--          <el-form-item label="供应商性质" prop="nature">-->
<!--            <el-select v-model="formData.nature" placeholder="请选择供应商性质" class="w-80!">-->
<!--              <el-option-->
<!--                v-for="dict in getStrDictOptions(DICT_TYPE.SUPPLIER_NATURE)"-->
<!--                :key="dict.id"-->
<!--                :label="dict.label"-->
<!--                :value="dict.value"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="8">-->
<!--          <el-form-item label="状态" prop="status">-->
<!--            <el-select v-model="formData.status" placeholder="请选择状态" class="w-80!">-->
<!--              <el-option-->
<!--                v-for="dict in getIntDictOptions(DICT_TYPE.SUPPLIER_STATUS)"-->
<!--                :key="dict.value"-->
<!--                :label="dict.label"-->
<!--                :value="dict.value"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="8">
          <el-form-item label="社会信用代码" prop="creditCode">
            <el-input
              v-model="formData.creditCode"
              class="w-80!"
              placeholder="请输入社会信用代码"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="公司规模" prop="size">
            <el-select v-model="formData.size" placeholder="请选择公司规模" class="w-80!">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SUPPLIER_SIZE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="纳税人识别号" prop="tin">
            <el-input v-model="formData.tin" class="w-80!" placeholder="请输入纳税人识别号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="法人" prop="corporation">
            <el-input v-model="formData.corporation" class="w-80!" placeholder="请输入法人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="成立日期" prop="incorporationDate">
            <el-date-picker
              class="w-80!"
              v-model="formData.incorporationDate"
              type="date"
              value-format="x"
              placeholder="选择成立日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="公司地址" prop="address">
            <el-input v-model="formData.address" class="w-80!" placeholder="请输入公司地址" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="注册资金(万元)" prop="registeredCapital">
            <el-input
              type="number"
              v-model="formData.registeredCapital"
              class="w-80!"
              placeholder="请输入注册资金"
            />
          </el-form-item>
        </el-col>
      <el-col :span="8">
        <el-form-item label="年营业额(万元)" prop="annualTurnove">
          <el-input
            v-model="formData.annualTurnove"
            type="number"
            class="w-80!"
            placeholder="请输入年营业额"
          />
        </el-form-item>
      </el-col>
        <el-col :span="8">
      <el-form-item label="经营范围" prop="bizScope">
        <el-input type="textarea" v-model="formData.bizScope" placeholder="请输入经营范围" />
      </el-form-item>
          </el-col>
        <el-col :span="8">
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
          </el-col>
      </el-row>
      <!--    <el-form-item label="商品简介" prop="introduction">-->
      <!--      <el-input-->
      <!--        v-model="formData.introduction"-->
      <!--        :autosize="{ minRows: 2, maxRows: 2 }"-->
      <!--        :clearable="true"-->
      <!--        :show-word-limit="true"-->
      <!--        class="w-80!"-->
      <!--        maxlength="128"-->
      <!--        placeholder="请输入商品简介"-->
      <!--        type="textarea"-->
      <!--      />-->
      <!--    </el-form-item>-->
      <!--    <el-form-item label="商品封面图" prop="picUrl">-->
      <!--      <UploadImg v-model="formData.picUrl" :disabled="isDetail" height="80px" />-->
      <!--    </el-form-item>-->
      <!--    <el-form-item label="商品轮播图" prop="sliderPicUrls">-->
      <!--      <UploadImgs v-model="formData.sliderPicUrls" :disabled="isDetail" />-->
      <!--    </el-form-item>-->
    </el-form>
    <el-form>
      <el-form-item style="float: right">
        <el-button v-if="!isDetail" :loading="formLoading" type="warning"  @click="submitForm">
          保存
        </el-button>
        <el-button @click="close" type="primary">返回</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import {DICT_TYPE, getIntDictOptions, getStrDictOptions} from '@/utils/dict'
import { Api, SupplierVO } from '@/api/supplier/base'
import {useTagsViewStore} from "@/store/modules/tagsView";
import type { Supplier } from '@/api/supplier/base/index'
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const { t } = useI18n() // 国际化
defineOptions({ name: 'SupplierBaseInfo' })
const props = defineProps({
  propFormData: {
    type: Object as PropType<Supplier>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false), // 是否作为详情组件
  supplierId: {type:String,required:true}
})
const supplierid = props.supplierId;
const message = useMessage() // 消息弹窗
const formRef = ref() // 表单 Ref
const formData = reactive<Supplier>({
  id: '',
  customerNature: undefined,
  code: undefined,
  name: undefined,
  classification: undefined,
  type: undefined,
  nature: undefined,
  creditCode: undefined,
  tin: undefined,
  corporation: undefined,
  incorporationDate: undefined,
  address: undefined,
  bizScope: undefined,
  registeredCapital: undefined,
  annualTurnove: undefined,
  size: undefined,
  status: undefined,
  remark: undefined
})
// const rules = reactive({
//   name: [required],
//   categoryId: [required],
//   keyword: [required],
//   introduction: [required],
//   picUrl: [required],
//   sliderPicUrls: [required],
//   brandId: [required]
// })

/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData, data)
  },
  {
    immediate: true
  }
)

const rules = reactive({
  customerNature: [{ required: true, message: '客商性质不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  classification: [{ required: true, message: '供应商分类不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '公司类型不能为空', trigger: 'blur' }],
  nature: [{ required: true, message: '供应商性质不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})

/** 表单校验 */
const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef)?.validate()
    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    message.error('【基础设置】不完善，请填写相关信息')
    emit('update:activeName', 'info')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })
const emit = defineEmits(['success','update:activeName','sendParam']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData as unknown as SupplierVO
    if (!supplierid.id){
      await Api.create(data).then(res => {
        if (res.code ===0) {
          const param = {id: res.data}
          emit('sendParam', param);
          message.success(t('common.createSuccess'))
        } else {
          message.error(res.msg)
        }
      })
    } else {
      await Api.update(data)
      message.success(t('common.updateSuccess'))
    }
    // 发送操作成功的事件
    emit('success')
    close()
  } finally {
    formLoading.value = false
  }
  //try {
  // 校验各表单
  // await unref(infoRef)?.validate()
  // await unref(skuRef)?.validate()
  // await unref(deliveryRef)?.validate()
  // await unref(descriptionRef)?.validate()
  // await unref(otherRef)?.validate()
  // // 深拷贝一份, 这样最终 server 端不满足，不需要影响原始数据
  // const deepCopyFormData = cloneDeep(unref(formData.value)) as ProductSpuApi.Spu
  // deepCopyFormData.skus!.forEach((item) => {
  //   // 给sku name赋值
  //   item.name = deepCopyFormData.name
  //   // sku相关价格元转分
  //   item.price = convertToInteger(item.price)
  //   item.marketPrice = convertToInteger(item.marketPrice)
  //   item.costPrice = convertToInteger(item.costPrice)
  //   item.firstBrokeragePrice = convertToInteger(item.firstBrokeragePrice)
  //   item.secondBrokeragePrice = convertToInteger(item.secondBrokeragePrice)
  // })
  // // 处理轮播图列表
  // const newSliderPicUrls: any[] = []
  // deepCopyFormData.sliderPicUrls!.forEach((item: any) => {
  //   // 如果是前端选的图
  //   typeof item === 'object' ? newSliderPicUrls.push(item.url) : newSliderPicUrls.push(item)
  // })
  // deepCopyFormData.sliderPicUrls = newSliderPicUrls
  // 校验都通过后提交表单
  // const data = deepCopyFormData as ProductSpuApi.Spu
  // const id = params.id as unknown as number
  // if (!id) {
  //   await ProductSpuApi.createSpu(data)
  //   message.success(t('common.createSuccess'))
  // } else {
  //   await ProductSpuApi.updateSpu(data)
  //   message.success(t('common.updateSuccess'))
  // }
  // close()
  //} finally {
  //  formLoading.value = false
  //}
}
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'Suppliers',query: {
      date: new Date().getTime(),
    } })
}
/** 初始化 */
onMounted(async () => {
  // 获得分类树
  // const data = await ProductCategoryApi.getCategoryList({})
  // categoryList.value = handleTree(data, 'id')
  // 获取商品品牌列表
  // brandList.value = await ProductBrandApi.getSimpleBrandList()
  console.log(JSON.stringify(formData.value))
})
</script>

<style lang="scss" scoped>
.el-input__inner {
  color: #0a0505;
}
</style>
