<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import type { FormInst, FormRules } from 'naive-ui';
import { NForm, NInput, NSwitch, useMessage } from 'naive-ui';
import E from 'wangeditor';
import { router } from '@/router';
import { fetchAddGoods, fetchEditGoods, fetchGoodsDetail } from '@/service/api/goods-center/health-goods';
import ZUpload from '../../../components/zt/upload/z-upload.vue';
const editor = ref();

const route = useRoute();
const formRef = ref<FormInst | null>(null);
const message = useMessage();
const disabled = ref(false);
const useTime = ref<[string, string]>(['2026-01-06 00:00:00', '2026-01-06 23:59:59']);
const loading = ref(false);
const model = ref({
  createTime: '',
  updateTime: '',
  shopId: 0,
  goodsName: '',
  goodsImg: '',
  goodsCode: '',
  price: 0,
  shelfStatus: 0,
  effectiveTime: 0,
  advanceBookingTime: 0,
  useStartTime: '00:00:00',
  useEndTime: '00:00:00',
  usageProcess: '',
  buyNotice: '',
  content: '',
  shopName: '',
  tel: '',
  sales: 0
});

const rules: FormRules = {
  shopName: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入'
  },
  goodsName: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入'
  },
  goodsImg: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请输入'
  },

  price: {
    type: 'number',
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入'
  },
  effectiveTime: {
    type: 'number',
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入'
  },
  advanceBookingTime: {
    type: 'number',
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入'
  },

  usageProcess: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入'
  },
  buyNotice: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入'
  },
  content: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入'
  },
  useStartTime: {
    type: 'string',
    required: true,
    trigger: ['blur', 'change'],
    message: '请输入'
  }
};

function handleValidateButtonClick(e: MouseEvent) {
  e.preventDefault();
  formRef.value?.validate(async errors => {
    if (!errors) {
      loading.value = true;
      model.value.content = editor.value.txt.html();
      model.value.useStartTime = useTime.value[0];
      model.value.useEndTime = useTime.value[1];
      let res;
      if (route.query.mode == 'edit') {
        res = await fetchEditGoods(model.value);
      } else {
        res = await fetchAddGoods(model.value);
      }
      loading.value = false;
      console.log(res);

      if (res.data === null) {
        router.push({
          path: '/goods-center/health-goods'
        });
      }
    } else {
      console.log(errors);
      message.error('验证失败');
    }
  });
}

async function getDetail() {
  // 获取详情接口
  const res = await fetchGoodsDetail(route.query.id);
  if (res.data) {
    model.value = res.data;
    editor.value.txt.html(res.data.content); // 重新设置编辑器内容
    useTime.value = [res.data.useStartTime, res.data.useEndTime];
    console.log(useTime.value);
  }
}

onMounted(() => {
  editor.value = new E('#div1');
  editor.value.create();
  if (route.query.id) {
    if (route.query.mode === 'detail') {
      disabled.value = true;
      editor.value.disable();
    }
    getDetail();
  }
  console.log(route.query);
});
</script>

<template>
  <div class="edit-health-goods pl-20px pt-20px">
    <NForm
      ref="formRef"
      :model="model"
      :rules="rules"
      label-placement="left"
      label-width="auto"
      require-mark-placement="right-hanging"
      size="medium"
      class="max-w-640px"
      :disabled="disabled"
    >
      <NFormItem label="门店名称" path="shopName">
        <NInput v-model:value="model.shopName" placeholder="" />
      </NFormItem>
      <NFormItem label="商品名称" path="goodsName">
        <NInput v-model:value="model.goodsName" placeholder="" />
      </NFormItem>
      <NFormItem label="封面" path="goodsImg">
        <ZUpload :value="model.goodsImg" :max="1"></ZUpload>
      </NFormItem>
      <NFormItem label="商品价格" path="price">
        <NInputNumber v-model:value="model.price" />
      </NFormItem>
      <NFormItem label="有效期" path="effectiveTime">
        购买之日起
        <NInputNumber v-model:value="model.effectiveTime" />
        天有效
      </NFormItem>
      <NFormItem label="预约信息" path="advanceBookingTime">
        提前
        <NInputNumber v-model:value="model.advanceBookingTime" />
        天预订
      </NFormItem>
      <NFormItem label="可用时间">
        <NDatePicker
          v-model:formatted-value="useTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          clearable
        />
      </NFormItem>
      <NFormItem label="消费流程" path="usageProcess">
        <NInput v-model:value="model.usageProcess" :maxlength="150" show-count placeholder="" type="textarea" />
      </NFormItem>
      <NFormItem label="购买人群" path="buyNotice">
        <NInput v-model:value="model.buyNotice" :maxlength="150" show-count placeholder="" type="textarea" />
      </NFormItem>
      <NFormItem label="图文说明" path="content">
        <div id="div1"></div>
      </NFormItem>
      <NFormItem label="上架状态" path="shelfStatus">
        <NSwitch v-model:value="model.shelfStatus" :unchecked-value="0" :checked-value="1" />
      </NFormItem>

      <div class="flex justify-end">
        <NButton round type="primary" :loading="loading" @click="handleValidateButtonClick">保存</NButton>
      </div>
    </NForm>
  </div>
</template>

<style lang="scss" scoped>
::v-deep .n-form-item-blank {
  z-index: 6 !important;
}
.edit-health-goods {
  background: #fff;
}
</style>
