<template>
    <HcNewCard>
        <template #header>
            <div class="w-32">
                <el-select v-model="searchForm.typeValue" block clearable placeholder="任务类型">
                    <el-option v-for="item in tasksType" :label="item.dictValue" :value="item.dictKey" />
                </el-select>
            </div>
            <div class="w-32 ml-3">
                <el-select v-model="searchForm.statusValue" block clearable placeholder="任务状态">
                    <el-option v-for="item in tasksStatus" :label="item.dictValue" :value="item.dictKey" />
                </el-select>
            </div>
            <div class="w-32 ml-3">
                <el-select v-model="searchForm.contractIdValue" block clearable placeholder="合同段" @change="ContractIdChange">
                    <el-option v-for="item in contractList" :label="item.contractName" :value="item.id" />
                </el-select>
            </div>
            <div class="w-32 ml-3">
                <el-select v-model="searchForm.batch" block clearable placeholder="上报批次">
                    <el-option v-for="item in reportBatch" :label="item.batch" :value="item.batch" />
                </el-select>
            </div>
            <div class="w-64 ml-3">
                <HcDatePicker :dates="betweenTime" clearable @change="betweenTimeUpdate" />
            </div>
            <div class="w-56 ml-3">
                <el-input v-model="searchForm.queryValue" block clearable placeholder="请输入名称关键词检索" @keyup="keyUpEvent" />
            </div>
            <div class="ml-2">
                <el-button type="primary" @click="searchClick">
                    <HcIcon name="search-2" />
                    <span>搜索</span>
                </el-button>
            </div>
        </template>
        <template #extra>
            <HcTooltip keys="tasks_data_set_sign_rules">
                <el-button hc-btn @click="setSignRulesClick">
                    <HcIcon name="settings" />
                    <span>设置重签规则</span>
                </el-button>
            </HcTooltip>
            <HcTooltip v-if="isTableKey === 'key1'" keys="tasks_data_batch_review">
                <el-button
                    :disabled="tableCheckedKeys.length <= 0" hc-btn type="primary"
                    @click="batchApprovalTaskClick"
                >
                    <HcIcon name="check-double" />
                    <span>批量审批</span>
                </el-button>
            </HcTooltip>
        </template>
        <HcTable
            ref="tableListRef" :column="tableListColumn" :datas="tableListData" :loading="tableLoading"
            is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
            @selection-change="tableSelectionChange"
        >
            <template #taskName="{ row }">
                <span class="text-link" @click="rowTaskName(row)">{{ row?.taskName }}</span>
            </template>
            <template #taskStatusName="{ row }">
                <el-tag
                    v-if="row?.taskStatusName"
                    :type="`${row.taskStatusName === '已审批' ? 'success' : row.taskStatusName === '已废除' ? 'warning' : 'info'}`" class="mx-1" effect="dark"
                >
                    {{ row.taskStatusName }}
                </el-tag>
            </template>
            <template #taskApproveUserNamesList="{ row }">
                <template v-for="item in row.taskApproveUserNamesList">
                    <el-tag
                        v-if="item.taskUserName"
                        :type="`${item.evisaStatus === 2 ? 'success' : item.evisaStatus === 3 ? 'warning' : item.evisaStatus === 999 ? 'danger' : 'info'}`" class="mx-1" effect="dark"
                    >
                        {{ item.taskUserName }}
                    </el-tag>
                </template>
            </template>
        </HcTable>
        <template #action>
            <div class="lr-dialog-footer">
                <div class="left">
                    <span class="text-success">审批人员中：</span>
                    <el-tag class="mx-1" effect="dark" type="info">未签字</el-tag>
                    <el-tag class="mx-1" effect="dark" type="success">已签字</el-tag>
                    <el-tag class="mx-1" effect="dark" type="warning">已废除</el-tag>
                    <el-tag class="mx-1" effect="dark" type="danger">签字异常</el-tag>
                </div>
                <div class="right">
                    <HcPages :pages="searchForm" :sizes="[10, 20, 30, 40, 50, 200]" @change="pageChange" />
                </div>
            </div>
        </template>
    </HcNewCard>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { getArrValue } from 'js-fast-way'
import tasksApi from '~api/tasks/data'
import { useAppStore } from '~src/store'
//参数
const props = defineProps({
    projectId: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
    contractList: {
        type: Array,
        default: () => ([]),
    },
    tableKey: {
        type: String,
        default: '',
    },
    selectContracId:{
        type: String,
        default: '',
    },
})
//事件
const emit = defineEmits(['rowTaskName', 'signRules', 'batchApproval', 'changeselectContracId'])
//初始变量
const useAppState = useAppStore()
//变量
const projectId = ref(props.projectId)
const contractId = ref(props.contractId)
const isTableKey = ref(props.tableKey)
const currentContractId = ref(useAppState.getContractId)
const selectContracId = ref(props.selectContracId)

//监听
watch(() => [
    props.tableKey, props.selectContracId,
], ([Key, Sid]) => {
    isTableKey.value = Key
    selectContracId.value = Sid
    setQueryData()
})

//渲染完成
nextTick(() => {
    setQueryData()
})

//获取相关数据
const setQueryData = () => {
    // searchForm.value.contractIdValue = contractId.value
     searchForm.value.contractIdValue = selectContracId.value
    queryTaskType()
    queryTaskStatus()
    searchClick()
    queryBatchList()
}

//获取任务类型
const tasksType = ref([])
const queryTaskType = async () => {
    const { error, code, data } = await tasksApi.queryTaskTypeStatus({
        typeOrStatus: 'task_type',
    })
    if (!error && code === 200) {
        tasksType.value = getArrValue(data)
    } else {
        tasksType.value = []
    }
}

//获取任务状态
const tasksStatus = ref([])
const queryTaskStatus = async () => {
    const { error, code, data } = await tasksApi.queryTaskTypeStatus({
        typeOrStatus: 'task_status',
    })
    if (!error && code === 200) {
        tasksStatus.value = getArrValue(data)
    } else {
        tasksStatus.value = []
    }
}

//合同段
const ContractIdChange = (val) => {
    searchForm.value.batch = null
   emit('changeselectContracId', val)
    queryBatchList()
    // queryUserStartFlow()
    getTableData()
   
}

//获取上报批次
const reportBatch = ref([])
const queryBatchList = async () => {
    const { contractId } = searchForm.value
    if (contractId) {
        const { error, code, data } = await tasksApi.queryBatchList({
            projectId: projectId.value,
            contractId: contractId || '',
        })
        if (!error && code === 200) {
            reportBatch.value = getArrValue(data)
        } else {
            reportBatch.value = []
        }
    } else {
        reportBatch.value = []
    }
}

//搜索表单
const searchForm = ref({
    queryValue: null, typeValue: null, statusValue: null, batch: null, startTimeValue: null, endTimeValue: null,
    current: 1, size: 200, total: 0,
})

//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({ val, arr }) => {
    betweenTime.value = arr
    searchForm.value.startTimeValue = val['start']
    searchForm.value.endTimeValue = val['end']
}

//回车搜索
const keyUpEvent = (e) => {
    if (e.key === 'Enter') {
        searchForm.value.current = 1
        getTableData()
    }
}

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

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

//获取数据
const tableLoading = ref(false)
const tableListColumn = ref([
    { key: 'taskName', name: '任务名称' },
    { key: 'taskTypeName', name: '任务类型', width: '120' },
    { key: 'taskStatusName', name: '任务状态', width: '160' },
    { key: 'startTime', name: '开始时间', width: '180' },
    { key: 'endTime', name: '限定时间', width: '180' },
    { key: 'taskDesc', name: '任务描述' },
    { key: 'taskReportUserName', name: '上报人', width: '120' },
    { key: 'taskApproveUserNamesList', name: '签字人员' },
    { key: 'evisaStatus', name: '电签状态' },
])
const tableListData = ref([])
const getTableData = () => {
    const key = isTableKey.value
    tableListRef.value?.clearSelection()
    tableCheckedKeys.value = []
    // if (key === 'key1') {
    //     queryUserToDoTaskList()
    // } else if (key === 'key2') {
    //     queryUserDoneTaskList()
    // } else if (key === 'key3') {
    //     queryUserStartFlow()
    // }
    if (key === 'key1') {
        searchForm.value.selectedType = 1
    } else if (key === 'key2') {
        searchForm.value.selectedType = 2
    } else if (key === 'key3') {
        searchForm.value.selectedType = 3
    }
    queryPage()
}

//待办任务列表
// const queryUserToDoTaskList = async () => {
//     tableLoading.value = true
//     const { error, code, data } = await tasksApi.queryUserToDoTaskList({
//         ...searchForm.value,
//         projectId: projectId.value,
//         currentContractId:currentContractId.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 queryPage = async () => {
    tableLoading.value = true
    const { error, code, data } = await tasksApi.getTaskPage({
        ...searchForm.value,

        projectIdValue: projectId.value,

        currentContractId:currentContractId.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 queryUserDoneTaskList = async () => {
    tableLoading.value = true
    const { error, code, data } = await tasksApi.queryUserDoneTaskList({
        ...searchForm.value,
        projectId: projectId.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 queryUserStartFlow = async () => {
    tableLoading.value = true
    const { error, code, data } = await tasksApi.queryUserStartFlow({
        ...searchForm.value,
        projectId: projectId.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 tableListRef = ref(null)
const tableCheckedKeys = ref([])
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows.filter((item) => {
        return (item ?? '') !== ''
    })
}

//任务审核
const rowTaskName = (row) => {
    emit('rowTaskName', row)
}

//设置重签规则
const setSignRulesClick = () => {
    emit('signRules', {})
}

//批量审批
const batchApprovalTaskClick = () => {
    const rows = tableCheckedKeys.value
    if (rows.length > 0) {
        emit('batchApproval', rows)
    } else {
        window?.$message?.warning('请先勾选需要审批的数据')
    }
}
</script>

<style lang="scss" scoped>

</style>
