<template>
    <div class="hc-project-list-adjust-excel-set-input">
        <el-form
            ref="formRef"
            :model="formModel"
            :rules="formRules"
            label-position="left"
            label-width="auto"
        >
            <el-form-item label="元素坐标：" prop="name">
                <el-input
                    v-model="formModel.name"
                    placeholder="请点击左侧表单"
                    disabled
                />
            </el-form-item>
            <el-form-item label="文本格式：" prop="textId">
                <el-select
                    v-model="formModel.textId"
                    filterable
                    block
                    placeholder="请选择文本格式"
                >
                    <el-option
                        v-for="item in sysTextType"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-row
                v-if="
                    formModel.textId === 'date' ||
                    formModel.textId === 'daterange'
                "
                :gutter="20"
            >
                <el-col :span="18">
                    <el-form-item label="日期格式：" prop="date">
                        <el-checkbox-group v-model="formModel.date">
                            <el-checkbox
                                v-for="item in yearList"
                                :key="item.value"
                                :value="item.value"
                                >{{ item.label }}</el-checkbox
                            >
                        </el-checkbox-group>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="" prop="divide_y">
                        <el-select
                            v-model="formModel.divide_y"
                            block
                            placeholder="选择分隔符"
                        >
                            <el-option label="文本" value="文本" />
                            <el-option label="-" value="-" />
                            <el-option label="/" value="/" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row
                v-if="
                    formModel.textId === 'date' ||
                    formModel.textId === 'daterange'
                "
                :gutter="20"
            >
                <el-col :span="18">
                    <el-form-item label="时间格式：" prop="time">
                        <el-checkbox-group v-model="formModel.time">
                            <el-checkbox
                                v-for="item in timeList"
                                :key="item.value"
                                :value="item.value"
                                >{{ item.label }}</el-checkbox
                            >
                        </el-checkbox-group>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="" prop="divide_h">
                        <el-select
                            v-model="formModel.divide_h"
                            block
                            placeholder="选择分隔符"
                        >
                            <el-option label="文本" value="文本" />
                            <el-option label=":" value=":" />
                            <el-option label="/" value="/" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item
                v-if="formModel.textId === 'daterange'"
                label="中间分隔符："
                prop="divide_c"
            >
                <el-select
                    v-model="formModel.divide_c"
                    block
                    placeholder="选择中间分隔符"
                >
                    <el-option label="至" value="至" />
                    <el-option label="-" value="-" />
                    <el-option label="~" value="~" />
                </el-select>
            </el-form-item>
        </el-form>
        <hc-card-item
            v-if="
                ['select', 'radio', 'checkbox', 'selectBox'].indexOf(
                    formModel.textId
                ) !== -1
            "
            title="相关数据："
        >
            <template #extra>
                <el-button type="primary" size="small" @click="addTableData"
                    >新增</el-button
                >
            </template>
            <hc-table
                :column="tableColumn"
                :datas="tableData"
                :is-current-row="false"
            >
                <template #dictValue="{ row }">
                    <hc-table-input v-model="row.dictValue" />
                </template>
                <template #action="{ index }">
                    <el-link type="danger" @click="rowDelClick(index)"
                        >删除</el-link
                    >
                </template>
            </hc-table>
        </hc-card-item>
        <div class="action-btn-box mt-30px text-center">
            <el-button
                type="primary"
                :loading="submitLoading"
                @click="dialogSubmit"
            >
                <hc-icon name="save" />
                <span>保存设置</span>
            </el-button>
        </div>
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { deepClone, formValidate, getObjValue, isNullES } from "js-fast-way";
import { getDictionaryData } from "~uti/tools";
import mainApi from "~api/project/tree";

const props = defineProps({
    info: {
        type: Object,
        default: () => ({}),
    },
});

//事件
const emit = defineEmits(["finish"]);

//监听数据
const dataInfo = ref(props.info);
watch(
    () => props.info,
    (data) => {
        dataInfo.value = getObjValue(data);
    },
    { immediate: true, deep: true }
);

//渲染完成
onMounted(() => {
    getDataApi();
});

//获取数据
const sysTextType = ref([]);
const getDataApi = async () => {
    sysTextType.value = await getDictionaryData("sys_text_type");
};

//年月日，时分秒
const yearList = [
    { label: "年", value: "YYYY", sort: 1 },
    { label: "月", value: "MM", sort: 2 },
    { label: "日", value: "DD", sort: 3 },
];
const timeList = [
    { label: "时", value: "HH", sort: 4 },
    { label: "分", value: "mm", sort: 5 },
    { label: "秒", value: "ss", sort: 6 },
];

//基础表单
const formRef = ref(null);
const formModel = ref({
    date: ["YYYY", "MM", "DD"],
    divide_y: "文本",
    time: ["HH", "mm", "ss"],
    divide_h: "文本",
    divide_c: "至",
});
const formRules = {
    name: { required: true, trigger: "blur", message: "请先获取元素坐标" },
    textId: { required: true, trigger: "blur", message: "请选择文本格式" },
    //date: { required: true, trigger: 'blur', message: '请选择日期格式' },
    divide_y: { required: true, trigger: "blur", message: "请选择日期分割" },
    //time: { required: true, trigger: 'blur', message: '请选择时间格式' },
    divide_h: { required: true, trigger: "blur", message: "请选择时间分割" },
    divide_c: { required: true, trigger: "blur", message: "请选择中间分隔符" },
};

//数据表格
const tableColumn = [
    { key: "dictValue", name: "默认值" },
    { key: "action", name: "操作", align: "center", width: 70 },
];
const tableData = ref([{}]);

//新增数据
const addTableData = () => {
    tableData.value.push({});
};

//删除数据
const rowDelClick = (index) => {
    tableData.value.splice(index, 1);
};

//提交
const submitLoading = ref(false);
const dialogSubmit = async () => {
    const isForm = await formValidate(formRef.value);
    if (!isForm) return false;
    submitLoading.value = true;
    const form = deepClone(formModel.value);
    //如果日期存在
    if (form.textId === "date" || form.textId === "daterange") {
        if (form.date.length <= 0 && form.time.length <= 0) {
            window.$message.warning("日期或时间，至少要选择一个");
            submitLoading.value = false;
            return;
        }
        let dateFormat = [];
        if (!isNullES(form.date) && form.date.length > 0) {
            if (form.date.indexOf("YYYY") !== -1) {
                dateFormat.push({ name: "年", value: "YYYY" });
            }
            if (form.date.indexOf("MM") !== -1) {
                dateFormat.push({ name: "月", value: "MM" });
            }
            if (form.date.indexOf("DD") !== -1) {
                dateFormat.push({ name: "日", value: "DD" });
            }
        }
        if (!isNullES(form.time) && form.time.length > 0) {
            if (form.time.indexOf("HH") !== -1) {
                dateFormat.push({ name: "时", value: "HH" });
            }
            if (form.time.indexOf("mm") !== -1) {
                dateFormat.push({ name: "分", value: "mm" });
            }
            if (form.time.indexOf("ss") !== -1) {
                dateFormat.push({ name: "秒", value: "ss" });
            }
        }
        if (!isNullES(form.date) && !isNullES(form.time)) {
            if (!isNullES(form.divide_y)) {
                dateFormat.push({ name: "divide_y", value: form.divide_y });
            }
            if (!isNullES(form.divide_h)) {
                dateFormat.push({ name: "divide_h", value: form.divide_h });
            }
            if (!isNullES(form.divide_c)) {
                dateFormat.push({ name: "divide_c", value: form.divide_c });
            }
        }
        if (dateFormat.length > 0) {
            form.dateFormat = dateFormat;
        }
    }
    //下拉框等数组数据
    if (
        ["select", "radio", "checkbox", "selectBox"].indexOf(form.textId) !== -1
    ) {
        if (tableData.value.length <= 0) {
            window.$message.warning("请先新增要选择的数据");
            submitLoading.value = false;
            return;
        }
        form.textInfo = tableData.value;
    }
    const { isRes } = await mainApi.saveTextInfo([form]);
    submitLoading.value = false;
    if (!isRes) return;
    window.$message.success("操作成功");
    emit("finish");
};

//设置dom数据
const typeObj = {
    text: "input",
    select: "select",
    multiple_select: "selectBox",
    textarea: "textarea",
    checkbox_group: "checkbox",
    form_checkbox: "checkbox",
    checkbox: "checkbox",
    radio_group: "radio",
    radio: "radio",
    date: "date",
    time: "date",
    datetime: "date",
    datetimerange: "daterange",
    dap_site_data: "searchSelect",
    strength_search: "strengthSearch",
    upload: "img",
    echart: "echart",
};
const setDomData = (item) => {
    const type = typeObj[item.type];
    const { pkeyId, primaryKeyId } = dataInfo.value;
    formModel.value = {
        name: item.text,
        key: item.key,
        type: "1",
        trIndex: item.tr,
        tdIndex: item.td,
        textId: type,
        tableId: pkeyId ? pkeyId : primaryKeyId,
    };
    let newArr = [];
    if (type === "selectBox" || type === "select" || type === "radio") {
        //获取多选相关的数据
        const dom = item?.zdom?.target;
        const child = dom.querySelectorAll(".hc-table-form-components-box");
        for (let i = 0; i < child.length; i++) {
            const val = child[i]?.getAttribute("data-label");
            newArr.push({ dictValue: val });
        }
    } else if (type === "checkbox") {
        //获取多选框数据
        const objs = isNullES(item.objs) ? [] : JSON.parse(item.objs);
        for (let i = 0; i < objs.length; i++) {
            newArr.push({ dictValue: objs[i].name });
        }
    }
    tableData.value = newArr;
    if (type === "date" || type === "daterange") {
        //分割日期时间
        const arr = item?.format?.split(" ");
        //移除空值
        const dateTimes = arr.filter((item) => {
            return !isNullES(item);
        });
        //取相关数据
        let date = "",
            time = "";
        if (dateTimes.length >= 2) {
            date = dateTimes[0];
            time = dateTimes[1];
        } else {
            //要判断下，是日期还是时间
            if (
                dateTimes[0].indexOf("Y") !== -1 ||
                dateTimes[0].indexOf("y") !== -1
            ) {
                date = dateTimes[0];
            } else if (
                dateTimes[0].indexOf("D") !== -1 ||
                dateTimes[0].indexOf("d") !== -1
            ) {
                date = dateTimes[0];
            } else if (
                dateTimes[0].indexOf("H") !== -1 ||
                dateTimes[0].indexOf("h") !== -1
            ) {
                time = dateTimes[0];
            } else if (
                dateTimes[0].indexOf("S") !== -1 ||
                dateTimes[0].indexOf("s") !== -1
            ) {
                time = dateTimes[0];
            }
        }
        //日期类型 YYYY年MM月DD日 YYYY-MM-DD  HH:mm:ss
        let dates = [],
            times = [];
        if (!isNullES(date)) {
            if (date.indexOf("Y") !== -1 || date.indexOf("y") !== -1) {
                dates.push("YYYY");
            }
            if (date.indexOf("M") !== -1 || date.indexOf("m") !== -1) {
                dates.push("MM");
            }
            if (date.indexOf("D") !== -1 || date.indexOf("d") !== -1) {
                dates.push("DD");
            }
            //分隔符
            if (
                date.indexOf("年") !== -1 ||
                date.indexOf("月") !== -1 ||
                date.indexOf("日") !== -1
            ) {
                formModel.value.divide_y = "文本";
            } else if (date.indexOf("-") !== -1) {
                formModel.value.divide_y = "-";
            } else if (date.indexOf("/") !== -1) {
                formModel.value.divide_y = "/";
            } else {
                formModel.value.divide_y = "文本";
            }
        }
        if (!isNullES(time)) {
            if (time.indexOf("H") !== -1 || time.indexOf("h") !== -1) {
                times.push("HH");
            }
            if (time.indexOf("M") !== -1 || time.indexOf("m") !== -1) {
                times.push("mm");
            }
            if (time.indexOf("S") !== -1 || time.indexOf("s") !== -1) {
                times.push("ss");
            }
            //分隔符
            if (
                time.indexOf("时") !== -1 ||
                time.indexOf("分") !== -1 ||
                time.indexOf("秒") !== -1
            ) {
                formModel.value.divide_h = "文本";
            } else if (time.indexOf(":") !== -1) {
                formModel.value.divide_h = ":";
            } else if (time.indexOf("/") !== -1) {
                formModel.value.divide_h = "/";
            } else {
                formModel.value.divide_h = "文本";
            }
        }
        formModel.value.date = dates;
        formModel.value.time = times;
        if (type === "daterange") {
            formModel.value.divide_c = item.range || "文本";
        }
    }
};

//导出函数
defineExpose({
    setDomData,
});
</script>

<style scoped lang="scss">
.hc-project-list-adjust-excel-set-input :deep(.hc-card-item-box) {
    padding: 6px 14px 14px;
    .hc-card-item-header {
        color: #101010;
        font-size: 14px;
        font-weight: unset;
    }
}
</style>
