<template>
    <hc-new-card>
        <template #header>
            <el-button hc-btn type="primary" @click="addFlowData">
                <HcIcon name="add" />
                <span>新建流程</span>
            </el-button>
            <el-button hc-btn type="warning" @click="tableSortClick">排序</el-button>
        </template>
        <template #extra>
            <el-alert
                :closable="false"
                title="同一合同段内，只需要设置重复岗位的流程即可，其他任务岗位，系统将自动推送，无需创建更多任务流"
                type="error"
            />
        </template>
        <hc-table :column="tableColumn" :datas="tableData" :loading="tableLoading" :index-style="{ width: 60 }" is-new>
            <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 :data="flowFormData.fixedBranchList" :datas="fixedData" ui="w-full" @change="flowFormChange" />
                </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 ml-2 text-xl" @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>
    </hc-new-card>
</template>

<script setup>
import { nextTick, onActivated, ref } from 'vue'
import { useAppStore } from '~src/store'
import { deepClone, formValidate, 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
    getTableData()
}

//表格数据
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 fixedData = ref({})
const addFlowData = () => {
    flowFormData.value = { id: '', fixedName: '', fixedBranchList: [] }
    fixedData.value = {
        projectId: projectId.value,
        contractId: contractId.value,
    }
    showEditModal.value = true
}

//编辑流程
const changeId = ref('')
const handleTableEdit = async (row) => {
    changeId.value = row.id
    fixedData.value = {
        id: row.id,
        projectId: projectId.value,
        contractId: contractId.value,
    }
    showEditModal.value = true
    getFlowDetail().then()
}

const getFlowDetail = async () => {
    const { error, code, data } = await tasksFlowApi.queryFixedFlowDetail({
        id: changeId.value,
    })
    if (!error && code === 200) {
        const { fixedFlowName, fixedBranchVOList } = getObjValue(data)
        flowFormData.value = {
            id: changeId.value,
            fixedName: fixedFlowName,
            fixedBranchList: fixedBranchVOList,
        }
    } 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 flowFormChange = (data) => {
    flowFormData.value.fixedBranchList = getArrValue(data)
}

//提交保存
const sevaLoading = ref(false)
const saveFormClick = async () => {
    const isValidate = await formValidate(formFlowRef.value)
    if (!isValidate) return false
    const form = deepClone(flowFormData.value)
    const fixedBranchList = form.fixedBranchList
    fixedBranchList.forEach((ele) => {
        delete ele.users
    })
    form.fixedBranchList = fixedBranchList
    if (!form.id && !form.fixedFlowId) {
        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 = changeId.value
        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()
        }
    })
}


//表格排序
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()
    }
}

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