<template>
  <el-dialog
    :title="purchaseTitle"
    append-to-body
    :visible.sync="openShow"
    width="30%"
    @close="closeDialog"
  >
    <avue-form ref="form" :option="option" v-model="formData"></avue-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
import {returnMaterial} from '@/api/materials/expend'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
    durableFormId: {
      type:  Number,
      default: 0,
    }
  },
  data() {
    const today = new Date();
    const defaultDate = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`;
    return {
      formData: {
        returnReason: '',
        returnTime: defaultDate, 
      },
      purchaseTitle:'报废',
      openShow: false,
      option: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "报废数量",
            prop: "num",
            span: 24,
            value: 1,
            disabled: true,
          },
          {
            label: "报废理由",
            prop: "returnReason",
            span: 24,
            type:'textarea',
            rows:5,
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
          },
          {
            label: "报废时间",
            prop: "returnTime",
            span: 24,
            type:'date',
            rows:5,
            rules: [
              {
                required: true,
                message: "请选择",
                trigger: "blur",
              },
            ],
          },
        ],
      },
    };
  },
  mounted() {
    this.openShow = this.showDialog;
  },
  methods: {
    closeDialog() {
      this.openShow = false;
      this.$emit("closeDialog");
    },
    async submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const params = {
              durableFormId: this.durableFormId, 
              num: 1,
              returnTime: this.formData.returnTime, 
              returnReason: this.formData.returnReason, 
              type: 2
            }
            await returnMaterial(params)
            this.$message.success('报废成功')
            this.closeDialog()
            this.$emit('submitSuccess')
            this.$refs.form.resetFields()
          } catch (error) {
            this.$message.error(error.message || '报废失败，请重试')
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped></style>
