<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--部门数据-->
            <el-col :span="4" :xs="24">
                <div class="head-container">
                    <el-input
                        v-model="deptName"
                        placeholder="请输入部门名称"
                        clearable
                        size="small"
                        prefix-icon="el-icon-search"
                        style="margin-bottom: 20px"
                    />
                </div>
                <div class="head-container">
                    <el-tree
                        :data="deptOptions"
                        :props="defaultProps"
                        :expand-on-click-node="false"
                        :filter-node-method="filterNode"
                        ref="tree"
                        node-key="id"
                        default-expand-all
                        highlight-current
                        @node-click="handleNodeClick"
                    />
                </div>
            </el-col>
            <!--用户数据-->
            <el-col :span="20" :xs="24">
                <el-form
                    :model="queryParams"
                    ref="queryForm"
                    size="small"
                    :inline="true"
                    v-show="showSearch"
                    label-width="68px"
                >
                    <el-form-item label="用户姓名" prop="nickName">
                        <el-input
                            v-model="queryParams.nickName"
                            placeholder="请输入用户姓名"
                            clearable
                            style="width: 240px"
                            @keyup.enter.native="handleQuery"
                        />
                    </el-form-item>
                    <el-form-item label="手机号码" prop="phonenumber">
                        <el-input
                            v-model="queryParams.phonenumber"
                            placeholder="请输入手机号码"
                            clearable
                            style="width: 240px"
                            @keyup.enter.native="handleQuery"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button
                            type="primary"
                            icon="el-icon-search"
                            size="mini"
                            @click="handleQuery"
                            >搜索</el-button
                        >
                        <el-button
                            icon="el-icon-refresh"
                            size="mini"
                            @click="resetQuery"
                            >重置</el-button
                        >
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button
                            type="warning"
                            plain
                            icon="el-icon-download"
                            size="mini"
                            @click="handleExport"
                            >导出
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
                            type="primary"
                            plain
                            icon="el-icon-plus"
                            size="mini"
                            :disabled="multiple"
                            @click="handleTask"
                            >有无证件核验
                        </el-button>
                    </el-col>
                    <right-toolbar
                        :showSearch.sync="showSearch"
                        @queryTable="getList"
                    ></right-toolbar>
                </el-row>
                <!-- <div style="width: 98%;margin: 10px;display: flex;justify-content: flex-end;">
                    <span style="font-weight: bold;">有证人数：{{statistics.ownNum}}</span>
                    <span style="font-weight: bold;margin-left: 20px;">无证人数：{{statistics.unOwnNum}}</span>
                </div> -->
                <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="50" align="center"/>
                    <el-table-column label="序号" align="center" width="80" type="index">
                        <template slot-scope="scope">
                            <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="用户姓名" align="center" prop="nickName"  :show-overflow-tooltip="true"/>
                    <el-table-column label="身份证号" align="center" prop="idNumber"  :show-overflow-tooltip="true"/>
                    <el-table-column label="手机号码" align="center" prop="phonenumber"  width="120">
                        <template slot-scope="scope">
                            <span>{{ hidePhone(scope.row.phonenumber) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="单位职务" align="center" prop="postName"  :show-overflow-tooltip="true"/>
                    <el-table-column label="人员类别" align="center" prop="userTypeName"  :show-overflow-tooltip="true"/>
                    <el-table-column label="责任处室" align="center" prop="deptName"  :show-overflow-tooltip="true"/>
                    <el-table-column label="有无证件" align="center" prop=""  :show-overflow-tooltip="true">
                      <template slot-scope="scope">
                          <span v-if="scope.row.isHave==0||scope.row.isHave==null" style="color: #FF7322;font-size: 15px;">无</span>
                          <span v-if="scope.row.isHave==1" style="color: #03DF6D;font-size: 15px;">有</span>
                      </template>
                    </el-table-column>

                </el-table>

                <pagination
                    v-show="total > 0"
                    :total="total"
                    :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
                />
            </el-col>
        </el-row>

        <!-- 添加或修改参数配置对话框 -->
        <el-dialog title="核验任务下达" :visible.sync="openTask" width="600px" append-to-body>
            <el-form ref="taskForm" :model="taskForm" :rules="taskRules" label-width="120px">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="核验开始日期" prop="startTime">
                       <el-date-picker
                           v-model="taskForm.startTime"
                           type="date"
                           placeholder="选择日期"
                           format="yyyy-MM-dd" style="width: 100%;"
                           :picker-options="pickerOptionsToday"
                           @focus="startDateFocus"
                           value-format="yyyy-MM-dd"></el-date-picker>
                   </el-form-item>
                   <el-form-item label="核验结束日期" prop="endTime">
                       <el-date-picker
                           v-model="taskForm.endTime"
                           type="date"
                           placeholder="选择日期"
                           :picker-options="pickerOptionsStart"
                           @focus="endDateFocus"
                           format="yyyy-MM-dd" style="width: 100%;"
                           value-format="yyyy-MM-dd"></el-date-picker>
                   </el-form-item>
                </el-col>
            </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitTask">确 定</el-button>
            <el-button @click="cancelTask">取 消</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {
    listUser,
    deptTreeSelect,
} from '@/api/system/user'
import {getCertificateUserListPageApi,addCertificateCheckApi} from "@/api/certificateManage/index"
import { getStatisticsApi } from "@/api/certificateStatistics/index";
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
    name: '',
    dicts: [
        // 'sys_normal_disable',
        // 'sys_user_sex',
        // 'sys_user_type',
        // 'sys_login_type',
        // 'sys_user_permanent',
    ],
    components: { Treeselect },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 用户表格数据
            userList: null,
            // 部门树选项
            deptOptions: undefined,
            // 部门名称
            deptName: undefined,
            defaultProps: {
                children: 'children',
                label: 'label',
            },
            statistics:{
              registerNum:0,
              ownNum:0,
              unOwnNum:0,
              storeNum:0,
              unStoreNum:0,
              passPortNum:0,
              outPassPortNum:0,
              inPassPortNum:0,
              hMCardNum:0,
              outHMCardNum:0,
              inHMCardNum:0,
              taiwanNum:0,
              outTaiwanNum:0,
              inTaiwanNum:0,
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                isCertificate:"1",
                userName: undefined,
                phonenumber: undefined,
                deptId: undefined,
            },
            openTask: false,
            // 表单参数
            taskForm: {
                processDate:""
            },
            // 表单校验
            taskRules: {
                processDate: [
                    {
                        required: true,
                        message: '核验截止日期不能为空',
                        trigger: 'blur',
                    },
                ]
            },
            pickerOptionsToday: {
              disabledDate(time) {
                // 获取今天的日期
                const today = new Date();
                today.setHours(0, 0, 0, 0); // 设置时间为00:00:00，确保比较时只比较日期部分
                // 比较日期，禁用今天之前的日期
                return time.getTime() < today.getTime();
              }
            },
            pickerOptionsStart: {
              disabledDate(time) {
                // 获取今天的日期
                const startTime=this.taskForm.startTime;
                const today = new Date(startTime);
                today.setHours(0, 0, 0, 0); // 设置时间为00:00:00，确保比较时只比较日期部分
                // 比较日期，禁用今天之前的日期
                return time.getTime() < today.getTime();
              }
            },
        }
    },
    watch: {
        // 根据名称筛选部门树
        deptName(val) {
            this.$refs.tree.filter(val)
        },
    },
    created() {
        this.getList()
        this.getDeptTree()
        this.initStatistics();
    },
    methods: {
        /* 手机号码脱敏 */
        hidePhone(phone) {
            if (!phone) return ''
            return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
        },
        startDateFocus() {
          this.taskForm.endTime = ''
          let endTime = this.taskForm.endTime;
          if (!endTime) return;
          let that = this;
          that.pickerOptionsToday = {
            disabledDate(time) {
                 // 获取今天的日期
                const today = new Date();
                today.setHours(0, 0, 0, 0); // 设置时间为00:00:00，确保比较时只比较日期部分
                // 比较日期，禁用今天之前的日期
                return time.getTime() < today.getTime();
              },
            };
        },
        endDateFocus() {
          let startTime = this.taskForm.startTime;
          if (!startTime) return;
          let that = this;
          that.pickerOptionsStart = {
            disabledDate(time) {
              // 获取开始的日期
              const startTime=that.taskForm.startTime;
              const today = new Date(startTime);
              today.setHours(0, 0, 0, 0); // 设置时间为00:00:00，确保比较时只比较日期部分
              // 比较日期，禁用开始之前的日期
              return time.getTime() < today.getTime();
            },
          };
        },
        initStatistics(){
          let param = {}
          getStatisticsApi(param).then(response => {
            console.log("getStatisticsApi",response)
            if(response.code==200){
              this.statistics =response.data;
              console.log("this.statistics",this.statistics)
            }
          });
        },
        /** 查询用户列表 */
        getList() {
            this.loading = true
            listUser(this.queryParams).then(
                (response) => {
                    this.userList = response.rows
                    this.total = response.total
                    this.loading = false
                },
            )
        },
        /** 查询部门下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then((response) => {
                this.deptOptions = this.filterTree(response.data)
            })
        },
        filterTree(nodes) {
            return nodes
                .map((node) => {
                    if (node.children) {
                        node.children = this.filterTree(node.children)
                    }
                    return node
                })
                .filter((node) => node.status !== '1')
        },
        // 筛选节点
        filterNode(value, data) {
            if (!value) return true
            return data.label.indexOf(value) !== -1
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.queryParams.deptId = data.id
            this.handleQuery()
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.$refs.tree.setCurrentKey(null)
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            // 更新选中的roleId数组
            this.ids = selection.map((item) => item.userId)
            // 更新单选和多选状态
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },

        /** 远程校验按钮操作 */
        handleTask() {
            this.resetTask()
            this.openTask = true
        },
        // 取消按钮
        cancelTask() {
            this.openTask = false
            this.resetTask()
        },
        // 表单重置
        resetTask() {
            this.taskForm = {
                verificationDate:""
            }
            this.resetForm('taskForm')
        },
        /** 提交按钮 */
        submitTask: function () {
            this.$refs['taskForm'].validate((valid) => {
                let paramd = Object.assign({},this.taskForm)
                console.log(paramd)
                console.log(this.ids)
                if (valid) {
                  paramd.userIds=this.ids;
                  paramd.checkType="1";
                  let param={
                    verifyTitle:"无证核验",
                    startTime:"",
                    endTime:"",
                    verifyUsers:this.ids,
                    type:"100000",
                    verifyType:"1",
                    noticeType:"2",
                    processDate:''
                  }
                  addCertificateCheckApi(param).then(response => {
                    if(response.code=200){
                      this.$modal.msgSuccess("验证下发成功");
                      this.openTask = false;
                      this.getList();
                    }else{
                      this.$modal.msgError(response.msg);
                    }
                  });
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            // const userIds = row.userId || this.ids
            // this.$modal
            //     .confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
            //     .then(function () {
            //         return delUser(userIds)
            //     })
            //     .then(() => {
            //         this.getList()
            //         this.$modal.msgSuccess('删除成功')
            //     })
            //     .catch(() => {})
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'system/user/export2',
                {
                    ...this.queryParams,
                },
                `user_${new Date().getTime()}.xlsx`,
            )
        },
        //日期
        formatDate(sdate) {
            let date = new Date(sdate);
            // 格式化为 YYYY-MM-DD
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }
    },
}
</script>

<style lang="scss" scoped>
//隐藏图片上传框的css
::v-deep.disabled {
    .el-upload--picture-card {
        display: none;
    }
}
.disabled-row {
    background-color: #f5f7fa !important;
    color: #909399;
    cursor: not-allowed;
}

.disabled-row .el-checkbox__input {
    cursor: not-allowed !important;
}

.disabled-row:hover td {
    background-color: #f5f7fa !important;
}
</style>
