<template>
  <el-dialog :model-value="visible" :width="width" title="售后信息登记" @close="close()">
    <div class="overflow-hidden p-15px">
      <el-form label-width="100px" label-position="top">
        <el-form-item label="跟进备注">
          <el-input :model-value="form.notes" type="textarea" placeholder="请输入售后跟进备注内容" resize="none"
            :autosize="{ minRows: 5, maxRows: 8 }" :maxlength="300" show-word-limit
            @update:model-value="change($event, 'notes')" />
        </el-form-item>
        <el-form-item label="退回运单号">
          <el-input :model-value="form.waybillNo" placeholder="请输入患者退药的运单号" maxlength="100"
            @update:model-value="change($event, 'waybillNo')" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div text-center>
        <el-button plain class="w-100px" type="primary" @click="close()">取消</el-button>
        <el-button class="w-100px" :loading="loading" type="primary" @click="confirm()">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { computed, ref, watch } from "vue";
import { storeToRefs } from 'pinia';
import { ElMessage, ElMessageBox } from "element-plus";
import { memberStore } from "@/store/member";
import { updateAfterSaleInfo } from "@/api/hlw";

const emits = defineEmits(["close", "change"]);
const props = defineProps({
  order: { type: Object, default: () => ({}) },
  visible: { type: Boolean, default: false },
  width: { type: [String, Number], default: "500px" },
});

const { memberInfo } = storeToRefs(memberStore());
const loading = ref(false);
const editForm = ref({});
const originForm = ref({});
const form = computed(() => ({ ...originForm.value, ...editForm.value }));

function change(value, field) {
  editForm.value[field] = value;
}

function close() {
  emits("close");
}

async function confirm() {
  if (loading.value) return;
  if(Object.keys(editForm.value).length === 0) {
    return close();
  }
  loading.value = true;
  const res = await updateAfterSaleInfo({ ...editForm.value, id: props.order._id });
  loading.value = false;
  if (res.success) {
    ElMessage.success('保存成功');
    emits("change", { afterSale: { ...form.value }, id: props.order._id });
    close();
  } else {
    ElMessage.error(res.message);
  }
}

watch(() => props.visible, (n) => {
  if (n) {
    const afterSale = props.order && props.order.afterSale ? props.order.afterSale : {};
    editForm.value = {};
    originForm.value.notes = typeof afterSale.notes === 'string' ? afterSale.notes.trim() : '';
    originForm.value.waybillNo = typeof afterSale.waybillNo === 'string' ? afterSale.waybillNo.trim() : '';
  }

});
</script>