<template>
  <el-drawer :title="dialog.title" v-model="dialog.visible" @close="cancel">
    <el-form ref="drawerRef" :model="formData" :rules="rules" label-position="top">
      <el-form-item label="批次管理" prop="isBatch">
        <el-select filterable v-model="formData.isBatch" size="small">
          <el-option
            v-for="item in isBatch"
            :key="item.key"
            :label="item.label"
            :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="有效期计算规则" prop="expirationRules">
        <el-select filterable v-model="formData.expirationRules" size="small">
          <el-option
            v-for="item in expirationRules"
            :key="item.key"
            :label="item.label"
            :value="item.value"/>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { getCurrentInstance, reactive, ref, toRefs } from 'vue'
import { ElForm } from 'element-plus'
import { editWareHouse } from '@/api/materialSpec'
const { proxy }: any = getCurrentInstance()
const emits = defineEmits(['refresh'])
// 公共数据
const drawerRef = ref(ElForm);
const state = reactive({
  dialog: {
    title: "编辑物料",
    type: 'edit',
    visible: false,
  },
  isBatch: [
    { key: 'y', label: '启用', value: 'Y' },
    { key: 'n', label: '不启用', value: 'N' }
  ],
  expirationRules: [
    { key: '0', label: '到货时间', value: '0' },
    { key: '1', label: '创建时间', value: '1' }
  ],
  formData: {
    // 工厂名
    siteName: '',
    // 物料号
    materialSpecName: '',
    // 启用批次管理（Y：启用，N：不启用）
    isBatch: '',
    // 有效期计算规则(0：到货时间，1：创建时间)
    expirationRules: ''
  },
  rules: {
    isBatch: [{ required: true, message: "是否启用批次管理", trigger: "blur" }],
    expirationRules: [{ required: true, message: "有效期计算规则", trigger: "blur" }],
  }
})
const { dialog, formData, rules, isBatch, expirationRules } = toRefs(state)

// 取消
function cancel() {
  state.dialog.visible = false;
}

// 提交
function submitForm() {
  drawerRef.value.validate((isValid: boolean) => {
    if (isValid) {
      // 编辑
      editWareHouse(state.formData).then((res: any) => {
        console.log(res)
        if (res.errorCode === 200) {
          proxy.$ElMessage.success(res.message)
          cancel()
          emits('refresh')
        } else {
          proxy.$ElMessage.error(res.message)
        }
      })
    }
  });
}

// 展示
const showModal = (row: any) => {
  state.dialog.visible = true
  // 数据
  state.formData.siteName = row.SITENAME
  state.formData.materialSpecName = row.MATERIALSPECNAME
  state.formData.isBatch = row.EDIT_IS_BATCH
  state.formData.expirationRules = row.EDIT_EXPIRATION_RULES
}
defineExpose({ showModal })
</script>
