<template>
    <div class="hc-layout-box">
        <HcCard :scrollbar="false" action-size="lg">
            <template #header>
                <HcTooltip keys="tasks_flow_add">
                    <el-button hc-btn type="primary" @click="addFlowData">
                        <HcIcon name="add-circle" />
                        <span>新建流程</span>
                    </el-button>
                </HcTooltip>
            </template>
            <template #extra>
                <el-alert
                    :closable="false"
                    title="同一合同段内，只需要设置重复岗位的流程即可，其他任务岗位，系统将自动推送，无需创建更多任务流" type="error"
                />
            </template>
            <HcTable :column="tableListColumn" :datas="tableListData" :loading="tableLoading" border>
                <template #action="{ row }">
                    <HcTooltip keys="tasks_flow_edit">
                        <el-button plain size="small" type="primary" @click="handleTableEdit(row)">编辑</el-button>
                    </HcTooltip>
                    <HcTooltip keys="tasks_flow_del">
                        <el-button plain size="small" type="danger" @click="handleTableDel(row)">删除</el-button>
                    </HcTooltip>
                </template>
            </HcTable>
            <template #action>
                <HcPages :pages="searchForm" @change="pageChange" />
            </template>
        </HcCard>
        <!-- 新增/编辑流程 弹框 -->
        <el-dialog
            v-model="showEditModal" :title="`${flowFormData.id ? '编辑' : '新增'}流程`" class="hc-modal-border"
            width="47rem"
        >
            <el-form ref="formFlowRef" :model="flowFormData" :rules="formFlowRules" label-width="auto" size="large">
                <el-form-item label="流程名称" prop="fixedFlowName">
                    <el-input v-model="flowFormData.fixedFlowName" placeholder="请输入流程名称" />
                </el-form-item>
                <el-form-item label="任务人" prop="linkUserJoinString">
                    <HcTasksUser
                        :contract-id="contractId" :project-id="projectId" :users="flowFormData.linkUserJoinString"
                        ui="w-full" @change="tasksUserChange"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="showEditModal = false">取消</el-button>
                    <el-button :loading="sevaLoading" hc-btn type="primary" @click="saveFormClick">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useAppStore } from '~src/store'
import { getArrValue, getObjValue } from 'js-fast-way'
import tasksFlowApi from '~api/tasks/flow'
import { delMessageV2 } from '~com/message/index.js'
//变量
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)

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

//搜索表单
const searchForm = ref({ current: 1, size: 20, total: 0 })

//分页被点击
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//获取数据
const tableLoading = ref(false)
const tableListData = ref([])

const tableListColumn = ref([
    { key: 'fixedFlowName', name: '流程名称' },
    { key: 'linkUserJoinString', name: '流程详情' },
    { key: 'action', name: '操作', width: '200', align: 'center' },
])

const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await tasksFlowApi.getPageData({
        projectId: projectId.value,
        contractId: contractId.value,
        ...searchForm.value,
    })
    //处理数据
    tableLoading.value = false
    if (!error && code === 200) {
        tableListData.value = getArrValue(data['records'])
        searchForm.value.total = data.total || 0
    } else {
        tableListData.value = []
        searchForm.value.total = 0
    }
}

//新增编辑数据
const showEditModal = ref(false)
const formFlowRef = ref(null)
const flowFormData = ref({ id: '', fixedFlowName: '', linkUserJoinString: '' })
const formFlowRules = {
    fixedFlowName: {
        required: true,
        trigger: 'blur',
        message: '请输入流程名称',
    },
    linkUserJoinString: {
        required: true,
        trigger: 'blur',
        message: '请选择任务人',
    },
}

//任务人选择改变
const tasksUserChange = (a, b, users) => {
    flowFormData.value.linkUserJoinString = users
}

//新建流程
const addFlowData = () => {
    flowFormData.value = { id: '', fixedFlowName: '', linkUserJoinString: '' }
    showEditModal.value = true
}

//编辑流程
const handleTableEdit = async (row) => {
    flowFormData.value = { id: '', fixedFlowName: '', linkUserJoinString: '' }
    showEditModal.value = true
    const { error, code, data } = await tasksFlowApi.queryFixedFlowDetail({
        id: row?.id,
    })
    if (!error && code === 200) {
        let users = '', res = getObjValue(data)
        const list = getArrValue(res['fixedFlowLinkList'])
        for (let i = 0; i < list.length; i++) {
            const item = getObjValue(list[i])
            if (users) {
                users += `,${item['fixedFlowLinkUserName']}-${item['fixedFlowLinkUser']}`
            } else {
                users = `${item['fixedFlowLinkUserName']}-${item['fixedFlowLinkUser']}`
            }
        }
        flowFormData.value = { id: res.id, fixedFlowName: res.fixedFlowName, linkUserJoinString: users }
    } else {
        flowFormData.value = { id: '', fixedFlowName: '', linkUserJoinString: '' }
    }
}

//提交保存
const sevaLoading = ref(false)
const saveFormClick = async () => {
    const form = flowFormData.value
    if (!form.id) {
        sevaLoading.value = true
        const { error, code } = await tasksFlowApi.addFixedFlowData({
            ...form,
            projectId: projectId.value,
            contractId: contractId.value,
        })
        //处理数据
        sevaLoading.value = false
        if (!error && code === 200) {
            showEditModal.value = false
            window?.$message?.success('保存成功')
            getTableData()
        }
    } else {
        sevaLoading.value = true
        const { error, code } = await tasksFlowApi.updateFixedFlowData({
            ...form,
            projectId: projectId.value,
            contractId: contractId.value,
        })
        //处理数据
        sevaLoading.value = false
        if (!error && code === 200) {
            showEditModal.value = false
            window?.$message?.success('保存成功')
            getTableData()
        }
    }
}

//删除
const handleTableDel = (row) => {
    delMessageV2(async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                removeFixedFlowData(row)
                instance.confirmButtonLoading = false
                done()
            } else {
                done()
            }
    })
}

//确认删除
const removeFixedFlowData = async (row) => {
    const { error, code } = await tasksFlowApi.removeFixedFlowData({
        ids: row?.id || '',
        projectId: projectId.value,
        contractId: contractId.value,
    })
    //处理数据
    if (!error && code === 200) {
        window.$message?.success('删除成功')
        getTableData()
    }
}
</script>

<style lang="scss" scoped>
.hc-layout-box {
    position: relative;
    height: 100%;
}
</style>

