<template>
    <!-- 业务办理审核 -- 领用审核 -->
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" inline>
            <el-form-item label="申请日期" prop="startTime">
                <el-date-picker
                v-model="queryParams.startTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="开始日期"
                @change="() => queryParams.endTime = ''"
                style="width: 130px"
                />
            </el-form-item>
            <el-form-item>-</el-form-item>
            <el-form-item prop="endTime">
                <el-date-picker
                v-model="queryParams.endTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="结束日期"
                :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.startTime).getTime() - 86400000}"
                style="width: 130px"
                />
            </el-form-item>
                <el-form-item label="分公司" prop="impUnitName">
                <el-select
                    v-model="queryParams.impUnitName"
                    placeholder="请选择分公司"
                    clearable
                    filterable
                    style="width: 100%"
                >
                    <el-option
                    v-for="item in impUnitOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="关键字" prop="keyWord">
                <el-input
                    clearable
                    placeholder="请输入关键字"
                    v-model="queryParams.keyWord"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="审核状态" prop="taskStatus">
                <el-select v-model="queryParams.taskStatus" placeholder="请选择审核状态" clearable>
                    <el-option
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        v-for="item in statusOptions"
                    />
                </el-select>
            </el-form-item>

            <!-- 表单按钮 -->
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
                <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>

        <el-table :data="tableList" fit highlight-current-row style="width: 100%" :max-height="650" v-loading="loading">
            <!-- <el-table-column type="selection" width="55" align="center" @selection-change="selectionChange" /> -->
            <el-table-column
                width="55"
                type="index"
                label="序号"
                align="center"
                :index="indexContinuation(queryParams.pageNum, queryParams.pageSize)"
            />
            <el-table-column
                v-for="column in tableColumns"
                align="center"
                :key="column.prop"
                :prop="column.prop"
                :label="column.label"
                :width="column.width"
                :show-overflow-tooltip="column.showTooltip == false ? false : true"
            >
                <!-- 插槽 -->
                <template v-slot="{ row }" v-if="column.prop == 'taskStatus'">
                    <el-tag v-if="row.taskStatus == '1'" size="mini">审核中</el-tag>
                    <el-tag v-if="row.taskStatus == '0'" type="warning" size="mini">待审核</el-tag>
                    <el-tag v-if="row.taskStatus == '2'" type="success" size="mini">已完成</el-tag>
                    <el-tag v-if="row.taskStatus == '3'" type="danger" size="mini">已驳回</el-tag>
                </template>
            </el-table-column>
            <!-- 操作 -->
            <el-table-column label="操作" align="center" width="180">
                <template slot-scope="{ row }">
                    <el-button
                        type="text"
                        size="mini"
                        icon="el-icon-edit"
                        v-if="auditingShow(row)"
                        @click="handleAuditing(row, 1)"
                    >
                        审核
                    </el-button>
                    <el-button
                        type="text"
                        size="mini"
                        icon="el-icon-search"
                        @click="handleAuditing(row, 2)"
                    >
                        查看
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
            :total="total"
            v-show="total > 0"
            @pagination="getList"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
        />
    </div>
</template>

<script>
import { getReceiveApplyApi } from '@/api/receive-apply/index.js'
import {getImpUnitListApi} from "@/api/materialsStation";
import { getToken, setToken, setExpiresIn } from '@/utils/auth'

export default {
    name: 'Receive-apply',
    data() {
        return {
            loading: false,
            total: 0, // 总条数
            userId: '',
            // 表格数据
            tableList: [],
            timeRange: [],
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                keyWord: '', // 关键字
                taskStatus: '1', // 审核状态
                startTime: '', // 开始时间
                endTime: '', // 结束时间
                impUnitName: '', // 分公司
            },
            // 审核状态
            statusOptions: [
                { label: '待审核', value: '0' },
                { label: '审核中', value: '1' },
                { label: '已完成', value: '2' },
                { label: '已驳回', value: '3' }
            ],
            // 表头 
            tableColumns: [
                { label: '申请时间', prop: 'createTime', width: '100',  showTooltip: false },
                { label: '申请人', prop: 'createBy' },
                { label: '分公司', prop: 'impUnitName', showTooltip: false },
                { label: '领用单位', prop: 'leaseUnit', showTooltip: false },
                { label: '领用工程', prop: 'leaseProject', showTooltip: false },
                { label: '领料物资类型', prop: 'maTypeNames' },
                { label: '协议号', prop: 'agreementCode' },
                { label: '业务单号', prop: 'code', showTooltip: false },
                { label: '领料人', prop: 'leasePerson' },
                { label: '领料人电话', prop: 'phone' },
                { label: '状态', prop: 'taskStatus' }
            ],
            impUnitOptions: [], // 分公司下拉选
        }
    },
    async created() {
        const end = new Date()
        let start = new Date()
        start.setMonth(start.getMonth() - 1)
        this.timeRange = [this.format(start), this.format(end)]
        this.queryParams.startTime = this.format(start)
        this.queryParams.endTime = this.format(end)

        const origin = window.location.href
        console.log(origin.split('ticket')[1], 'origin')
        const token = getToken()
        console.log('🚀 ~ created ~ shh:', token)

        if (origin.indexOf('ticket') != -1 && !token) {
            this.isIws = true
            const loading = this.$loading({
                lock: true,
                text: '登录中',
            })
            try {
                const res = await iwsLogin({
                    ticket: origin.split('ticket%3D')[1].split('%26')[0] || origin.split('ticket=')[1].split('&')[0],
                    sysType: 0
                })
                console.log('🚀 ~ created ~ res:', res)
                if (res.code == 200) {
                    setToken(res.data.access_token)
                    this.$store.commit('SET_TOKEN', res.data.access_token)
                    setExpiresIn(1800)
                    this.$store.commit('SET_EXPIRES_IN', 1800)
                }
                // setExpiresIn(res.data.expires_in)
                // this.$store.commit('SET_EXPIRES_IN', res.data.expires_in)
                loading.close()

                setTimeout(() => {
                    this.$router.push({ path: '/business-examine/receive-apply' })
                    // this.getList()
                }, 300)
            } catch (error) {
                console.log('🚀 ~ created ~ error:', error)
                this.$message({
                    message: '登录失败, 即将关闭页面',
                    type: 'error'
                })
                loading.close()
                setTimeout(() => {
                    // 关闭窗口
                    window.close()
                }, 1500)
            }
        } else {
            this.userId = sessionStorage.getItem('userId')
            // 设置默认状态为第一个选项（待审核）
            // if (this.statusOptions.length > 0) {
            //     this.queryParams.taskStatus = this.statusOptions[0].value
            // }
            // if (this.statusOptions.length > 1) {
            //     this.queryParams.taskStatus = this.statusOptions[1].value
            // }
            this.getImpUnitOptions()
            this.getList()
        }
    },
    methods: {
        format(date) {
            const y = date.getFullYear()
            const m = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            return `${y}-${m}-${day}`
        },
        // 查询
        handleQuery() {
            this.getList()
        },
        // 重置
        handleReset() {
            const end = new Date()
            let start = new Date()
            start.setMonth(start.getMonth() - 1)
            this.timeRange = [this.format(start), this.format(end)]
            this.queryParams.startTime = this.format(start)
            this.queryParams.endTime = this.format(end)
            this.queryParams.pageNum = 1
            this.queryParams.pageSize = 10
            this.$refs.queryForm.resetFields()
            this.getList()
        },

        async getImpUnitOptions() {
            try {
            const res = await getImpUnitListApi()
            this.impUnitOptions = res.data.map(item => ({
                label: item.impUnitName,
                value: item.impUnitName
            }))
            } catch (e) {
            console.error('获取分公司下拉失败:', e)
            }
        },        
        // 获取列表
        async getList() {
            try {
                this.loading = true
                const params = {
                    ...this.queryParams,
                    // startTime: this.timeRange ? this.timeRange[0] : '',
                    // endTime: this.timeRange ? this.timeRange[1] : ''
                }
                const res = await getReceiveApplyApi(params)
                this.tableList = res.data.rows
                this.total = res.data.total || 0
            } catch (error) {
                this.tableList = []
                this.total = 0
            } finally {
                this.loading = false
            }
        },
        // 多选
        selectionChange(val) {
            console.log('selectionChange', val)
        },
        // 操作按钮
        handleAuditing(row, type) {
            // ----type---- 1. 查看 2. 审核
            // 跳转审核详情页面
            this.$router.push({
                name: 'receive-apply-details',
                query: {
                    id: row.id,
                    taskId: row.taskId,
                    type,
                    nodeId: row.nodeId
                }
            }) // 跳转审核详情页面
        },

        // 判断审核按钮显示隐藏
        auditingShow(row) {
            if (row.configValue) {
                return (row.taskStatus == 1 || row.taskStatus == 0) && row.configValue.includes(this.userId)
            }
        }
    }
}
</script>

<style lang="scss" scoped></style>
