<script setup lang="ts">
import { FormRules, ElForm, ElMessage } from "element-plus";
import { reactive, ref } from "vue";
import { httpUpdate, httpDetail } from "/@/api/mobile/shopStock";
import { responseHandle } from "/@/utils/responseHandle";
import { useNav } from "/@/layout/hooks/useNav";
import { FLAG_OPTIONS } from "/@/config/status";
import { PageDetail } from "/@/components/PageDetail";
import goodDetailConfig from "../config/goodDetail.config";

enum FROM_TYPE {
  create = "create",
  edit = "edit",
  view = "view"
}
const { logout } = useNav();
const showModel = ref(false);
const TYPE = ref<FROM_TYPE>(FROM_TYPE.create);
const formRef = ref<InstanceType<typeof ElForm>>(null);
const PageDetailRef = ref<InstanceType<typeof PageDetail>>(null);
const loading = ref(false);
const titleType = ref("");
const inventory = ref(0);
const id = ref("");
const emit = defineEmits(["reload"]);
const initform = {
  id: "",
  number: 1,
  inventory: 0,
  flag: "1"
};
const ruleForm = ref({ ...initform });
const rules = reactive<FormRules>({
  number: [{ required: true, trigger: "change", message: "请选择变动数！" }],
  flag: [{ required: true, trigger: "change", message: "选择变动类型" }]
});

const initData = async () => {
  const { code, data, message } = await httpDetail({ id: id.value });
  responseHandle({
    code,
    message,
    logout,
    handler: () => {
      Object.keys(ruleForm.value).forEach(key => {
        if (key === "flag") {
          ruleForm.value[key] = "1";
        } else if (key === "id") {
          ruleForm.value[key] = data[key] ? data[key] + "" : "";
        } else {
          ruleForm.value[key] = data[key] ? Number(data[key] + "") : 0;
        }
      });
      inventory.value = Number(data.inventory);
      PageDetailRef.value.reload({ id: data.good_id });
    }
  });
};
async function show(node: any, did: string, isCreate: string) {
  id.value = did;
  loading.value = true;
  Object.keys(ruleForm.value).forEach(key => {
    ruleForm.value[key] = initform[key];
  });
  TYPE.value = isCreate;
  switch (TYPE.value) {
    case "create":
      titleType.value = "新建兑换商品库存";
      break;
    case "edit":
      titleType.value = "编辑兑换商品库存";
      break;
    case "view":
      titleType.value = "兑换商品库存详情";
      break;
    default:
      titleType.value = "新建兑换商品库存";
  }

  showModel.value = true;
  if (TYPE.value !== "create") {
    await initData();
  }
  loading.value = false;
}
function handleUpdate() {
  const data = {
    ...ruleForm.value
  };

  return {
    data,
    api: httpUpdate
  };
}

function handleSave() {
  formRef.value.validate(async vaild => {
    if (vaild) {
      if (loading.value) return;
      loading.value = true;
      const handler = handleUpdate;
      const { api, data } = handler();
      const { flag, number } = data;
      if (flag === "-1") {
        if (Number(number) > Number(inventory.value)) {
          ElMessage.warning(
            `减少库存操作时，变动库存不能大于当前库存${inventory.value}！`
          );
          loading.value = false;
          return;
        }
      }
      const { message, code } = await api(data);
      loading.value = false;
      responseHandle({
        code,
        message,
        logout,
        handler: () => {
          showModel.value = false;
          emit("reload");
        }
      });
    }
  });
}
defineExpose({
  show
});
</script>

<template>
  <el-dialog
    v-model="showModel"
    :close-on-press-escape="false"
    center
    append-to-body
    destroy-on-close
    :width="'1040px'"
    :title="titleType"
    v-loading="loading"
  >
    <el-form
      ref="formRef"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      style="margin-top: -10px"
      class="demo-ruleForm"
      status-icon
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="当前库存数" prop="inventory">
            <el-input-number
              v-model="ruleForm.inventory"
              :step="1"
              :min="0"
              :disabled="true"
              :precision="0"
              style="width: 100%"
              :max="99999999"
              value-on-clear="min"
              controls-position="right"
              step-strictly
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="TYPE !== 'view'">
          <el-form-item label="变动类型" prop="flag">
            <el-select
              v-model="ruleForm.flag"
              placeholder="变动类型"
              :disabled="TYPE === 'view'"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in FLAG_OPTIONS"
                :label="item.label"
                :value="item.id"
                :key="item.id + index"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6" v-if="TYPE !== 'view'">
          <el-form-item label="变动数量" prop="number">
            <el-input-number
              v-model="ruleForm.number"
              :step="1"
              :min="1"
              :disabled="TYPE === 'view'"
              :precision="0"
              style="width: 100%"
              :max="99999999"
              value-on-clear="min"
              controls-position="right"
              step-strictly
            />
          </el-form-item>
        </el-col>

        <el-col :span="TYPE !== 'view' ? 6 : 18" class="flex justify-end">
          <el-button
            v-if="TYPE !== 'view'"
            :loading="loading"
            :disabled="loading"
            type="primary"
            @click="handleSave"
            >保存</el-button
          >
          <el-button @click="showModel = false">取消</el-button>
        </el-col>
        <el-col :span="24">
          <el-form-item label="商品信息">
            <PageDetail ref="PageDetailRef" :contentConfig="goodDetailConfig" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
