<template>
    <div class="container">
        <header>
            <el-form :inline="true" class="demo-form-inline" :label-width="120">
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="来信时间">
                            <el-date-picker v-model="query.mailTime" value-format="YYYY-MM-DD" type="daterange"
                                range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="信件来源">
                            <el-select v-model="query.source" placeholder="" clearable style="width: 280px">
                                <el-option v-for="item in dictData.mail_source" :key="item.value" :label="item.name"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="来信人员">
                            <div class="flex gap">
                                <el-select v-model="query.contactField" style="width: 100px">
                                    <el-option label="姓名" value="name" />
                                    <el-option label="身份证" value="idCard" />
                                    <el-option label="联系电话" value="phone" />
                                </el-select>
                                <el-input v-model="query.contactFieldValue" :placeholder="placeholderText" clearable
                                    style="width: 172px" />
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="信件等级">
                            <el-select v-model="query.mailLevel" placeholder="" clearable style="width: 280px">
                                <el-option v-for="item in dictData.mail_level" :key="item.value" :label="item.name"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="信件分类">
                            <el-tree-select v-model="query.mailCategory" :data="mailStore.mailCategorys" check-strictly
                                filterable style="width: 280px" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="信件状态">
                            <el-select v-model="query.mailState" placeholder="" clearable style="width: 280px">
                                <el-option v-for="item in dictData.mail_state" :key="item.value" :label="item.name"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="办理单位">
                            <div class="flex gap">
                                <el-tree-select class="flex-1" v-model="query.threeDeptName" :data="optionsData.dept"
                                    clearable node-key="id" filterable :props="{
                                        value: 'name',
                                        label: 'name',
                                        disabled(data: any) {
                                            return !!data.isStop
                                        }
                                    }" check-strictly :default-expand-all="true" placeholder="请选择上级部门"
                                    style="width: 280px" />
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="流程阶段">
                            <el-select v-model="query.flowKey" placeholder="" clearable style="width: 280px">
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="信件标签">
                            <el-select v-model="query.tags" placeholder="请选择标签" multiple clearable style="width: 280px">
                                <el-option v-for="item in dictData.mail_tags" :key="item.value" :label="item.name"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div style="display: flex; justify-content: space-between; margin-bottom: 20px;">
                    <div>
                        <el-button type="primary" @click="checkMail">信件核对</el-button>
                    </div>
                    <div>
                        <el-button type="primary" @click="getList">查询</el-button>
                        <el-button @click="reset">重置</el-button>
                    </div>
                </div>
            </el-form>
        </header>
        <main>
            <div class="table-container">
                <el-table :data="todos" style="width: 100%" stripe ref="tableRef" @selection-change="handleSelectionChange"
                    @select-all="handleSelectAll">
                    <el-table-column type="selection" width="30" />
                    <el-table-column prop="mailTime" label="来信时间" align="center" width="170" />
                    <el-table-column label="信件来源" align="center" width="94">
                        <template #default="{ row }">
                            <span>{{
                                dictData.mail_source.filter(
                                    (item) => item.value === row.source
                                )[0].name
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="contactName" label="姓名" align="center" width="70" />
                    <el-table-column prop="contactPhone" label="联系电话" width="120" />
                    <el-table-column label="信件等级" width="100">
                        <template #default="{ row }">
                            <mail-level :value="row.mailLevel" :list="dictData.mail_level" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="mailCategory" label="信件分类" width="160" />
                    <el-table-column prop="content" label="信件内容" show-overflow-tooltip />
                    <el-table-column label="信件状态" width="90">
                        <template #default="{ row }">
                            <span>{{ getDictLable(dictData.mail_state, row.mailState) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="threeDeptName" label="办理单位" width="160" />
                    <el-table-column label="流程节点">
                        <template #default="{ row }">
                            <el-tag :type="getFlowTagType(row.flowKey)" v-if="row.flowBeforeName">{{ row.flowBeforeName
                            }}</el-tag>
                            <el-tag type="danger" v-else>未签收</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="流程限时" width="140">
                        <template #default="{ row }">
                            <div v-if="row.flowLimitedRemainingTime > 0" class="success">
                                <span class="mr-4">剩余</span>
                                <span class="text">{{ formatTimeText(row.flowLimitedRemainingTime) }}</span>
                            </div>
                            <div v-if="row.flowLimitedRemainingTime < 0" class="error">
                                <span class="mr-4">超时</span>
                                <span class="text">{{ formatTimeText(-row.flowLimitedRemainingTime) }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="tags" label="信件标签" width="160" />
                    <el-table-column label="操作">
                        <template #default="{ row }">
                            <el-button type="primary" link @click="handleMail(row.mailId)">立即处理</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div style="display: flex; justify-content: space-between; margin-top: 4px;">
                <div style="display: flex; align-items: center;">
                    <el-checkbox v-model="checkAll" label="全选" style="margin-left: 15px;" :indeterminate="isCheckAll"
                        @click="handleCheckAll">全选</el-checkbox>
                    <span class="ml-4">({{ selectedCount }})条</span>
                    <el-button type="primary" link @click="outputSelectedMail" class="ml-4">信件导出</el-button>
                </div>
                <div>
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page="query.current" :page-sizes="[10, 15, 20, 40, 50]" :page-size="query.size"
                        layout="total,sizes, prev, pager, next, jumper" :total="totalSize.total">
                    </el-pagination>
                </div>
            </div>
        </main>
    </div>
    <MailDialog v-model:show="showModel" :mail-id="activeMailId" @update="getList" />
</template>
<script lang="ts" setup>
import MailDialog from "../work/components/MailDialog.vue";
import { getDones } from "@/api/work";
import { useDictData } from "@/hooks/useDictOptions";
import useMailStore from "@/stores/modules/mail";
import { formatTimeText, getDictLable, getFlowTagType } from "@/utils/util";
import { useDictOptions } from '@/hooks/useDictOptions'
import { deptLists } from '@/api/org/department'
import { ref, reactive, watch } from "vue";

const tableRef = ref(null);
const mailStore = useMailStore();
mailStore.getMailCategorys();
const { dictData } = useDictData(["mail_source", "mail_level", "mail_state"]);

const query = ref({
    contactField: "name",
    size: 20,
    current: 1
});
const totalSize = reactive({
    total: 0,
    pages: 0
})

const placeholderText = ref("请输入姓名")
watch(() => query.value.contactField, (val, prevVal) => {
    if (val === "idCard") {
        placeholderText.value = "请输入身份证号";
    } else if (val === "phone") {
        placeholderText.value = "请输入联系电话";
    } else {
        placeholderText.value = "请输入姓名";
    }
});


const allSelectedRows = ref([]);
const checkAll = ref(false);
const isCheckAll = ref(false);
const selectedCount = ref(0);
const oldSelection = ref([]);
const handleSelectAll = (selection: any) => {
    console.log("handleSelectAll", selection, isCheckAll.value)
    if (isCheckAll.value === true) {
        for (let i = 0; i < selection.length; i++) {
            if (allSelectedRows.value.includes(selection[i].mailId)) {
                allSelectedRows.value.splice(allSelectedRows.value.indexOf(selection[i].mailId), 1)
            }
        }
    }
}
const handleSelectionChange = (selection: any) => {
    checkAll.value = (tableRef.value.getSelectionRows().length === tableRef.value.data.length) ? true : false
    isCheckAll.value = (tableRef.value.getSelectionRows().length > 0 &&
        tableRef.value.data.length > tableRef.value.getSelectionRows().length) ? true : false
    console.log("oldSelection, selection", oldSelection.value.length, selection.length)
    sloveAllSelectedRows(selection)
}
const sloveAllSelectedRows = (selection: any) => {
    if (selection.length >= oldSelection.value.length) {
        for (let s of selection) {
            if (!oldSelection.value.includes(s) && !allSelectedRows.value.includes(s.mailId)) {
                allSelectedRows.value.push(s.mailId)
            }
        }
    } else {
        if (oldSelection.value.length - selection.length === 1) {
            for (let s of oldSelection.value) {
                if (!selection.includes(s) && allSelectedRows.value.includes(s.mailId)) {
                    allSelectedRows.value.splice(allSelectedRows.value.indexOf(s.mailId), 1)
                }
            }
        }

    }
    oldSelection.value = selection;
    console.log("oldSelection-Updated:", oldSelection.value)
    selectedCount.value = allSelectedRows.value.length;
}
const handleCheckAll = () => {
    tableRef.value.toggleAllSelection()
}

const outputSelectedMail = () => {
    console.log("outputSelectedMail")
}

const todos = ref([]);
const showModel = ref(false);
const activeMailId = ref("");

function handleMail(mailId) {
    showModel.value = true;
    activeMailId.value = mailId;
}

const handleSizeChange = (size) => {
    query.value.size = size;
    console.log("handleSizeChange", query.value.size)
    getList();
}

const handleCurrentChange = (page) => {
    query.value.current = page;
    getList();
}

function getList() {
    if (query.value.mailTime) {
        query.value.mailTimeStart = query.value.mailTime[0];
        query.value.mailTimeEnd = query.value.mailTime[1];
    }
    getDones(query.value).then((data) => {
        todos.value = data.records;
        console.log("todos", todos.value)
        totalSize.total = data.total;
        totalSize.pages = data.pages;
    });
}

const { optionsData } = useDictOptions<{
    dept: any[]
}>({
    dept: {
        api: deptLists
    }
})

function reset() {
    query.value = {}
    getList()
}

const checkMail = () => {
    console.log("createMail")
}

getList()


</script>
<style lang="scss" scoped>
.table-container {
    border: 1px solid rgba(198, 208, 251, 1);
}

.success .text {
    color: #128009;
    padding: 0 8px;
    height: 24px;
    line-height: 24px;
    text-align: center;
}

.error {
    background-color: #FF0000;
    color: #fff;
    padding: 0 8px;
    height: 24px;
    line-height: 24px;
    border-radius: 20px;
    text-align: center;
}
</style>