<script setup>
import {apiProductsConfig} from '@/api/products'
const show = defineModel('show', { type: Boolean, default: false })
const props = defineProps({
  productInfo:{
    type:Object,
    default:{}
  },
  isAdd:{
    type:Boolean,
    default:false
  },
  labelOptions:{
    type:Array,
    default:[]
  },
})
const rules = {
  SourceId:[{required:true,message:'请选择品种'}],
  Price:[{required:true,message:'请输入价格'}],
  ProductName:[{required:true,message:'请输入套餐名称'}],
  ValidDays:[{required:true,message:'请输入有效时长'}],
}
const emits = defineEmits(["close"])
const formRef = ref(null)
const packageData = reactive({
    SourceId:null,
    Type:'',
    ProductName:'',
    CoverSrc:'',
    ValidDays:null,
    Price:'',
    Description:'',
    RiskLevel:'',
    Id:null
})
watch(show,(newval)=>{
  if(newval){
    if (!props.isAdd) {
      formRef.value?.clearValidate()
      packageData.SourceId = [packageData.SourceId] || []
      Object.assign(packageData,props.productInfo)
    }
  }else{
    Object.assign(packageData,{
      SourceId:null,
      Type:'',
      ProductName:'',
      CoverSrc:'',
      ValidDays:null,
      Price:'',
      Description:'',
      RiskLevel:'',
      Id:null
    })
    formRef.value?.resetFields()
    console.log(packageData);
  }
})

function getRiskLevel() {
  apiProductsConfig.getRiskLevel({
    SourceId:packageData.SourceId[packageData.SourceId.length-1],
    ProductType:'package'
  }).then(res=>{
    if(res.Ret!==200) return
    console.log(res.Data);
    packageData.RiskLevel = res.Data?.RiskLevel||''
  })
}




async function handleSubmitForm() {
  try{
  await formRef.value?.validate()
  }catch(e){ return }
  const packageParams = {
    SourceId:Array.isArray(packageData.SourceId) ? packageData.SourceId[packageData.SourceId.length-1] : packageData.SourceId,
    Type: 'package',
    ProductName:packageData.ProductName,
    CoverSrc:packageData.CoverSrc,
    ValidDays:parseInt(packageData.ValidDays),
    Price:packageData.Price,
    Description:packageData.Description,
    RiskLevel:packageData.RiskLevel || '',
    ProductId:packageData.Id || null
  }
  const res = props.isAdd ? await apiProductsConfig.postAddProduct(packageParams) : await apiProductsConfig.postEditProduct(packageParams)
  if(res.Ret!==200) return
  ElMessage.success(res.Msg)
  handleClose()
}
function handleClose() {
  emits("close")
}


function handleUploadImg(file){
    //图片大小和格式限制
    const {size,type} = file.file
    const sizeLimit = 5*1024*1024
    if(!['image/png','image/jpeg'].includes(type)){
        ElMessage.warning('仅支持png、jpg格式的图片')
        return
    }
    if(size>sizeLimit){
        ElMessage.warning('套餐封面不能超过5M')
        return
    }
    let form = new FormData();
    form.append('File',file.file);
    apiProductsConfig.postUploadFile(form).then(res=>{
        if(res.Ret!==200) return 
        packageData.CoverSrc = res.Data?.Url||''
    })
}
function handleValidValidDays() {
  packageData.ValidDays=packageData.ValidDays.replace(/[^\.\d]/g,'').replace('.','').replace(/^0/,'');
}
function handleValidPrice() {
  packageData.Price=packageData.Price.replace(/[^\.\d]/g,'').replace(/^00/,'');
}
</script>

<template>
  <el-dialog
    v-model="show"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    width="50%"
    :title="isAdd?'添加套餐':'编辑'"
  >
    <div class="dialog-content">
      <el-form label-width="100px" ref="formRef" :model="packageData" class="form" :rules="rules">
        <div class="left">
          <el-form-item label="品种" prop="SourceId" :label-width="150">
            <!-- <el-input v-model="packageData.Price" placeholder="请选择品种" /> -->
            <el-cascader
              filterable
              :options="props.labelOptions"
              collapse-tags
              v-model="packageData.SourceId" 
              @change="getRiskLevel"
              :props="{
                value:'id',
                label:'name',
              }"
              style="width: 100%;"
              placeholder="请选择品种"
              :disabled="!isAdd"
              clearable>
            </el-cascader>
          </el-form-item>
          <el-form-item label="套餐名称" prop="ProductName" :label-width="150">
            <el-input v-model="packageData.ProductName" placeholder="请输入套餐名称"/>
          </el-form-item>
          <el-form-item label="商品价格(元)" prop="Price" :label-width="150">
            <el-input v-model="packageData.Price" placeholder="请输入价格" @keyup="handleValidPrice()"/>
          </el-form-item>
          <el-form-item label="有效时长(天)" prop="ValidDays" :label-width="150">
            <el-input v-model="packageData.ValidDays" min="0" class="no-spinner" placeholder="请输入有效时长" @keyup="handleValidValidDays()" />
          </el-form-item>
          <div class="tips" v-if="!isAdd">
            提示：修改价格和有效时长不影响历史已支付订单，仅对未来订单生效！
          </div>
        </div>
        <div class="left">
          <el-form-item label="风险等级" v-if="packageData.RiskLevel">
            <span>{{ packageData.RiskLevel }}</span>
          </el-form-item>
          <el-form-item label="套餐简介">
            <el-input
              v-model="packageData.Description"
              style="width: 240px"
              :rows="4"
              type="textarea"
              placeholder="请输入套餐简介"
            />
          </el-form-item>
          <el-form-item label="套餐封面">
            <ImageUpload
              :imgUrl="packageData.CoverSrc"
              uploadHint="支持jpg、jpeg、png等格式，建议上传宽高比例为3:4的图片"
              width="120px"
              height="148px"
              @upload="handleUploadImg"
              @remove="packageData.CoverSrc=''"
          ></ImageUpload>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <template #footer>
      <div class="btn-content">
        <el-button style="width: 80px" @click="handleClose()">取消</el-button>
        <el-button
          type="primary"
          style="width: 80px; margin-right: 24px"
          @click="handleSubmitForm"
          >保存</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.dialog-content {
  width: 100%;
  .form {
    height: 350px;
    display: flex;
    align-items: center;
    .left {
      width: 50%;
      height: 100%;
      display: inline-block;
    }
  }
  .tips {
    margin-top: 50px;
    line-height: 22px;
    padding-left: 50px;
    color: #909399;
  }
}
.btn-content {
  text-align: center;
  padding-bottom: 20px;
}
</style>
