<template>
    <hc-new-card>
        <template #header>
            <el-button hc-btn type="primary" @click="addFlowData">新建流程</el-button>
        </template>
        <template #extra>
            <el-alert :closable="false" title="同一合同段内，只需要设置重复岗位的流程即可，其他任务岗位，系统将自动推送，无需创建更多任务流" type="error" />
        </template>
        <hc-table :column="tableColumn" :datas="tableData" :loading="tableLoading" is-new :index-style="{ width: 60 }">
            <template #action="{ row }">
                <el-link type="success" @click="handleTableEdit(row)">修改</el-link>
                <el-link type="danger" @click="handleTableDel(row)">删除</el-link>
            </template>
        </hc-table>
        <template #action>
            <hc-pages :pages="searchForm" @change="pageChange" />
        </template>
        <!-- 新增/编辑流程 弹框 -->
        <hc-new-dialog v-model="showEditModal" :title="`${flowFormData.id ? '编辑' : '新增'}流程`" widths="40rem">
            <el-form ref="formFlowRef" class="p-4" :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">
                    <hc-tasks-user :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>
        </hc-new-dialog>
    </hc-new-card>
</template>

<script setup>
import { onActivated, onMounted, ref } from 'vue'
import { useAppStore } from '~src/store'
import { getArrValue, getObjValue } from 'js-fast-way'
import tasksFlowApi from '~api/tasks/flow'
import { delMessage } from '~uti/tools'

//变量
const store = useAppStore()
const projectId = ref(store.getProjectId)
const contractId = ref(store.getContractId)

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

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

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

//表格数据
const tableLoading = ref(false)
const tableColumn = ref([
    { key: 'fixedFlowName', name: '流程名称' },
    { key: 'linkUserJoinString', name: '流程详情' },
    { key: 'action', name: '操作', width: 94 },
])
const tableData = ref([])

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) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data.total || 0
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}

//新建流程
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 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 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().then()
        }
    } 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().then()
        }
    }
}

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