<template>
    <hc-new-dialog v-model="isShow" is-table widths="96%" title="任务审核" @close="cancelClick">
        <template #header="{ titleId, titleClass }">
            <div class="hc-card-header flex items-center">
                <div :id="titleId" :class="titleClass">任务审核 【已开启电签】</div>
            </div>
        </template>
        <div v-loading="isLoading" class="relative h-full">
            <div class="hc-task-name relative">{{ rowInfo.taskName }} 审批信息</div>
            <div class="hc-task-body relative flex">
                <div class="hc-task-time">
                    <hc-body class="hc-task-body-card" padding="10px" scrollbar>
                        <el-timeline class="hc-time-line">
                            <template v-for="(item, index) in flowList" :key="index">
                                <el-timeline-item :class="item.status === '2' ? 'success' : 'primary'" size="large">
                                    <div class="timeline-item-icon">
                                        <hc-icon v-if="item.status === '2'" class="check-icon" name="check" />
                                    </div>
                                    <div class="reply-name">{{ item.name }}</div>
                                    <div class="reply-time">{{ item.date }}</div>
                                    <div class="reply-content" v-html="item.flowValue" />
                                </el-timeline-item>
                            </template>
                        </el-timeline>
                    </hc-body>
                </div>
                <div :id="`hc_task_table_${uuid}`" class="hc-task-table">
                    <hc-body class="hc-task-body-card" padding="10px">
                        <hc-table
                            ref="tableRef" :column="tableColumn" :datas="tableData" :is-stripe="false"
                            is-new :index-style="{ width: 60 }" is-current-row @row-click="tableRowClick"
                        >
                            <template #action="{ row }">
                                <div class="hc-task-table-action" :class="row.isComment === 1 ? 'is-cur' : ''" @click="rowRemarkClick(row)">
                                    <i class="i-iconoir-star-solid" />
                                </div>
                            </template>
                            <template #state="{ row }">
                                <div class="hc-task-table-state">
                                    <i v-if="row.status === 1" class="i-iconoir-check-circle-solid is-success" />
                                    <i v-else-if="row.status === 2" class="i-iconoir-xmark-circle-solid is-danger" />
                                    <span v-else-if="row.status === 3">审批结束</span>
                                    <i v-else class="i-iconoir-help-circle-solid" />
                                </div>
                            </template>
                        </hc-table>
                    </hc-body>
                </div>
                <div :id="`hc_task_form_${uuid}`" class="hc-task-form">
                    <hc-body class="hc-task-body-card" padding="10px" scrollbar>
                        <HcTaskForm :table="tableInfo" :info="rowInfo" :is-edit="tabsKey === 1" @finish="taskFormFinish" />
                    </hc-body>
                </div>
            </div>
        </div>
        <template #footer>
            <div class="hc-task-dialog-footer">
                <el-button :disabled="tabsKey !== 1" @click="rejectionClick">驳回审批</el-button>
                <el-button type="primary" :loading="confirmLoading" :disabled="tabsKey !== 1" @click="confirmClick">同意审批</el-button>
            </div>
        </template>
    </hc-new-dialog>
    <!-- 批注 -->
    <HcTaskNotes v-model="isNotesShow" :table="tableNoteInfo" :info="rowInfo" :is-edit="tabsKey === 1" @finish="taskNotesFinish" />
    <!-- 驳回 -->
    <HcRepealForm v-model="isRepealShow" :info="rowInfo" @finish="taskRepealFinish" />
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { getArrValue, getObjValue, getRandom } from 'js-fast-way'
import { useAppStore } from '~src/store'
import HcTaskForm from './task-form.vue'
import HcTaskNotes from './task-notes.vue'
import HcRepealForm from './repeal-form.vue'
import mainApi from '~api/tasks/hc-data'

const props = defineProps({
    tabs: {
        type: [String, Number],
        default: '',
    },
    row: {
        type: Object,
        default: () => ({}),
    },
})

//事件
const emit = defineEmits(['finish', 'close'])
const uuid = getRandom(4)

const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId || '')
const contractId = ref(useAppState.getContractId || '')

//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})

//监听
const tableRef = ref(null)
const tabsKey = ref(Number(props.tabs))
const rowInfo = ref(props.row)

watch(() => [
    props.tabs,
    props.row,
], ([key, row]) => {
    tabsKey.value = Number(key)
    rowInfo.value = row
}, {
    immediate: true,
    deep: true,
})

//监听显示
watch(isShow, (val) => {
    if (val) {
        setTaskInfo()
        setSplitRef()
    }
})

//初始化设置拖动分割线
const setSplitRef = () => {
    //配置参考： https://split.js.org/#/?direction=vertical&snapOffset=0
    nextTick(() => {
        window.$split(['#hc_task_table_' + uuid, '#hc_task_form_' + uuid], {
            sizes: [50, 50],
            snapOffset: 0,
            minSize: [50, 500],
        })
    })
}

//设置任务信息
const setTaskInfo = () => {
    //meterType：1中间，2材料，3开工，4变更令
    const { meterType } = rowInfo.value
    if (meterType === 1) {
        tableColumn.value = middlepayTableColumn.value
    } else if (meterType === 2) {
        tableColumn.value = materialTableColumn.value
    } else if (meterType === 3) {
        tableColumn.value = startWorkTableColumn.value
    } else if (meterType === 4) {
        tableColumn.value = alterTableColumn.value
    } else {
        tableColumn.value = []
    }
    getTableDetail()
}

//获取数据详情
const isLoading = ref(false)
const getTableDetail = async () => {
    isLoading.value = true
    confirmLoading.value = true
    //获取数据
    const { data } = await mainApi.getDetail(rowInfo.value.id)
    const { taskProcessInfo, taskCenterDataInfo } = getObjValue(data)
    tableData.value = getArrValue(taskCenterDataInfo)
    flowList.value = getArrValue(taskProcessInfo)
    //默认选中第一行
    let info = {}
    if (tableData.value.length > 0) {
        info = tableData.value[0]
    }
    await nextTick(() => {
        tableInfo.value = info
        tableRef.value?.tableRef?.setCurrentRow(info)
    })
    //关闭加载状态
    isLoading.value = false
    confirmLoading.value = false
}

//流程信息，1待审批，2已审批
const flowList = ref([])

//中间计量单的表格数据
const middlepayTableColumn = ref([
    { key: 'action', name: '批注', width: 45, align: 'center' },
    { key: 'meterNumber', name: '计量单编号' },
    { key: 'meterMoney', name: '计量金额', width: 100 },
    { key: 'engineerDivide', name: '工程划分' },
    { key: 'state', name: '审批状态', fixed: 'right', width: 70, align: 'center' },
])
//开工预付款计量单的表格数据
const startWorkTableColumn = ref([
    { key: 'action', name: '批注', width: 45, align: 'center' },
    { key: 'periodName', name: '计量期', minWidth: 100, align: 'center' },
    { key: 'businessDate', name: '业务日期', width: 160, align: 'center' },
    { key: 'meterMoney', name: '计量金额', width: 100, align: 'center' },
    { key: 'state', name: '审批状态', fixed: 'right', width: 70, align: 'center' },
])
//变更令的表格数据
const alterTableColumn = ref([
    { key: 'action', name: '批注', width: 45, align: 'center' },
    { key: 'changeNumber', name: '变更编号', minWidth: 120, align: 'center' },
    { key: 'changeName', name: '变更名称', minWidth: 120, align: 'center' },
    { key: 'changeMoney', name: '变更金额', width: 100, align: 'center' },
    { key: 'changeApprovalDate', name: '变更批复日期', width: 160, align: 'center' },
    { key: 'state', name: '审批状态', fixed: 'right', width: 70, align: 'center' },
])
//材料计量单的表格数据
const materialTableColumn = ref([
    { key: 'action', name: '批注', width: 45, align: 'center' },
    { key: 'periodName', name: '计量期', minWidth: 100, align: 'center' },
    { key: 'contractMaterialName', name: '合同材料', minWidth: 120, align: 'center' },
    { key: 'materialArriveNumber', name: '材料到场编号', width: 120, align: 'center' },
    { key: 'meterMoney', name: '计量金额', width: 100, align: 'center' },
    { key: 'state', name: '审批状态', fixed: 'right', width: 70, align: 'center' },
])

//表格数据
const tableColumn = ref([])
const tableData = ref([])

//表格行被点击
const tableInfo = ref({})
const tableRowClick = ({ row }) => {
    tableInfo.value = row
}

//批注, isComment 是否已批注，1=是，0=否
const isNotesShow = ref(false)
const tableNoteInfo = ref({})
const rowRemarkClick = (row) => {
    tableNoteInfo.value = row
    nextTick(() => {
        isNotesShow.value = true
    })
}

//批注完成
const taskNotesFinish = () => {
    getTableDetail()
}

//单条审批
const taskFormFinish = () => {
    getTableDetail()
}

//确认审批
const confirmLoading = ref(false)
const confirmClick = async () => {
    confirmLoading.value = true
    const { error, code, msg } = await mainApi.taskApprove({
        taskId: rowInfo.value.id,
        projectId: projectId.value,
        contractId: contractId.value,
    })
    confirmLoading.value = false
    if (!error && code === 200) {
        window.$message.success('审批成功')
        emit('finish')
        cancelClick()
    } else {
        window.$message.error(msg ?? '审批失败')
    }
}

//驳回审批
const isRepealShow = ref(false)
const rejectionClick = async () => {
    isRepealShow.value = true
}

//驳回完成
const taskRepealFinish = () => {
    emit('finish')
    cancelClick()
}

//取消审批
const cancelClick = () => {
    isShow.value = false
    isLoading.value = false
    confirmLoading.value = false
    tableColumn.value = []
    tableData.value = []
    tableInfo.value = {}
    emit('close')
}
</script>

<style lang="scss" scoped>
.hc-task-name {
    font-weight: bold;
    color: #1A1a1a;
    padding-bottom: 10px;
    border-bottom: 1px solid #f5f5f5;
}
.hc-task-body {
    height: calc(100% - 27px);
    .hc-task-time {
        position: relative;
        height: 100%;
        flex-shrink: 0;
        width: 170px;
    }
    .hc-task-table, .hc-task-form {
        position: relative;
        height: 100%;
        flex: 1;
        flex-basis: auto;
    }
    .hc-task-table {
        border-left: 1px solid #e5e5e5;
    }
}


//表格图标
.hc-task-table-action, .hc-task-table-state {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    font-size: 20px;
    color: #929293;
    i {
        display: inline-flex;
    }
}

//表格批注
.hc-task-table-action.is-cur {
    color: #F2B90B;
}

//表格状态
.hc-task-table-state {
    .is-success {
        color: #25a62d;
    }
    .is-danger {
        color: #F5221D;
    }
    span {
        color: #1A1a1a;
    }
}

//弹窗底部
.hc-task-dialog-footer {
    position: relative;
    text-align: center;
}
</style>

<style lang="scss">
.hc-task-body-card {
    background: #f7f7f7;
    .el-scrollbar__bar.is-vertical {
        right: -8px;
    }
}
</style>
