<script setup>
import AgentForm from "@/views/components/AgentForm";
import { reactive, ref, toRefs } from "vue";
import { agentAdd, agentDetail, agentEdit } from "@/api/dataList/agent";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import tab from "@/plugins/tab";

const route = useRoute();
const data = reactive({
  form: {
    idImage: [],
  },
});
const { form } = toRefs(data);
const agentFormRef = ref();
const getAgentDetail = (id) => {
  agentDetail(id).then((resp) => {
    form.value = resp.data;
    form.value.idImage = form.value.idCardPics?.split(",") ?? [];
    form.value.keywords = form.value.keyword?.split(",") ?? [];
  });
};

const cancel = () => {
  tab.closeOpenPage({
    path: "/dataList/agent",
  });
};
const submitForm = async () => {
  const valid = await agentFormRef.value.validateForm();
  if (valid) {
    form.value.idCardPics = form.value.idImage.join(",");
    form.value.keyword = form.value.keywords.join(",");
    console.log(form.value);
    if (form.value.brokerId) {
      agentEdit(form.value).then(() => {
        ElMessage.success("修改经纪人成功");
      });
    } else {
      agentAdd(form.value).then(() => {
        ElMessage.success("新增经纪人成功");
      });
    }
    cancel();
  }
};
if (route.query.id) {
  getAgentDetail(route.query.id);
}
</script>

<template>
  <div class="app-container">
    <el-card style="width: 55%; margin: 0 auto">
      <agent-form ref="agentFormRef" v-model="form" />
      <el-row justify="center">
        <el-col :span="1.5">
          <el-button type="primary" @click="submitForm">提交</el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<style lang="scss" scoped></style>
