<template>
    <SysDialog class="addedit-product-rateratio" :visible="dialog.visible" v-bind="getBindValue" @onClose="onclose"
        @onConfirm="confirm">
        <template #content>
            <el-form ref="noticeFormRef" :model="noticeForm" inline label-width="80">
                <el-form-item label="客户" prop="customer" class="rateratio-item" :rules="customerRules">
                    <BaseSelect class="item-w-100" v-model:modelValue="noticeForm.customer"
                        :options="storePersonnel.customerList" :clearable="true" remote multiple collapse-tags
                        :is-loading="true" :isKeyObject="true" placeholder="客户" @change="changeCustomer" />
                </el-form-item>
                <el-form-item label="业务人员" prop="salesmanUser" class="rateratio-item" :rules="salesmanUserRules">
                    <BaseSelect class="item-w-100" v-model:modelValue="noticeForm.salesmanUser"
                        :options="storePersonnel.salesmanUsesList" :clearable="true" remote multiple collapse-tags
                        :is-loading="true" :isKeyObject="true" placeholder="业务人员" @change="changeSalesmanUser" />
                </el-form-item>
                <el-form-item label="标题" prop="targetName" class="rateratio-item" :rules="noticeFormRules.targetName">
                    <el-input v-model="noticeForm.targetName" placeholder="标题"></el-input>
                </el-form-item>
                <el-form-item label="通知内容" prop="content" class="content">
                    <MarkDown v-model:value="noticeForm.content" mode="wysiwyg" :width="baseMarkDown.width"
                        :height="baseMarkDown.height" :toolbar="baseMarkDown.toolbar" @change="handleChange"
                        ref="markDownRef" placeholder="这是占位文本">
                    </MarkDown>
                </el-form-item>
            </el-form>
        </template>
    </SysDialog>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, nextTick } from 'vue';
import SysDialog from "@/components/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import MarkDown from '@/components/Markdown/src/Markdown.vue';
import BaseSelect from '@/components/QuerySelect/BaseSelect.vue';
import { usePersonnel } from '@/store/list_personnel';
import { NoticeDto } from '@/api/newsInfo/newsInfoModel';
import { isArrayLength } from '@/utils/is';
import { ListIitem } from '@/api/base/BaseDataModel';
import { cloneDeep } from '@/utils/cloneDeep';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';

const props = defineProps<{
    multipleSelection: string[]
}>()
const emit = defineEmits(['saveNotice'])
//弹框属性
const { dialog, onClose, onShow } = useDialog();
const storePersonnel = usePersonnel()
const { formValidate, resetForm, clearValidateForm } = useEleFormValidate();
// 弹框一些配置
const getBindValue = reactive({
    title: "消息通知",
    width: 675,
    height: 0,
});
const noticeFormRef = ref()
const markDownRef = ref()
const baseMarkDown = reactive({
    width: '100%',
    height: 450,
    toolbar: [
        'headings',
        'bold',
        'link',
        'inline-code',
        'quote',
        'insert-before',
        'insert-after',
    ],
})
// 参数
const noticeForm = reactive<NoticeDto & Recordable>({
    // 暂存的列表数据
    customer: null,
    salesmanUser: null,
    targetObjectModelList: [],
    productIdWithVersion: [],
    targetName: '',
    content: ''
})
const noticeFormRules = reactive({
    targetName: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    customer: [{ required: true, message: '请选择客户', trigger: 'change' }],
    salesmanUser: [{ required: true, message: '请选择业务人员', trigger: 'change' }]
})
// 费用设置数据(多选)
const multipleSelection = computed(() => props.multipleSelection)
//客户人员校验-关联业务人员
const customerRules = computed({
    get: () => {
        if (isArrayLength(noticeForm.salesmanUser)) {
            clearValidateForm(noticeFormRef.value)
            return [{ required: false, message: '请选择客户', trigger: 'change' }]
        } else {
            salesmanUserRules.value = noticeFormRules.salesmanUser
            return noticeFormRules.customer
        }
    },
    set: (val) => {
        noticeFormRules.customer = val
    }
})
//业务人员校验-关联客户人员
const salesmanUserRules = computed({
    get: () => {
        if (isArrayLength(noticeForm.customer)) {
            clearValidateForm(noticeFormRef.value)
            return [{ required: false, message: '请选择业务人员', trigger: 'change' }]
        } else {
            customerRules.value = noticeFormRules.customer
            return noticeFormRules.salesmanUser
        }
    },
    set: (val) => {
        noticeFormRules.salesmanUser = val
    }
})

// 文本框输入事件
function handleChange(val: string) {
    noticeForm.content = val;
    // console.log(unref(markDownRef), ":markDownRef", val)
}
// 确定
const confirm = async () => {
    const isValidate = await formValidate(noticeFormRef.value)
    if (!isValidate) return
    noticeForm.customer = null
    noticeForm.salesmanUser = null
    const params = cloneDeep(noticeForm)
    // console.log(params, ":params");
    emit('saveNotice', params)
    onclose()
}
const onclose = () => {
    onClose()
    resetForm(noticeFormRef.value)
    noticeForm.targetObjectModelList = []
    noticeForm.customer = null
    noticeForm.salesmanUser = null
}
const show = () => {
    storePersonnel.addGetCustomerList()
    storePersonnel.addGetSalesmanUserList()
    onShow()
    nextTick(() => {
        noticeForm.productIdWithVersion = multipleSelection.value//产品编号+版本编号
        // initData()
        // console.log(multipleSelection.value, ":multipleSelection");
    })
}

// 测试数据
const initData = () => {
    // 创建一个正则表达式以匹配 HTML 标签
    const regex = /<[^>]+>/g;
    const text =
        '您的会议室已经预定，稍后会同步到`邮箱`  \n>**事项详情**  \n>事　项：<font color="info">开会</font>  \n>组织者：@miglioguan  \n>参与者：@miglioguan、@kunliu、@jamdeezhou、@kanexiong、@kisonwang  \n>  \n>会议室：<font color="info">广州TIT 1楼 301</font>  \n>日　期：<font color="warning">2018年5月18日</font>  \n>时　间：<font color="comment">上午9:00-11:00</font>  \n>  \n>请准时参加会议。  \n>  \n>如需修改会议信息，请点击：[修改会议信息](https://work.weixin.qq.com)';
    const textArr = text.split('\n');
    const textNews = textArr.map((item) => {
        if (item.startsWith('>')) item = item.replace('>', '> ');
        return item;
    });
    const dataText = textNews.map((item) => {
        // 过滤HTML标签
        if (item) item = item.replace(regex, '');
        return item;
    });
    const textContent = dataText.join('\n');
    noticeForm.content = textContent
}

// 添加通知目标对象
const targetObjectModel = (val: ListIitem[], objectType: 0 | 1) => {
    const targetIdList: string[] = []
    const targetNameList: string[] = []
    for (const item of val) {
        if (item) {
            // 获取value、label值
            targetIdList.push(String(item.value))
            targetNameList.push(item.label)
        }
    }
    // 是否存在客户人员数据
    const isCustomer = noticeForm.targetObjectModelList.some(item => item.objectType === objectType)
    if (isCustomer) {
        noticeForm.targetObjectModelList.map(item => {
            if (item.objectType === objectType) {
                // 改变已有客户人员
                Object.assign(item, { objectType, targetIdList, targetNameList })
            }
        })
        return false
    }
    // 添加
    noticeForm.targetObjectModelList.push({ objectType, targetIdList, targetNameList })
}
// 选择处理客户人员
const changeCustomer = (val: ListIitem[]) => {
    if (!isArrayLength(val)) return
    targetObjectModel(val, 1)
}
// 选择处理业务人员
const changeSalesmanUser = (val: ListIitem[]) => {
    if (!isArrayLength(val)) return
    targetObjectModel(val, 0)
}

//父组件调用子组件显示弹框
//暴露出去给外部使用
defineExpose({
    show
});
</script>
<style lang="scss" scoped>
.addedit-product-rateratio {
    .rateratio-item {
        width: 45%;

        .item-w-100 {
            width: 100%;
        }
    }

    .personnel {
        margin-left: 8px;
    }

    .content {
        display: block;
        margin-right: 0;
    }
}
</style>