<template>
    <HcCard>
        <template #header>
            <div class="w-32">
                <el-select v-model="searchForm.taskType" block clearable size="large" 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.taskStatus" block clearable size="large" 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.contractId" placeholder="合同段" block clearable size="large" @change="ContractIdChange">
                    <el-option v-for="item in contractList" :label="item.name" :value="item.id"/>
                </el-select>
            </div>
            <div class="w-32 ml-3">
                <el-select v-model="searchForm.batch" block clearable size="large" 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" size="large" clearable @change="betweenTimeUpdate"/>
            </div>
            <div class="w-56 ml-3">
                <el-input v-model="searchForm.queryValue" block size="large" placeholder="请输入名称关键词检索" clearable @keyup="keyUpEvent"/>
            </div>
            <div class="ml-2">
                <el-button type="primary" size="large" @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 keys="tasks_data_batch_review" v-if="isTableKey === 'key1'">
                <el-button hc-btn type="primary" :disabled="tableCheckedKeys.length <= 0" @click="batchApprovalTaskClick">
                    <HcIcon name="check-double"/>
                    <span>批量审批</span>
                </el-button>
            </HcTooltip>
        </template>
        <HcTable ref="tableListRef" :column="tableListColumn" :datas="tableListData" :loading="tableLoading" isCheck @selection-change="tableSelectionChange">
            <template #taskName="{row}">
                <span class="text-link" @click="rowTaskName(row)">{{row?.taskName}}</span>
            </template>
            <template #taskStatus="{row}">
                <el-tag :type="`${row['taskStatus']['status'] === 2 ? 'success' : row['taskStatus']['status'] === 3 ? 'warning' : 'info'}`"
                        class="mx-1" effect="dark" v-if="row?.taskStatus?.statusValue">{{row['taskStatus']['statusValue']}}</el-tag>
            </template>
            <template #waitingUserList="{row}">
                <template v-for="item in row['waitingUserList']">
                    <el-tag :type="`${item.status === 2 ? 'success' : item.status === 3 ? 'warning' : item.status === 999 ? 'danger' : 'info'}`"
                            class="mx-1" effect="dark" v-if="item['waitingUserName']">{{item['waitingUserName']}}</el-tag>
                </template>
            </template>
        </HcTable>
        <template #action>
            <div class="lr-dialog-footer">
                <div class="left">
                    <span class="text-success">审批人员中：</span>
                    <el-tag type="info" class="mx-1" effect="dark">未签字</el-tag>
                    <el-tag type="success" class="mx-1" effect="dark">已签字</el-tag>
                    <el-tag type="warning" class="mx-1" effect="dark">已废除</el-tag>
                    <el-tag type="danger" class="mx-1" effect="dark">签字异常</el-tag>
                </div>
                <div class="right">
                    <HcPages :pages="searchForm" @change="pageChange"/>
                </div>
            </div>
        </template>
    </HcCard>
</template>

<script setup>
import {ref, nextTick, watch} from "vue";
import {getArrValue} from "vue-utils-plus"
import tasksApi from '~api/tasks/data';

//参数
const props = defineProps({
    projectId: {
        type: [String,Number],
        default: ''
    },
    contractId: {
        type: [String,Number],
        default: ''
    },
    contractList: {
        type: Array,
        default: () => ([])
    },
    tableKey: {
        type: String,
        default: ''
    }
})

//变量
const projectId = ref(props.projectId);
const contractId = ref(props.contractId);
const isTableKey = ref(props.tableKey);

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

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

//获取相关数据
const setQueryData = () => {
    searchForm.value.contractId = contractId.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 = () => {
    searchForm.value.batch = null
    queryBatchList()
}

//获取上报批次
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, taskType: null, taskStatus: null, batch: null, startTime: null, endTime: null,
    current: 1, size: 20, total: 0
})

//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({val,arr}) => {
    betweenTime.value = arr
    searchForm.value.startTime = val['start']
    searchForm.value.endTime = 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:'typeValue', name: '任务类型', width: '120'},
    {key:'taskStatus', name: '任务状态', width: '160'},
    {key:'startTime', name: '开始时间', width: '180'},
    {key:'endTime', name: '限定时间', width: '180'},
    {key:'taskContent', name: '任务描述'},
    {key:'reportUserName', name: '上报人', width: '120'},
    {key:'waitingUserList', name: '签字人员'},
    {key:'evisaContent', 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()
    }
}

//待办任务列表
const queryUserToDoTaskList = async () => {
    tableLoading.value = true
    const { error, code, data } = await tasksApi.queryUserToDoTaskList({
        ...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 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 emit = defineEmits(['rowTaskName','signRules','batchApproval'])

//任务审核
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>
