<template>
    <div class="hc-layout-box">
        <HcNewCard :scrollbar="false" action-size="lg">
            <template #header>
                <div class="w-64">
                    <el-input v-model="searchForm.evisaUserName" block clearable placeholder="请输入用户名称检索" @keyup="keyUpEvent" />
                </div>
                <div class="w-32 ml-3">
                    <el-select v-model="searchForm.contractId" block clearable placeholder="合同段" @change="ContractIdChange">
                        <el-option v-for="item in contractList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </div>
                <div class="w-32 ml-3">
                    <el-select v-model="searchForm.visaStatus" block placeholder="电签状态" @change="visaStatusChange">
                        <el-option label="电签失败" :value="1" />
                        <el-option label="电签成功" :value="2" />
                    </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_sign_key_renewal">
                    <el-button hc-btn type="primary" :loading="resignLoading" :disabled="tableCheckedKeys.length == 0" @click="resignClick">
                        <HcIcon name="restart" />
                        <span>一键重签</span>
                    </el-button>
                </HcTooltip>
            </template>
            <HcTable
                ref="tableListRef" :column="tableListColumn" :datas="tableData" :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>
                <HcPages :pages="searchForm" :sizes="[10, 20, 30, 40, 50, 200]" @change="pageChange" />
            </template>
        </HcNewCard>
        <!-- 一键重签弹窗 -->
        <hc-new-dialog v-model="resignModal" title="一键重签" widths="38rem" :loading="resignLoading" @close="cancelresign" @save="saveResign">
            <div>
                是否重新生成pdf:
                <el-radio-group v-model="resignModalRadio">
                    <el-radio :label="0">否</el-radio>
                    <el-radio :label="1">是</el-radio>
                </el-radio-group>
            </div>
        </hc-new-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useAppStore } from '~src/store'
import { arrToId, getArrValue, getObjValue } from 'js-fast-way'
import signApi from '~api/tasks/sign'

//变量
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const projectInfo = ref(useAppState.getProjectInfo)
const contractInfo = ref(useAppState.getContractInfo)

//渲染完成
onMounted(() => {
    const project = getObjValue(projectInfo.value)
    contractList.value = getArrValue(project['contractInfoList'])
    const { contractType } = contractInfo.value
    searchForm.value.contractId = contractId.value
    contractTypeTabKey.value = contractType === 2 ? '2' : '1'
    getTableData()
})

const tasksData = ref([])
const statusData = ref([])
const contractTypeTabKey = ref('1')

//合同段
const contractList = ref([])
const ContractIdChange = (id) => {
    const list = contractList.value
    for (let i = 0; i < list.length; i++) {
        if (list[i].id === id) {
            contractTypeTabKey.value = list[i].contractType === 2 ? '2' : '1'
            break
        }
    }
    console.log(contractTypeTabKey.value)
    getTableData()
}
const visaStatusChange = () => {
    getTableData()
}
//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({ val, arr }) => {
    betweenTime.value = arr
    searchForm.value.startTimeValue = val['start']
    searchForm.value.endTimeValue = val['end']
}

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

//回车搜索
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 tableData = ref([])
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await signApi.eVisaFailedPage({
        ...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 tableListRef = ref(null)
const tableCheckedKeys = ref([])
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows.filter((item) => {
        return (item ?? '') !== ''
    })
}
const tableListColumn = ref([
    { key: 'taskName', name: '流程名称' },
    { key: 'taskStatusName', name: '任务状态' },
    { key: 'evisaStatusName', name: '电签状态' },
    { key: 'startTime', name: '开始时间' },
    { key: 'endTime', name: '限定时间' },
    { key: 'evisaUpdateDate', name: '审批时间' },
    { key: 'evisaFailedInfo', name: '电签失败原因' },
    { key: 'taskReportUserName', name: '上报人' },
    { key: 'taskApproveUserNamesList', name: '电签任务人' },
])

//一键重签
const resignModal = ref(false)
const resignModalRadio = ref(0)
const resignLoading = ref(false)
const resignClick = async ()=>{
    resignModal.value = true


}
const saveResign = async ()=>{
    const taskIds = arrToId(tableCheckedKeys.value)
   resignLoading.value = true
    const { error, code, msg } = await signApi.reSigningEVisa({
       contractId:searchForm.value.contractId,
       projectId:projectId.value,
       taskIds:taskIds,
        classifyType: contractTypeTabKey.value,
        type:resignModalRadio.value,
    })
    //判断状态
    resignLoading.value = false
    if (!error && code === 200) {
       window.$message.success(msg)
       getTableData()
    }
    resignModal.value = false
}
const cancelresign = ()=>{
    resignModalRadio.value = 0
    resignModal.value = false
}
const rowTaskName = (row)=>{
    if (row?.sigPdf) {
        window.open(row.sigPdf, '_blank')
    } else {
        window?.$message.warning('暂无文档')
    }
}
</script>

<style lang="scss" scoped>
.hc-layout-box {
    position: relative;
    height: 100%;
}
</style>
