<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="流程名称" prop="processName">
                <el-input v-model="queryParams.processName" placeholder="请输入流程名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="创建时间" prop="processCreationTime">
                <el-date-picker clearable v-model="queryParams.processCreationTime" type="date"
                    value-format="YYYY-MM-DD" placeholder="请选择创建时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="创建人" prop="processCreationUser">
                <el-input v-model="queryParams.processCreationUser" placeholder="请输入创建人" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="修改时间" prop="processUpdateTime">
                <el-date-picker clearable v-model="queryParams.processUpdateTime" type="date" value-format="YYYY-MM-DD"
                    placeholder="请选择修改时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="修改时间" prop="processUpdateUser">
                <el-input v-model="queryParams.processUpdateUser" placeholder="请输入修改时间" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索
                </el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item> -->
        </el-form>

        <el-row :gutter="10" class="mb8" style="min-height:32px">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wfProcess:wfProcess:add']">
                    新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['wfProcess:wfProcess:edit']">修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['wfProcess:wfProcess:remove']">删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport"
                    v-hasPermi="['wfProcess:wfProcess:export']">导出
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="wfProcessList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="流程表主键ID" align="center" prop="processId" /> -->
            <el-table-column label="序号" align="center" type="index" width="50" />
            <el-table-column label="流程名称" align="center" prop="processName" />
            <el-table-column label="流程状态" align="center" prop="processState">
                <template #default="scope">
                    <el-switch v-model="scope.row.processState" active-value="1" inactive-value="0"
                        @change="handleProcessStateChange(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="processCreationTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.processCreationTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建人" align="center" prop="processCreationUser">
                <template #default="scope">
                    <TextTag :options="userList" column="userId" label="nickName" :value="scope.row.processCreationUser"
                        text />
                </template>
            </el-table-column>
            <el-table-column label="修改时间" align="center" prop="processUpdateTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.processUpdateTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="修改人" align="center" prop="processUpdateUser">
                <template #default="scope">
                    <TextTag :options="userList" column="userId" label="nickName" :value="scope.row.processUpdateUser"
                        text />
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
                <template #default="scope">
                    <!-- <el-button text type="primary" icon="View" @click="handleView(scope.row)"
                        v-hasPermi="['wfProcess:wfProcess:query']">详细
                    </el-button> -->
                    <el-button text type="success" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['wfProcess:wfProcess:edit']">修改
                    </el-button>
                    <el-button text type="danger" icon="Delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['wfProcess:wfProcess:remove']">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改流程对话框 -->
        <el-dialog :title="title" v-model="open" width="800px" append-to-body>
            <!-- {{ form }} -->
            <el-form ref="wfProcessRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="流程名称" prop="processName">
                    <el-input v-model="form.processName" placeholder="请输入流程名称" />
                </el-form-item>
                <!-- <el-form-item label="创建时间" prop="processCreationTime">
                    <el-date-picker clearable v-model="form.processCreationTime" type="date" value-format="YYYY-MM-DD"
                        placeholder="请选择创建时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="创建人" prop="processCreationUser">
                    <el-input v-model="form.processCreationUser" placeholder="请输入创建人" />
                </el-form-item>
                <el-form-item label="修改时间" prop="processUpdateTime">
                    <el-date-picker clearable v-model="form.processUpdateTime" type="date" value-format="YYYY-MM-DD"
                        placeholder="请选择修改时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="修改时间" prop="processUpdateUser">
                    <el-input v-model="form.processUpdateUser" placeholder="请输入修改时间" />
                </el-form-item> -->

                <el-form-item label="流程状态" prop="processState">
                    <el-select v-model="form.processState" placeholder="请选择流程状态">
                        <el-option v-for="item in com_process_state" :key="item.value" :label="item.label"
                            :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-for="(item, i ) in form.links" :label="'流程环节' + (i + 1)" prop="null">
                    <el-card shadow="hover">
                        <!-- {{ com_link_type }} -->
                        <el-input v-model="item.linkName" class="margin-bottom" placeholder="请选择环节名称">
                        </el-input>

                        <el-select v-model="item.linkType" @change="item._ids = []" placeholder="请选择环节类型">
                            <el-option v-for="item in com_link_type" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                        <div class="margin-bottom"></div>
                        <el-select v-if="item.linkType == 1" v-model="item._ids" multiple placeholder="请选择用户">
                            <el-option v-for="item in userList" :key="item.userId"
                                :label="`${item.nickName} (${item.userName})`" :value="item.userId">
                            </el-option>
                        </el-select>
                        <el-select v-else-if="item.linkType == 2" v-model="item._ids" multiple placeholder="请选择角色">
                            <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName"
                                :value="item.roleId">
                            </el-option>
                        </el-select>
                        <el-select v-else-if="item.linkType == 4" v-model="item._ids" multiple placeholder="请选择岗位">
                            <el-option v-for="item in postList" :key="item.postId" :label="item.postName"
                                :value="item.postId">
                            </el-option>
                        </el-select>
                        <div class="margin-bottom"></div>
                        <el-select v-model="item.isZybp" placeholder="是否只阅">
                            <el-option label=" " value=" " />
                            <el-option label="阅批" value="0" />
                            <el-option label="只阅" value="1" />
                        </el-select>
                    </el-card>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Plus" circle @click="handleAddLink()"></el-button>
                    <el-button :icon="Minus" circle v-show="form.links.length > 1" @click="handleRemoveLink()">
                    </el-button>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="WfProcess">
import { listWfProcess, getWfProcess, delWfProcess, addWfProcess, updateWfProcess } from "@/api/wfProcess/wfProcess";
import { listUser } from "@/api/system/user";
import { listRole } from "@/api/system/role";
import { listPost } from "@/api/system/post";

import {
    Plus,
    Minus,
} from '@element-plus/icons-vue'


const { proxy } = getCurrentInstance();
const { com_process_state, com_link_type } = proxy.useDict('com_process_state', 'com_link_type');
const wfProcessList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const userList = ref([]);
const roleList = ref([]);
const postList = ref([]);
const linksTail = ref({});


const data = reactive({
    form: {
    },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        processName: null,
        processState: null,
        processCreationTime: null,
        processCreationUser: null,
        processUpdateTime: null,
        processUpdateUser: null
    },
    rules: {
        processName: [
            {
                required: true, message: "流程名称不能为空", trigger: "blur"
            }
        ],
        processState: [
            {
                required: true, message: "流程状态不能为空", trigger: "change"
            }
        ],
        linkName: [
            {
                required: true, message: "环节名称不能为空", trigger: "change"
            }
        ]
    }
});

const { queryParams, form, rules } = toRefs(data);
const baseUrl = import.meta.env.VITE_APP_BASE_API;

/** 查询流程列表 */
function getList() {
    loading.value = true;
    listWfProcess(queryParams.value).then(response => {
        wfProcessList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

function addList() {
    loading.value = true;
    listWfProcess(queryParams.value)
        .then(response => {
            wfProcessList.value.push(...response.rows);
            total.value = response.total;
            if (wfProcessList.value.length >= total.value) finished.value = true;
            loading.value = false;
        })
        .catch(response => {
            loading.value = false;
        });
}

// 下拉刷新
function handlePullDownRefresh() {
    queryParams.value.pageNum = 1;
    wfProcessList.value = [];
    addList();
}

// 滚动到底部的事件
function handleReachBottom() {
    queryParams.value.pageNum++;
    addList();
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        processId: null,
        processName: null,
        processState: "1",
        processCreationTime: null,
        processCreationUser: null,
        processUpdateTime: null,
        processUpdateUser: null,
        links: [{
            linkName: '',
            linkType: "1",
            ids: "",
            isZybp: " "
        }]
    };
    proxy.resetForm("wfProcessRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.processId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加流程";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    let _form;
    const processId =
        row.processId || ids.value
    getWfProcess(processId).then(response => {
        _form = JSON.parse(JSON.stringify(response.data));
        linksTail.value = _form.links.splice(_form.links.length - 1, 1)
        for (let i = 0; i < _form.links.length; i++) {
            //// console.log(typeof(_form.links[i].ids))
            if (typeof (_form.links[i].ids) == "string") {
                //// console.log(_form.links[i].ids.split(","))
                _form.links[i]._ids = _form.links[i].ids.split(",")
                // _form.links[i]._ids = _form.links[i]._ids.slice(0, _form.links[i]._ids.length - 1)
                for (let j = 0; j < _form.links[i]._ids.length; j++) {
                    _form.links[i]._ids[j] = parseInt(_form.links[i]._ids[j])
                }
            }
        }
        form.value = JSON.parse(JSON.stringify(_form));
        open.value = true;
        title.value = "修改流程";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["wfProcessRef"].validate(valid => {
        if (valid) {

            let hasEmpty = false
            for (let i = 0; i < form.value.links.length; i++) {
                form.value.links[i].ids = form.value.links[i]._ids.join(",")
                form.value.links[i].linkName = form.value.links[i].linkName.trim()
                if (((!form.value.links[i].ids.length) && form.value.links[i].linkType != 3) || (!form.value.links[i]
                    .linkName.length)) {
                    hasEmpty = true
                }
            }
            if (hasEmpty) {
                proxy.$modal.msgError("表单内容不能有空")
                return
            }
            if (form.value.processId != null) {
                form.value.links.push(...linksTail.value)
                updateWfProcess(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                form.value.links.push({
                    linkName: "结束"
                })
                addWfProcess(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const processIds = row.processId || ids.value;

    // proxy.$modal.confirm('是否确认删除流程编号为"' + processIds + '"的数据项？').then(function () {
    proxy.$modal.confirm('是否确认删除？').then(function () {
        return delWfProcess(processIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
    downloadWfProcess(queryParams.value)
    // proxy.download('wfProcess/wfProcess/export', {
    //   ...queryParams.value
    // }, `wfProcess_${new Date().getTime()}.xlsx`)
}

/** 详细按钮操作 */
function handleView(row) {
}

function handleAddLink() {
    form.value.links.push({
        linkName: '',
        linkType: "1",
        ids: "",
        isZybp: " "
    })
}

function handleRemoveLink() {
    form.value.links.pop()
}

function handleProcessStateChange(row) {
   // console.log(row)
    let text = row.processState === "0" ? "停用" : "启用";
    proxy.$modal.confirm('确认要"' + text + '"流程"' + row.processName + '"?').then(function () {

        getWfProcess(row.processId).then(response => {
            let _form = JSON.parse(JSON.stringify(response.data));
            response.data.processState = row.processState;
           // console.log(response.data)

            return updateWfProcess(response.data);
        });

        let data = JSON.parse(JSON.stringify(row))
    }).then(() => {
        proxy.$modal.msgSuccess(text + "成功");
    }).catch(function () {
        row.processState = row.processState === "0" ? "1" : "0";
    });
}


listUser(proxy.addDateRange({
    pageNum: 1,
    pageSize: 9999,
}, undefined)).then(res => {
    userList.value = res.rows;
});
listRole(proxy.addDateRange({
    pageNum: 1,
    pageSize: 9999,
}, undefined)).then(response => {
    roleList.value = response.rows;
});
listPost({
    pageNum: 1,
    pageSize: 9999,
}).then(response => {
    postList.value = response.rows;
});
getList();

</script>

