<script setup lang="ts">
import { FormRules, ElForm } from "element-plus";
import { reactive, ref } from "vue";
import { httpUpdate, httpAdd, httpDetail } from "/@/api/operate/setComGood";
import { responseHandle } from "/@/utils/responseHandle";
import { useNav } from "/@/layout/hooks/useNav";

import { ElMessage } from "element-plus";
import { ComCard } from "/@/components/RemoteSelect";
import LadderTable from "./ladder-table.vue";
import OrderDialog from "/@/components/PageListModal";
const modelRef = ref<InstanceType<typeof OrderDialog>>(null);
import dayjs from "dayjs";
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 loading = ref(false);
const titleType = ref("");
const id = ref("");
const emit = defineEmits(["reload"]);
const initform = {
  group_id: "",
  good_id: []
};
const ruleForm = ref({ ...initform });
const rules = reactive<FormRules>({
  group_id: [
    { required: true, trigger: "change", message: "请选择企业卡类型" }
  ],
  good_id: [
    { required: true, type: "array", trigger: "change", message: "请选择商品" }
  ]
});
const initData = async () => {
  const { code, data, message } = await httpDetail({ id: id.value });
  responseHandle({
    code,
    message,
    logout,
    handler: () => {
      console.log(data);
      Object.keys(ruleForm.value).forEach(key => {
        ruleForm.value[key] = data[key] ? data[key] + "" : "";
      });
    }
  });
};
async function show(node: any, did: string, isCreate: string) {
  id.value = did;
  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 = "新建公司商品";
  }
  if (TYPE.value !== "create") {
    await initData();
  }

  showModel.value = true;
}

function handleAddOrder(list) {
  list.forEach(item => {
    const { id } = item;
    let findex = ruleForm.value.good_id.findIndex(e => e.id + "" == id + "");
    if (findex == -1) {
      ruleForm.value.good_id.push(item);
    }
  });
}
function handleSave() {
  formRef.value.validate(async vaild => {
    if (vaild) {
      if (loading.value) return;
      loading.value = true;
      const { group_id, good_id } = ruleForm.value;
      if (good_id.length > 0) {
        loading.value = false;
        ElMessage.warning("至少选择一个商品！");
        return;
      }
      const good_id_arr = [];
      good_id.forEach(si => {
        good_id_arr.push(si.id);
      });
      const model = {
        group_id,
        good_id: good_id_arr
      };

      const { message, code } =
        TYPE.value === FROM_TYPE.create
          ? await httpAdd(model)
          : await httpUpdate(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"
              placeholder="公司卡类型"
            /> </el-form-item
        ></el-col>
        <el-col :span="24">
          <el-form-item label="商品列表" prop="good_id">
            <LadderTable
              :readonly="false"
              :ladder="ruleForm.good_id"
              @choose="() => modelRef.show('')"
              @delete="index => ruleForm.good_id.splice(index, 1)"
            /> </el-form-item
        ></el-col>
      </el-row>
      <div 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>
      </div>
    </el-form>
  </el-dialog>
  <OrderDialog ref="modelRef" @save-btn-click="handleAddOrder" />
</template>
