<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="80vw" @confirm="handleSubmit"
            @close="handleClose">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
                <el-col>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="审批流名称" prop="name">
                                <el-input v-model="formData.name" clearable placeholder="请输入审批流名称" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="审批分类">
                                <el-select class="flex-1" v-model="formData.flow_type" clearable placeholder="请选择所属分类"
                                    @change="getFlowTypeList">
                                    <el-option v-for="(item, index) in dictData.flow_type" :key="index"
                                        :label="item.name" :value="parseInt(item.value)" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="审批类型" prop="flow_cate">
                                <el-select class="flex-1" v-model="formData.flow_cate" :disabled="!formData.flow_type"
                                    clearable placeholder="请选择审批类型">
                                    <el-option v-for="(item, index) in flowTypeList" :key="index" :label="item.title"
                                        :value="parseInt(item.id)" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col>
                            <el-form-item label="流程说明" prop="remark">
                                <el-input v-model="formData.remark" clearable type="textarea" placeholder="请输入流程说明" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="状态" prop="status" v-if="mode == 'edit'">
                        <el-radio-group v-model="formData.status" placeholder="请选择状态">
                            <el-radio v-for="(item, index) in dictData.flow_type_status" :key="index"
                                :label="(item.value)">
                                {{ item.name }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="流程类型" prop="check_type" clearable :style="{ width: '100%' }">
                        <el-radio-group v-model="formData.check_type" @change="checkTypeFn">
                            <el-radio :label="1">固定审批</el-radio>
                            <!-- <el-radio :label="2">授权审批人</el-radio>
                            <el-radio :label="3">可回退审批 </el-radio> -->
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <p v-if="formData.check_type == 1">
                    <el-row v-for="(item, index) in formData.flow_list">
                        <el-col :span="8">
                            <el-form-item label="审批流程">
                                <el-select v-model="item.flow_step" placeholder="审批类型" @change="clearFlowUser(index)"
                                    clearable :style="{ width: '100%' }">
                                    <el-option :value="item.value" :label="item.name"
                                        v-for="(item, index) in dictData.flow_step_flow_type"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="item.flow_step == '3' || item.flow_step == '2'">
                            <el-form-item label="指定人员">
                                <el-tag v-for="(tag, i) in item.flow_user" @close="item.flow_user.splice(i, 1)"
                                    :key="tag.id" class="mx-1" closable>
                                    {{ tag.name }}
                                </el-tag>
                                <el-button type="primary" @click="openDialog(index)">
                                    选择人员
                                </el-button>

                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-button @click="formData.flow_list.splice(index, 1)">
                                删除
                            </el-button>
                        </el-col>

                    </el-row>
                    <el-col :span="24">
                        <el-form-item>
                            <el-button type="primary" @click="
            formData.flow_list.push(
                {
                    flow_step: '',
                    flow_user: []
                }
            )
            ">其他联系人</el-button>
                        </el-form-item>
                    </el-col>
                </p>
                <el-row v-if="formData.check_type == 2">
                    <el-col :span="12">
                        <el-form-item label="">
                            <span>无需审批</span>
                        </el-form-item>
                    </el-col>
                </el-row>

                <p v-if="formData.check_type == 3">
                    <el-row v-for="(item, index) in formData.flow_list">
                        <el-col :span="8">
                            <el-form-item label="审批流程" prop="copy_uids">
                                <el-input v-model="item.flow_step" clearable placeholder="请输入流程名称">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="指定人员">
                                <el-tag v-for="(tag, i) in item.flow_user" @close="item.flow_user.splice(i, 1)"
                                    :key="tag.id" class="mx-1" closable>
                                    {{ tag.name }}
                                </el-tag>
                                <el-button type="primary" @click="openDialog(index)">
                                    选择人员
                                </el-button>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-button @click="formData.flow_list.splice(index, 1)">
                                删除
                            </el-button>
                        </el-col>
                    </el-row>
                    <el-col :span="24">
                        <el-form-item >
                            <el-button type="primary" @click="
            formData.flow_list.push(
                {
                    flow_step: '',
                    flow_user: []
                }
            )
            ">其他联系人</el-button>
                        </el-form-item>
                    </el-col>
                </p>

                <el-form-item label="抄送人" prop="copy_unames">
                    <el-tag v-for="(tag, index) in formData.copy_uids" @close="formData.copy_uids.splice(index, 1)"
                        :key="tag.id" class="mx-1" closable>
                        {{ tag.name }}
                    </el-tag>
                    <el-button type="primary" @click="openDialog(-1)">
                        选择人员
                    </el-button>
                </el-form-item>
            </el-form>
        </popup>

        <personnelSelector v-if="showDiolg" ref="personnel" @confirm="submituser" />
    </div>
</template>

<script lang="ts" setup name="flowEdit">
import type { FormInstance } from "element-plus";
import Popup from "@/components/popup/index.vue";
import { apiFlowAdd, apiFlowEdit } from "@/api/flow";
import { apiFlowTypeLists } from '@/api/flow_type'
import personnelSelector from '@/components/personnelselector/index.vue'
import { ref } from "vue"
import type { PropType } from "vue";

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({}),
    },
});

const personnel = ref('')
const emit = defineEmits(["success", "close"]);
const formRef = shallowRef<FormInstance>();
const popupRef = shallowRef<InstanceType<typeof Popup>>();
const mode = ref("add");
const showDiolg = ref(false)

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == "edit" ? "编辑审批流程表" : "新增审批流程表";
});

// 表单数据
const formData = reactive({
    id: "",
    name: "",
    check_type: "",
    flow_type: "",
    flow_cate: "",
    remark: "",
    flow_list: [
        {
            flow_step: "",
            flow_user: []
        },

    ],
    copy_uids: [],
    status: 0
});

// 获取对应审批类型
const flowTypeList = reactive([])

const getFlowTypeList = async () => {
    if (!formData.flow_type) return
    let res = await apiFlowTypeLists({
        type: formData.flow_type,
        status: 2
    })
    Object.assign(flowTypeList, res.lists)
}


//单选框改变时清空单选下的表单数据
const checkTypeFn = () => {
    formData.flow_list = [
        {
            "flow_step": "",
            "flow_user": []
        },
    ]
};

// 表单验证
const formRules = reactive<any>({});

const setRules = () => {
    let ruleList = ['name', 'check_type', 'type', 'flow_cate', 'remark', 'copy_uids']

    ruleList.forEach(item => {
        formRules[item] = {
            required: true,
            message: "请输入审批流名称",
            trigger: ["blur"]
        }
    })
}
setRules()

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key];
        }
    }
    await getFlowTypeList()
    formData.check_type = Number(formData.check_type)
    formData.flow_type = Number(formData.flow_type)
};


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate();
    formData.copy_uids = [].concat(...formData.copy_uids.map(item => ([item.id])));
    formData.flow_list.forEach(item => {
        item.flow_user = [].concat(...item.flow_user.map(items => ([items.id])));
    });
    mode.value == "edit"
        ? await apiFlowEdit(formData)
        : await apiFlowAdd(formData);
    popupRef.value?.close();
    emit("success");
};

const submituser = (e) => {

    if (selectIndex == -1) {
        formData.copy_uids = e.map(item => ({ id: item.id, name: item.name }))
    } else {
        formData.flow_list[selectIndex].flow_user = e.map(item => ({ id: item.id, name: item.name }))
    }
    showDiolg.value = false


}

const clearFlowUser = (index) => {
    formData.flow_list[index].flow_user = []
}

//打开弹窗
const open = (type = "add") => {
    mode.value = type;
    popupRef.value?.open();
};

// 关闭回调
const handleClose = () => {
    emit("close");
};

// selectIndex为-1时为抄送选择抄送人员,其余为指定人员所在的flow_list的下标
let selectIndex;
const openDialog = async (index) => {
    showDiolg.value = true
    await nextTick()
    personnel.value?.open()
    selectIndex = index
}

defineExpose({
    open,
    setFormData,
});
</script>
