<script lang="ts" setup>
/**
 * @Name: SkuBuilder.vue
 * @Description: 产品属性-行编辑
 * @Author: Cheney
 */

import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { Close, Finished } from '@element-plus/icons-vue';
import { useResponse } from '/@/utils/useResponse';
import * as api from '../api';


const btnLoading = ref(false);

const editOpen = defineModel({ default: false });

const editDrawer = <Ref>useTemplateRef('editDrawer');

const props = defineProps({
  rowData: Object
});
const { rowData } = props;
const emit = defineEmits([ 'refresh' ]);

interface RuleForm {
  name: any,
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  name: rowData?.name
});

const rules = reactive<FormRules<RuleForm>>({
  // shop_name: [ { required: true, message: '请输入店铺', trigger: 'blur' } ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const res = await useResponse(api.updateRow, { id: rowData?.id, ...ruleForm }, btnLoading);
        if (res && res.code == 2000) {
          editOpen.value = false;
          ElMessage.success({ message: '编辑成功', plain: true, icon: 'Operation' });
          emit('refresh');
        }
      } catch (error) {
        console.error('Error==>', error);
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

function closeDrawer() {
  editDrawer.value.handleClose();
}

</script>

<template>
  <div class="drawer-container">
    <el-drawer ref="editDrawer"
               v-model="editOpen"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="`产品种类 - 编辑 `"
               size="25%">
      <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          class="mx-2.5 mt-7"
          label-position="top"
          label-width="auto"
          status-icon>
        <el-form-item class="font-medium" label="种类名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item>
          <el-divider />
          <div class="flex flex-1 justify-end">
            <el-button :icon="Close" @click="closeDrawer">取 消</el-button>
            <el-button :icon="Finished" :loading="btnLoading" type="primary" @click="submitForm(ruleFormRef)">
              确 定
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<style scoped>
.drawer-container :deep(.el-drawer__header) {
  border-bottom: none;
  font-weight: 500;
}

.drawer-container :deep(.el-drawer__title) {
  font-size: 18px;
}
</style>
