<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="fixedName">
                    <el-input v-model="flowFormData.fixedName" placeholder="请输入流程名称" />
                </el-form-item>
                <el-form-item label="任务名称" prop="fixedBranchList">
                    <hc-tasks-user :id="changeId" :contract-id="contractId" :project-id="projectId" :users="linkUserJoinString" ui="w-full" :is-show-task-name="true" :fixed-branch-list="flowFormData.fixedBranchList" @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: 20, 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: '', fixedName: '', fixedBranchList: [] }
    linkUserJoinString.value = ''
    showEditModal.value = true
}


//编辑流程
const linkUserJoinString = ref(null)
const changeId = ref('')
const handleTableEdit = async (row) => {
    changeId.value = row.id
    flowFormData.value = { id: '', fixedName: '', fixedBranchList: [] }
    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['fixedBranchVOList'])
      
            const item = getObjValue(list[0])['userList']
            for (let index = 0; index < item.length; index++) {
                const element = item[index]
                 if (users) {
                users += `,${element['userName']}-${element['userId']}`
                    } else {
                        users = `${element['userName']}-${element['userId']}`
                    }
            
      
            console.log(users, 'users')
        }
        flowFormData.value = { id: res.fixedFlowId, fixedName: res.fixedFlowName, fixedBranchList:res.fixedBranchVOList }
        linkUserJoinString.value = users
    } else {
        flowFormData.value = { id: '', fixedName: '', fixedBranchList: [] }
    }
}

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

//任务人选择改变
const tasksUserChange = ( fixedBranchList) => {
    flowFormData.value.fixedBranchList = fixedBranchList
}

//提交保存
const sevaLoading = ref(false)
const saveFormClick = async () => {
    const form = flowFormData.value
    console.log(form, 'form')
    const fixedBranchList = form.fixedBranchList
    fixedBranchList.forEach((ele)=>{
        delete ele.users
    })
    form.fixedBranchList = fixedBranchList
    if (!form.id) {
        sevaLoading.value = true
        const { error, code } = await tasksFlowApi.saveFixedFlow({
            ...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
        form.fixedFlowId = form.id
        delete form.id
        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({
            id:row?.id || '',
            name: row?.fixedFlowName,
          
        })
        //处理数据
        if (!error && code === 200) {
            window.$message?.success('删除成功')
            getTableData().then()
        }
    })
}
</script>
