<script setup lang="ts">
import { FormRules, ElForm, ElMessage } from "element-plus";
import { reactive, ref } from "vue";
import { httpAdd, httpUpdate, httpDetail } from "/@/api/mobile/exchangeStock";
import { responseHandle } from "/@/utils/responseHandle";
import { useNav } from "/@/layout/hooks/useNav";
import { ComCard } from "/@/components/RemoteSelect";
import OrderDialog from "/@/components/PageListModal";
import LadderTable from "./ladder-table.vue";
// import LadderModal from "./ladder-modal.vue";
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 ladderModalRef = ref<InstanceType<typeof LadderModal>>(null);

const formRef = ref<InstanceType<typeof ElForm>>(null);
const modelOrderRef = ref<InstanceType<typeof OrderDialog>>(null);
const loading = ref(false);
const titleType = ref("");
const inventory = ref(0);
const id = ref("");
const emit = defineEmits(["reload"]);
const initform = {
  group_id: "",
  list: []
};
const ruleForm = ref({ ...initform });
const rules = reactive<FormRules>({
  group_id: [
    { required: true, trigger: "change", message: "请选择公司卡类型！" }
  ],
  list: [
    { required: true, type: "array", 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 {
          ruleForm.value[key] = data[key] ? data[key] + "" : "";
        }
      });
      inventory.value = Number(data.inventory);
    }
  });
};
function modularShow() {
  console.log(ruleForm.value);
  if (!ruleForm.value.group_id) {
    ElMessage.warning("请选择公司卡类型！");
    return;
  }
  modelOrderRef.value.show(ruleForm.value.group_id, "1");
}
function handleAddOrder(list) {
  console.log(list);
  list.forEach(item => {
    const { id } = item;
    let findex = ruleForm.value.list.findIndex(e => e.id + "" == id + "");
    if (findex == -1) {
      let model = Object.assign(item, {
        inventory: 100
      });
      ruleForm.value.list.push(model);
    }
  });
}
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 handleCreate() {
  const data = {
    ...ruleForm.value
  };

  return {
    data,
    api: httpAdd
  };
}

function handleSave() {
  formRef.value.validate(async vaild => {
    if (vaild) {
      if (loading.value) return;
      loading.value = true;
      const handler =
        TYPE.value === FROM_TYPE.create ? handleCreate : handleUpdate;
      const { api, data } = handler();
      const { group_id, list } = data;
      const model = {
        group_id,
        list: []
      };
      let isok = true;
      list.forEach(si => {
        if (Number.isNaN(si.inventory) || Number(si.inventory) === 0) {
          isok = false;
        }
        model.list.push({ good_id: si.id, inventory: si.inventory });
      });
      if (!isok) {
        ElMessage.warning("部分商品添加库存数为0！");
        loading.value = false;
        return;
      }
      const { message, code } = await api(model);
      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="24">
          <el-form-item label="公司卡类型" prop="group_id">
            <ComCard
              v-model="ruleForm.group_id"
              :disabled="TYPE === 'view'"
              placeholder="公司卡类型"
              @change="ruleForm.list = []"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="商品信息" prop="list">
            <LadderTable
              :readonly="false"
              :ladder="ruleForm.list"
              @choose="() => modularShow()"
              @delete="index => ruleForm.list.splice(index, 1)"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24" 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-row>
    </el-form>
  </el-dialog>
  <OrderDialog ref="modelOrderRef" @save-btn-click="handleAddOrder" />
</template>
