<script setup lang="ts">
import { computed, ref, watchEffect, reactive, unref } from "vue";
import { ActionType } from "/@/components/PageContent";
import { createBasicTitle } from "./utils/create-basic-title";
import BasicDescriptions from "/@/components/BasicDescriptions";
import { ElForm, ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { projectFormRules } from "../config/_rules";
import { FLAG_OPTIONS } from "/@/config/status";
import { useNav } from "/@/layout/hooks/useNav";
import { bargainColumns } from "../config/_details";
const { logout } = useNav();
import { httpAdd, httpDetail, httpUpdate } from "/@/api/mobile/shopStock";
const emit = defineEmits(["submitOk"]);
const ruleFormRef = ref<FormInstance>();
const form = {
  id: "",
  number: 1,
  flag: "1"
};
const ruleForm = reactive({ ...form });
const type = ref<ActionType>("preview");
const dialogVisible = ref(false);
const confirmLoading = ref(false);
const title = ref("");
const uID = ref("");
const bargain = ref({});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (confirmLoading.value) return;
      confirmLoading.value = true;
      const model = unref(ruleForm);
      const { flag, number } = model;
      const { inventory } = bargain;
      if (flag === "-1") {
        if (Number(number) > Number(inventory)) {
          ElMessage.warning("减少库存操作时，变动库存不能大于当前库存！");
          return;
        }
      }
      let res = {};
      if (type.value == "create") {
        delete model["id"];
        res = await httpAdd(model);
      } else {
        res = await httpUpdate(model);
      }
      const { code: hcode, data, message } = res;
      confirmLoading.value = false;
      if (hcode === 0) {
        dialogVisible.value = false;
        emit("submitOk", {});
      } else if (hcode >= 100 && hcode <= 104) {
        logout();
      } else {
        ElMessage.warning(message);
      }
    } else {
      console.log("error submit!", fields);
    }
    handleAddOrder;
  });
};

function handleAddOrder(list) {
  console.log(list);
}
const initData = async () => {
  if (confirmLoading.value) return;
  confirmLoading.value = true;
  const { code, data, message } = await httpDetail({ id: uID.value });
  if (code === 0) {
    bargain.value = data;
    const { id } = data;
    ruleForm.id = id;
  } else if (code >= 100 && code <= 104) {
    logout();
  } else {
    ElMessage.warning(message);
  }
  confirmLoading.value = false;
};
defineExpose({
  onShow: async (basicTitle: string, readonly: ActionType, id: string) => {
    type.value = readonly;
    const readTitle = createBasicTitle(type.value);
    title.value =
      readonly == "preview" ? basicTitle + readTitle : readTitle + basicTitle;
    Object.keys(ruleForm).forEach(key => {
      ruleForm[key] = form[key];
    });
    dialogVisible.value = true;
    confirmLoading.value = false;
    uID.value = id;
    bargain.value = {};
    if (type.value !== "create") {
      await initData();
    }
  }
});
</script>

<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    center
    top="5vh"
    destroy-on-close
    width="1024px"
  >
    <BasicDescriptions
      labelWidth="120"
      v-if="bargain && bargain?.id"
      :columns="bargainColumns"
      :data="bargain"
    />
    <el-form
      ref="ruleFormRef"
      v-loading="confirmLoading"
      :model="ruleForm"
      v-show="type !== 'preview'"
      :rules="projectFormRules"
      label-width="100px"
      :disabled="type === 'preview'"
      status-icon
    >
      <el-row style="padding: 20px 0 0 0">
        <el-col :span="8">
          <el-form-item label="变动状态" prop="flag">
            <el-select
              v-model="ruleForm.flag"
              placeholder="变动状态"
              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="8">
          <el-form-item label="变动数量" prop="number">
            <el-input-number
              v-model="ruleForm.number"
              :step="1"
              :min="1"
              :precision="0"
              style="width: 100%"
              :max="99999999"
              value-on-clear="min"
              controls-position="right"
              step-strictly
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <div class="w-full flex justify-end">
              <el-button type="primary" @click="submitForm(ruleFormRef)"
                >提交</el-button
              >
              <ElButton @click="() => (dialogVisible = false)">取消</ElButton>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
