<template>
    <div class="table-box">
        <div style="padding-bottom: 16px">
            <PermissionButton
                :buttons="dataStore.buttons"
                @handleButtonClickCallback="handleButtonClickCallback"
            ></PermissionButton>
        </div>
        <div class="card table-main">
            <DetailsSearch
                :formData="dataStore.formData"
                :ruleForm="dataStore.ruleForm"
                :labelWidth="dataStore.labelWidth"
                @selectMultipleRemoveTag="handleSelectMultipleRemoveTag"
                :inline="true"
            />
        </div>
    </div>
</template>

<script setup lang="ts" name="foundationSubscribeListAdd">
import PermissionButton from "@/components/PermissionButton/index.vue";
import DetailsSearch from "@/components/DetailsSearch/index.vue";
import { FORM_DATA, RULE_FORM } from "./constant/add";
import { useRoute } from "vue-router";

import { getSubscribeDetailsApi, getSubscribeAddApi, getSubscribeUpdateApi } from "@/api/modules/subscribe";
import { setDetailsData } from "./init/setDetailsData";
import { useMsg } from "@/hooks/useMsg";
import { BUTTON } from "./constant/add/button";
import { useUserStore } from "@/stores/modules/user";
import { cloneDeep } from "lodash-es";

const dataStore = reactive({
    formData: cloneDeep(FORM_DATA),
    ruleForm: cloneDeep(RULE_FORM),
    labelWidth: "120px",
    buttons: cloneDeep(BUTTON),
    selectOptions: [],
    isAdd: false, //用于判断用户是否点击了新增按钮
    selectedValues: [] // 绑定选中值：数组类型（因 multiple 为 true）
});
const userStore = useUserStore();
const $route = useRoute();

dataStore.formData[0].options = userStore.orgIdArr;
const init = () => {
    //$route.query.title === "新增订阅" ? org_number: ["101"],
    if ($route.query.title === "新增订阅") {
        dataStore.ruleForm.org_number = ["101"];
    }
};
init();
//新增
const handleAdd = () => {
    if (
        dataStore.ruleForm?.customer_number.length ||
        dataStore.ruleForm?.org_number ||
        dataStore.ruleForm?.product_lines ||
        dataStore.ruleForm?.subscriber_dduid
    ) {
        ElMessageBox.confirm("当前数据未提交, 确认放弃新增数据?", "温馨提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        })
            .then(async () => {
                dataStore.ruleForm = cloneDeep(RULE_FORM);
                dataStore.isAdd = true;
            })
            .catch(() => {});
    }
};

//添加
const getSubscribeAdd = async (params: any) => {
    const result = await getSubscribeAddApi(params);
    if (result?.code === 0) {
        useMsg("success", "新增成功 ！");
    }
};
//更新
const getSubscribeUpdate = async (params: any) => {
    const result = await getSubscribeUpdateApi($route.query.id, params);
    if (result?.code === 0) {
        useMsg("success", "更新成功 ！");
    }
};

const handleCommit = () => {
    if (!dataStore?.ruleForm?.org_number?.length) {
        return useMsg("warning", "组织不能为空 ! ");
    }
    if (!dataStore?.ruleForm?.customer_number?.length) {
        return useMsg("warning", "客户名称不能为空 ! ");
    }
    if (!dataStore?.ruleForm?.product_lines?.length) {
        return useMsg("warning", "品线不能为空 ! ");
    }
    if (!dataStore?.ruleForm?.subscriber_dduid) {
        return useMsg("warning", "订阅账号不能为空 ! ");
    }
    //参数
    let params = {
        org_number: dataStore.ruleForm?.org_number.join(","),
        product_lines: dataStore.ruleForm?.product_lines.join(","),
        customer_number: dataStore.ruleForm?.customer_number.join(","),
        subscriber_dduid: dataStore.ruleForm?.subscriber_dduid
    };

    if (dataStore.isAdd || $route.query.title === "新增订阅") {
        getSubscribeAdd(params);
    }
    if (!dataStore.isAdd && $route.query.title === "编辑订阅") {
        getSubscribeUpdate(params);
    }
};
//详情
const getSubscribeDetails = async () => {
    console.log($route.query.id);
    let id = $route.query.id;
    if (!id) {
        return;
    }
    const result = await getSubscribeDetailsApi(id);
    if (result?.code === 0) {
        const { data } = result;
        //设置详情数据
        setDetailsData(dataStore, data);
    }
};
//本地多选远程搜索Tag删除回调(组织)
const handleSelectMultipleRemoveTag = async (params: any) => {
    const { org_number } = params;
    let customers: any = [];
    // 筛选出 org_number 在 ids 中的数据
    dataStore.formData[1].options = dataStore.formData[1].options.filter((item: any) => org_number.includes(item.org_number));

    dataStore.formData[1].options.length &&
        dataStore.formData[1].options.forEach((item: any) => {
            customers.push(item.value);
        });

    dataStore.ruleForm.customer_number = customers;
};
getSubscribeDetails();

const handleButtonClickCallback = (item: any) => {
    console.log(item);
    if (item?.type === "add") {
        handleAdd();
    }
    if (item?.type === "commit") {
        handleCommit();
    }
};
</script>
