<template>
  <el-dialog :visible="innerVisible" title="申请预付" width="380px" center :close-on-click-modal="false" @close="onClose">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-position="left" size="mini" label-width="80px">
      <el-form-item label="预付类型" prop="prepay_type">
        <el-select style="width:100%" placeholder="预付类型" v-model="ruleForm.prepay_type">
          <el-option v-for="prepay in prepaymentTypeOptions" :key="prepay.value" :label="prepay.label" :value="prepay.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="支付比例" prop="prepay_tax"> 
        <el-select style="width:100%" v-model="ruleForm.prepay_tax" placeholder="支付比例" :disabled="!ruleForm.prepay_type">
          <el-option 
            v-for="payRatio in payRatioOptions" 
            :key="payRatio.id" 
            :value="payRatio.id" 
            :label="payRatio.ratio" 
          />
        </el-select>
      </el-form-item>
    
      <el-form-item class="flex-end">
        <el-button type="primary" @click="onSubmit">保 存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import { prepaymentTypeOptions } from "../../columns"
import asyncRequest from "@/apis/service/customerService/demandOrder";

/**
 * @props
  prepay_type  //预付类型
  prepay_tax  //支付比例
*/
export default {
  props:['visible','sitem'],
  computed:{
    innerVisible:{
      get(){
        return this.visible
      },
      set(newVal){
        this.$emit('update:visible',newVal)
      }
    }
  },
  data(){
    return {
      prepaymentTypeOptions,
      payRatioOptions:[],
      ruleForm: { prepay_type:"",  /* 预付类型**/ prepay_tax:"" /* 支付比例 **/ },
      rules:{
        prepay_type:[{
          required:true,
          trigger:'change',
          message:'请选择预付类型'
        }],
        prepay_tax:[{
          required:true,
          trigger:'change',
          message:'请选择支付比例'
        }],
      }
    }
  },
  watch:{
    'ruleForm.prepay_type':{
      handler(){
        this.prepay_tax = ""
        this.fetchPrepayRatioOptions()
      }
    }
  },
  methods:{
    onClose(){
      this.ruleForm = { 
        prepay_type:"",  //预付类型
        prepay_tax:"" //支付比例
      }
      this.innerVisible = false
    },
    async fetchPrepayRatioOptions(){
      const { code, data } = await asyncRequest.prepayRatio({ name: this.ruleForm.prepay_type, status: 1 })
      if(code !== 1) return
      this.payRatioOptions = data.list
    },
    async onSubmit(){
      try {
        await this.$refs.ruleForm.validate()
        const { code } = await asyncRequest.prepayApply({
          id:this.sitem.id,
          ...this.ruleForm
        })
        if(code !== 1) return
        this.innerVisible = false
        this.$emit("refresh")
      }catch(err){
        console.log(err)
      }
    }
  }
}
</script>
