<template>
    <div class="hc-layout-box">
        <hc-new-card :scrollbar="false" action-size="lg">
            <template #header>
                <hc-tooltip keys="tasks_flow_add">
                    <el-button hc-btn type="primary" @click="addFlowData">
                        <hc-icon name="add-circle" />
                        <span>新建流程</span>
                    </el-button>
                </hc-tooltip>
                <el-button hc-btn type="warning" @click="tableSortClick">排序</el-button>
            </template>
            <template #extra>
                <el-alert :closable="false" title="同一合同段内，只需要设置重复岗位的流程即可，其他任务岗位，系统将自动推送，无需创建更多任务流" type="error" />
            </template>
            <hc-table :column="tableListColumn" :datas="tableListData" :loading="tableLoading" is-new :index-style="{ width: 60 }">
                <template #action="{ row }">
                    <hc-tooltip keys="tasks_flow_edit">
                        <el-button plain size="small" type="primary" @click="handleTableEdit(row)">编辑</el-button>
                    </hc-tooltip>
                    <hc-tooltip keys="tasks_flow_del">
                        <el-button v-del-com:[handleTableDel]="row" plain size="small" type="danger">删除</el-button>
                    </hc-tooltip>
                </template>
            </hc-table>
            <template #action>
                <hc-pages :pages="searchForm" @change="pageChange" />
            </template>
        </hc-new-card>
        <!-- 新增/编辑流程 弹框 -->
        <hc-new-dialog v-model="showEditModal" :title="`${flowFormData.id ? '编辑' : '新增'}流程`" widths="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">
                    <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-dialog v-model="sortModal" title="调整排序" widths="80vw" is-table is-footer-center @close="sortModalClose">
            <el-alert title="可拖动排序，也可在后面点击图标，切换排序" type="error" :closable="false" />
            <div class="hc-table-h">
                <hc-table
                    ui="hc-table-row-drop" :column="sortTableColumn" :datas="sortTableData" :loading="sortTableLoading"
                    is-row-drop quick-sort is-new :index-style="{ width: 80 }" @row-drop="sortTableRowDrop" @row-sort="sortTableRowDrop"
                >
                    <template #key2="{ row }">
                        <span class="text-link">{{ row?.key2 }}</span>
                    </template>
                    <template #action="{ index }">
                        <span class="text-link text-xl" @click="upSortClick(index)">
                            <hc-icon name="arrow-up" fill />
                        </span>
                        <span class="text-link text-xl ml-2" @click="downSortClick(index)">
                            <hc-icon name="arrow-down" fill />
                        </span>
                    </template>
                </hc-table>
            </div>
            <template #footer>
                <el-button hc-btn @click="sortModalClose">
                    <hc-icon name="close" />
                    <span>取消</span>
                </el-button>
                <el-button type="primary" hc-btn :loading="sortModalLoading" @click="sortModalSave">
                    <hc-icon name="check" />
                    <span>确认</span>
                </el-button>
            </template>
        </hc-new-dialog>
    </div>
</template>

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

//变量
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, msg } = 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 {
            window.$message.error(msg)
        }
    } else {
        sevaLoading.value = true
        const { error, code, msg } = 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()
        } else {
            window.$message.error(msg)
        }
    }
}

//删除
const handleTableDel = async ({ item }, resolve) => {
    await removeFixedFlowData(item)
    resolve()
}

//确认删除
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().then()
    }
}

//表格排序
const sortModal = ref(false)
//显示
const tableSortClick = () => {
    sortModal.value = true
    getSortTableData()
}

//表格数据
const sortTableColumn = ref([
    { key: 'fixedFlowName', name: '流程名称' },
    { key: 'linkUserJoinString', name: '流程详情' },
    { key:'action', name: '排序', width: 90, align: 'center' },
])
const sortTableData = ref([])

//获取数据
const sortTableLoading = ref(false)
const getSortTableData = async () => {
    sortTableLoading.value = true
    const { error, code, data } = await tasksFlowApi.getPageData({
        projectId: projectId.value,
        contractId: contractId.value,
        current: 1,
        size: 9999,
    })
    //处理数据
    sortTableLoading.value = false
    if (!error && code === 200) {
        sortTableData.value = getArrValue(data['records'])
    } else {
        sortTableData.value = []
    }
}

//拖动完成
const sortTableRowDrop = (rows) => {
    sortTableData.value = [] // 先清空，否则排序会异常
    nextTick(() => {
        sortTableData.value = rows
    })
}

//向下
const downSortClick = (index) => {
    const indexs = index + 1
    const data = sortTableData.value
    if (indexs !== data.length) {
        const tmp = data.splice(indexs, 1)
        sortTableData.value.splice(index, 0, tmp[0])
    } else {
        window?.$message?.warning('已经处于置底，无法下移')
    }
}

//向上
const upSortClick = (index) => {
    const data = sortTableData.value || []
    if (index !== 0) {
        const tmp = data.splice(index - 1, 1)
        sortTableData.value.splice(index, 0, tmp[0])
    } else {
        window?.$message?.warning('已经处于置顶，无法上移')
    }
}

//保存
const sortModalLoading = ref(false)
const sortModalSave = async () => {
    sortModalLoading.value = true
    const { error, code } = await tasksFlowApi.batchUpdateSort(sortTableData.value)
    //判断状态
    sortModalLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('保存成功')
        sortModal.value = false
        getTableData().then()
    } else {
        window.$message?.error('保存失败')
    }
}

//关闭
const sortModalClose = () => {
    sortModal.value = false
}
</script>

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

