<template>
    <HcCard>
        <template #header>
            <div class="w-36">
                <el-select v-model="searchForm.orgDept" block clearable placeholder="选择部门" size="large" @change="changeDpet">
                    <el-option v-for="item in department" :label="item.deptName" :value="item.id" />
                </el-select>
            </div>
            <div class="w-36 ml-2">
                <el-select v-model="searchForm.userId" block clearable placeholder="选择人员" size="large">
                    <el-option v-for="item in departmentPeople" :label="item.name" :value="item.id" />
                </el-select>
            </div>
            <div class="w-36 ml-4">
                <el-date-picker v-model="searchForm.startTime" class="block" type="month" value-format="YYYY-MM" placeholder="开始日期" clearable size="large" />
            </div>
            <div class="mx-2">
                ~
            </div>
            <div class="w-36">
                <el-date-picker v-model="searchForm.endTime" class="block" type="month" value-format="YYYY-MM" placeholder="结束日期" clearable size="large" />
            </div>
            <div class="ml-4">
                <el-button size="large" type="primary" @click="searchClick">
                    <HcIcon name="search-2" />
                    <span>搜索</span>
                </el-button>
            </div>
            <div class="ml-2">
                <el-button size="large" @click="resetClick">
                    <HcIcon name="close-circle" />
                    <span>重置</span>
                </el-button>
            </div>
        </template>
        <template #extra>
            <el-button v-if="isEditState" size="large" type="warning" @click="submitLogsClick">
                <HcIcon name="check-double" />
                <span>提交日志</span>
            </el-button>
            <template v-else>
                <el-button v-if="!isShowEdit" size="large" type="primary" @click="editLogsClick">
                    <HcIcon name="add" />
                    <span>写日志</span>
                </el-button>
                <!-- 修改自己的日志 -->
                <el-button v-else size="large" type="primary" @click="editmyLog">
                    <HcIcon name="add" />
                    <span>写日志</span>
                </el-button>
            </template>
          
            <el-button v-if="isEditState" size="large" type="primary" @click="gobackLog">
                <HcIcon name="arrow-go-back" />
                <span>取消</span>
            </el-button>
        </template>
        <div class="hac-logs-main-body">
            <div class="hac-logs-user-list-body">
                <HcCardItem scrollbar>
                    <div v-for="(item, key) in userList" class="hac-user-list-item">
                        <div class="label">
                            {{ key }}
                        </div>
                        <template v-for="items in item">
                            <div class="user-item" :class="userItemId.id === items.id ? 'cur' : ''" @click="userItemClick(items)">
                                <img class="avatar" :src="items?.headPicture || avatarPng" alt="">
                                <div class="name">
                                    {{ items?.logTitle }}
                                </div>
                                <div v-if="items?.isEdit === 0" class="state">
                                    <span v-if="items?.isRead === 0" class="text-xl text-red mr-2">
                                        <HcIcon name="alarm-warning" />
                                    </span>
                                    <span>{{ items?.isRead === 0 ? '未读' : '已读' }}</span>
                                </div>
                            </div>
                        </template>
                    </div>
                </HcCardItem>
            </div>
            <div v-loading="logLoading" class="hac-logs-content-body">
                <HcLogsContent v-if="isEditState" ref="logsRef" :data="logForm" :is-showmy-edit="isShowEdit" />
                <HcLogsContent v-else :data="logDetail" :edit="false" :undefined-num="undefinedNum" />
            </div>
        </div>
    </HcCard>
</template>

<script setup>
import { onActivated, ref } from 'vue'
import logsApi from '~api/task/logs'
import { useAppStore } from '~src/store'
import { getArrValue, getObjValue, isArray } from 'js-fast-way'
import HcLogsContent from './components/logs-content.vue'
import avatarPng from '~src/assets/images/avatar.png'
import dayjs from 'dayjs'
import { getdepartmentList, getuserList } from '~api/other'

const useAppState = useAppStore()
const userInfo = ref(useAppState.getUserInfo)
const isShowEdit = ref(false)//编辑自己的日志
// 调用时机为首次挂载, 以及每次从缓存中被重新插入时
onActivated(() => {
    isEditState.value = false
    getLogList()
    getDepartmentDict()
    getUserDict()
   

})
const department = ref([])
//获取部门列表
const getDepartmentDict = async ()=>{
    const { error, code, data } = await getdepartmentList({ deptType:2 })
    if (!error && code === 200) {
        department.value = getArrValue(data)

    } else {
        department.value = []

    }
}
//改变部门
const changeDpet = (val)=>{
    getDepartmentuserDict(val)
}
const departmentPeople = ref([])
//获取部门人员列表
const getDepartmentuserDict = async (id)=>{
    const { error, code, data } = await getuserList({ deptId:id })
    if (!error && code === 200) {
        departmentPeople.value = getArrValue(data)

    } else {
        departmentPeople.value = []

    }
}
//获取所有员工

const getUserDict = async ()=>{
    const { error, code, data } = await getuserList({ tenantId:useAppState.tenantId })
    if (!error && code === 200) {
        departmentPeople.value = getArrValue(data)

    } else {
        departmentPeople.value = []

    }
}
//搜索表单
const searchForm = ref({ orgDept: null, userId: null, startTime: null, endTime: null })

//搜索
const searchClick = () => {
    if (!isEditState.value) {
        getLogList()
    } else {
        window.$message?.warning('请先提交日志或退出填写日志状态')
    }
}

//重置
const resetClick = () => {
    searchForm.value = {}
    getLogList()
}

//日志填报列表查询
const userList = ref({})
const getLogList = async () => {
    const { error, code, data, msg } = await logsApi.getLogList(searchForm.value)
    //判断状态
    if (!error && code === 200) {
        const res = getObjValue(data)
        userList.value = res
        //默认选择第一个
        Object.keys(res).forEach((key, index) => {
            if (index === 0) {
                userItemId.value = res[key][0]
            }
        })
        getLogDetail()
    } else {
        userList.value = {}
        userItemId.value = {}
        window.$message?.error(msg)
    }
}

//用户列表点击
const userItemId = ref({})
const userItemClick = (item) => {
    if (!isEditState.value) {
        userItemId.value = item
        isShowEdit.value = false
        item.isRead = 1
        getLogDetail()
    } else {
        window.$message?.warning('请先提交日志或退出填写日志状态')
    }
}

//日志填报详情
const logDetail = ref({})
const undefinedNum = ref(null)
const getLogDetail = async () => {
    const item = userItemId.value
    if (item.id) {
        const { error, code, data, msg } = await logsApi.getLogDetail({
        id: item.id,
        })
        //判断状态
        if (!error && code === 200) {
            logDetail.value = getObjValue(data)
            const { real_name, avatar } = userInfo.value
            let logTitle = logDetail.value['logTitle']
            console.log(logTitle, 'logTitle')
            let index = logTitle.lastIndexOf('的')
            let str = logTitle.substring(0, index)
            //判断是否编辑自己的日志
            if (real_name === str) {
                isShowEdit.value = true
            }
        } else {
            logDetail.value = {}
            window.$message?.error(msg)
        }
        //计算未完成数量
        console.log(logDetail.value.taskList, 'taskList')
        let arr = []
        if (isArray(logDetail.value?.taskList)) {
            // eslint-disable-next-line array-callback-return
            arr = logDetail.value?.taskList.filter((ele)=>{
                // eslint-disable-next-line eqeqeq
                if (ele?.isOverdue == 1) {
                    return ele
                }
            })
        }
     
        undefinedNum.value = arr.length
       console.log( undefinedNum.value, ' undefinedNum.value')
    }

}

//日志填报表单
const logForm = ref({
    headPicture: '',
    logTitle: '',
    createTime: '',
    riskWarning: '',
    workDesc: '',
    expenseReimbursementAmount: '',
})

//当前状态，false查看模式，true写日志模式
const isEditState = ref(false)
const editLogsClick = () => {
    console.log('写日志')
    logForm.value = {
    headPicture: '',
    logTitle: '',
    createTime: '',
    riskWarning: '',
    workDesc: '',
    expenseReimbursementAmount: '',
}
    const { real_name, avatar } = userInfo.value
    isEditState.value = true
    logForm.value.headPicture = avatar || avatarPng
    logForm.value.logTitle = real_name + '的日志'
    logForm.value.createTime = dayjs().format('YYYY-MM-DD')
}
//修改自己的日志

const editmyLog = ()=>{
    console.log('修改自己的')
    isEditState.value = true
    logForm.value = logDetail.value
  
}
//返回到查看日志界面
const gobackLog = ()=>{
    isEditState.value = false
    isShowEdit.value = false
}
const logsRef = ref(null)
const logLoading = ref(false)

const submitLogsClick = async () => {
    logLoading.value = true
    const form = logsRef.value?.getLogForm()
    //移除不必要的字段
    delete form.createTime
    delete form.headPicture
    delete form.logTitle
    //发起请求
    const { error, code, msg } = await logsApi.setLogSubmit(form)
    //判断状态
    logLoading.value = false
    if (!error && code === 200) {
        isEditState.value = false
        getLogList()
    } else {
        window.$message?.error(msg)
    }
}
</script>

<style lang="scss" scoped>
@import "~src/styles/task/logs.scoped.scss";
</style>
