<template>
    <div class="bigBox">
        <section v-show='props.isShowTotal' ref="getHeight">
            <XgfryTotal :obj="pageData.listQuery" ref="aqqcTotal" :key="keys" />
        </section>
        <!-- 查询 -->
        <el-divider />
        <div class='tabox'>
            <section class="query-flex" ref="queryHeight">
                <section class="query-section">
                    <section class="flex">
                        <el-input placeholder="请输入姓名" v-model="pageData.listQuery.xm" clearable style='width:250px'
                            @keyup.enter="gettablist"></el-input>
                        <el-input class="ml12" placeholder="请输入身份证号" v-model="pageData.listQuery.idcard" clearable
                            style='width:250px' @keyup.enter="gettablist"></el-input>
                    </section>
                </section>
                <div class="query-btn">
                    <el-button @click="gettablist" class="ml6">
                        <el-icon>
                            <Search />
                        </el-icon>查询</el-button>
                    <el-button @click="handleRest">
                        <el-icon>
                            <Refresh />
                        </el-icon>重置</el-button>
                </div>
            </section>
            <el-divider />
            <section class="button">
                <!-- <el-button @click="addInfo" v-if='isAuth'>
                    <el-icon>
                        <Plus />
                    </el-icon>新增</el-button> -->
                <el-button @click="handleExport" v-loading="exportLoading" :disabled="pageData.tableData.length == 0">
                    <el-icon>
                        <Download />
                    </el-icon>导出</el-button>
            </section>
            <section :style="{ 'height': totalHeight }">
                <MOSTY.Table :table-columns="pageData.tableColumns" :tableData="pageData.tableData"
                    :tableloading="tableloading" :isSelect="false" :isSort="true" @SortChange="SortChange"
                    actionsW="280">
                    <template #sex="{ row }">
                        <dict-tag :options="D_BZ_XB" :value="row.sex" :tag="false" />
                    </template>
                    <template #zslx="{ row }">
                        <dict-tag :options="D_TB_XGFZSLB" :value="row.zslx" :tag="false" />
                    </template>
                    <template #orgname="{ row }">
                        <span>归口：{{ row.orgname }} {{ row.deptname || '' }}——属地：{{ row.belongOrgName + '' +
                            row.belongDeptName }}</span>
                    </template>
                    <template #actions="{ row }">
                        <section class="flexs">
                            <span class="operedit flexs" @click="editInfo(row)" v-if='isAuth'>
                                <el-icon>
                                    <EditPen />
                                </el-icon>编辑</span>
                            <el-popconfirm v-if='isAuth' confirm-button-text="是" cancel-button-text="否" icon-color="red"
                                title="确定要删除?" @confirm="handledelete(row)">
                                <template #reference>
                                    <span class="operdel flexs" size="small">
                                        <el-icon>
                                            <Delete />
                                        </el-icon>删除</span>
                                </template>
                            </el-popconfirm>
                            <span class="operesee flexs" @click="seeInfo(row)">
                                <el-icon>
                                    <View />
                                </el-icon>查看</span>
                            <span class="operesee flexs" v-if="row.accountFlag == '1'" @click="zhInfo(row)">
                                <el-icon>
                                    <Setting />
                                </el-icon>账号管理</span>
                        </section>
                    </template>
                </MOSTY.Table>
            </section>
            <div class="fenye">
                <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange"
                    :pageSizeArr="[15, 20, 50, 100]" @changeSize="handleSizeChange" />
            </div>
        </div>
    </div>
    <el-dialog v-model="centerDialogVisible" title="账号管理" width="600px" center :before-close="closeDialog">
        <el-form ref="ruleFormRef2" :model="zhFromobj" :rules="rules" :disabled="false" label-width="120px"
            class="demo-ruleForm" status-icon :inline="true" style="display: block;">
            <el-form-item label="登录账号:" prop="phone">
                <el-input v-model="zhFromobj.phone" @input="validateInput" clearable style='width:337px'
                    :maxlength="12"></el-input>
            </el-form-item>
            <el-form-item label="密码:" prop="userpwd">
                <el-input v-model="zhFromobj.userpwd" style='width:337px' @input="handleInput" placeholder="请输入密码">
                    <template #append>
                        <el-icon>
                            <View />
                        </el-icon>
                    </template>
                </el-input>
                <div class="input_span">
                    <span
                        :style="{ 'background-color': (msgText > 1 || msgText == 1) ? '#FC5F76' : '#BBBBBB', 'color': (msgText > 1 || msgText == 1) ? '#FC5F76' : '#BBBBBB' }">弱</span>
                    <span
                        :style="{ 'background-color': (msgText > 2 || msgText == 2) ? '#FF9900' : '#BBBBBB', 'color': (msgText > 2 || msgText == 2) ? '#FF9900' : '#BBBBBB' }">中</span>
                    <span
                        :style="{ 'background-color': (msgText > 3 || msgText == 3) ? '#33CC00' : '#BBBBBB', 'color': (msgText > 3 || msgText == 3) ? '#33CC00' : '#BBBBBB' }">强</span>
                </div>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitzh(ruleFormRef2)" v-loading='loadingshowzh'> <el-icon>
                        <DocumentChecked />
                    </el-icon>
                    <span>保存</span></el-button>
                <el-button @click="closeDialog"> <el-icon>
                        <DocumentDelete />
                    </el-icon>
                    <span>关闭</span></el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import * as MOSTY from "@/components/MyComponents/index";
import { reactive, ref, onMounted, getCurrentInstance, watch, computed, nextTick } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage, ElLoading } from "element-plus";
import { exportXlsx } from "@/excel/Export2Excel.js";
import { getItem } from "@/utils/storage";
import { getAuth } from "@/utils/tools.js";
import * as rule from "@/utils/rules.js";
import XgfryTotal from './XgfryTotal.vue'
const { proxy } = getCurrentInstance();
const { D_BZ_XB, D_TB_RELATED, D_TB_XGFZSLB, D_BZ_HZZT } = proxy.$dict("D_BZ_XB", "D_TB_RELATED", "D_TB_XGFZSLB", "D_BZ_HZZT");
const emits = defineEmits(["handleChange", 'searchChange', 'changePage']);
const props = defineProps({
    obj: {
        default: null,
        type: Object
    },
    type: {
        default: '',
        type: String
    },
    tableHeight: {
        default: '40vh',
        type: String
    },
    isShowTotal: {
        type: Boolean,
        default: false
    }
});
const zhFromobj = ref({})
const centerDialogVisible = ref(false)
const loadingshowzh = ref(false)
const ruleFormRef2 = ref()
const tableloading = ref(false);
const orgid = ref(getItem("deptId").ssdwid)
const isAuth = ref(true)
const getHeight = ref(null)
const queryHeight = ref(null)
const aqqcTotal = ref(null)
const keys = ref(0)
const exportLoading = ref(false);
const rules = reactive({
    ...rule.NoText({ require: true, validator: true }, "phone"),
    userpwd: [{ required: true, message: "请输入密码", trigger: "input" }]
});
const pageData = reactive({
    listQuery: {
        xm: '',
    },
    pageConfiger: {
        pageSize: 15,
        pageCurrent: 1,
        total: 0
    },
    tableColumns: [
        {
            title: "所属相关方",
            prop: "relatedname",
            width: '300',
            sortable: true
        },
        {
            title: "人员归口-属地详情",
            prop: "orgname",
            width: '600',
            slot: true,
            sortable: true
        },
        // {
        //     title: "归口管理单位",
        //     prop: "orgname",
        //     slot: true,
        //     sortable: true
        // },
        // {
        //     title: "归口管理部门",
        //     prop: "deptname",
        //     sortable: true
        // },
        // {
        //     title: "属地管理单位",
        //     prop: "belongOrgName",
        //     sortable: true,
        // },
        // {
        //     title: "属地管理部门",
        //     prop: "belongDeptName",
        //     sortable: true,
        // },
        {
            title: "姓名",
            prop: "xm",
            sortable: true
        },
        {
            title: "性别",
            prop: "sex",
            slot: true,
            sortable: true
        },
        // {
        //     title: "身份证号",
        //     prop: "idcard",
        //     sortable: true
        // },
        {
            title: "手机号码",
            prop: "mobile",
            sortable: true
        },
        // {
        //     title: "账号",
        //     prop: "phone",
        //     sortable: true
        // },
        // {
        //     title: "操作",
        //     prop: "actions",
        //     slot: true
        // }
    ],
    tableData: []
})
const msgText = ref('')
const totalHeight = ref(null)
watch(() => props.isShowTotal, (val) => {
    nextTick(() => {
        if (val) {
            totalHeight.value = `calc(100vh - ${338 + queryHeight.value.offsetHeight + getHeight.value.offsetHeight}px)`
            return
        }
        totalHeight.value = `calc(100vh - 370px)`
    })
}, {
    deep: true,
    immediate: true
})
onMounted(() => {

    isAuthorize()
})
watch(
    () => props.obj.orgid,
    (newValue) => {
        if (newValue) {
            pageData.listQuery.orgid = newValue
            orgid.value = props.obj.orgid
            gettablist()
        }

    },
    { deep: true, immediate: true }
);


function handleInput(val) {
    if (/[\u4e00-\u9fa5]/.test(val)) {
        // 密码中包含中文
        ElMessage.error('密码不符合要求');
    } else {
        const sz = /[0-9]/.test(val)//数字
        const xx = /[a-z]/.test(val)//小写
        const dx = /[A-Z]/.test(val)//大写
        const tszf = /\W/.test(val)//特殊字符
        const Isarr = [sz, xx, dx, tszf].filter(item => { return item == true })
        const strongRegex = /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,}$/;
        if (strongRegex.test(val) || Isarr.length >= 3) {
            msgText.value = 3
        } else if (Isarr.length >= 2) {
            msgText.value = 2
        } else {
            msgText.value = 1
        }
    }
}
//排序
function SortChange(prop, order) {
    pageData.listQuery.sortField = prop
    pageData.listQuery.sortOrder = order
    gettablist()
}

const closeDialog = () => {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？').then(() => {
        centerDialogVisible.value = false
    })
};
// 是否可以操作
const isAuthorize = async () => {
    isAuth.value = await getAuth()
}
//账号管理
function zhInfo(val) {
    zhFromobj.value = JSON.parse(JSON.stringify(val))
    centerDialogVisible.value = true
    handleInput(zhFromobj.value.userpwd)
}
// 导出
const handleExport = () => {
    const loading = ElLoading.service({
        lock: true,
        text: '导出中...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    let title = {
        relatedname: "所属相关方",
        orgname: "归口管理单位",
        deptname: "归口管理部门",
        xm: "姓名",
        sex: "性别",
        idcard: "身份证号",
        mobile: "手机号码",
        phone: "账号"
    };
    const params = {
        pageCurrent: 1,
        pageSize: 10999,
    };
    getApi(params, "/mosty-jcgl/relatedUser/getPageList").then((res) => {
        if (res.records) {
            let data = res.records;
            if (data) {
                for (let i = 0; i < data.length; i++) {
                    data[i].sex = proxy.$getDictVal(data[i].sex, D_BZ_XB);
                    data[i].zslx = proxy.$getDictVal(data[i].zslx, D_TB_XGFZSLB);
                }
                let tablename = "相关方人员信息列表.xlsx";
                exportXlsx(title, data, '相关方人员信息列表', tablename);
            }
        }
    }).finally(() => {
        loading.close()
    })
}
// 重置过滤条件
const handleRest = () => {
    pageData.listQuery.xm = ''
    pageData.listQuery.idcard = ''
    pageData.listQuery.relatedid = ''
    pageData.pageConfiger.pageCurrent = 1
    gettablist()
}

//相关方人员分页查询
function gettablist() {
    tableloading.value = true
    // 保证能查询出本级
    pageData.listQuery.type = "01"
    getApi({ ...pageData.pageConfiger, ...pageData.listQuery }, "/mosty-jcgl/relatedUser/getPageList").then((res) => {
        if (res) {
            keys.value++
            tableloading.value = false
            pageData.tableData = res.records
            pageData.pageConfiger.total = res.total
        }
    })
}
//新增
const addInfo = () => {
    let arr = {
        title: "相关方人员新增",
        saveBtnShow: true,
        orgid: props.obj.orgid,
        zdlist: { D_BZ_XB, D_TB_XGFZSLB }
    };
    emits("changePage", "Details", arr);
};
//修改
const editInfo = (row) => {
    let arr = {
        title: "相关方人员编辑",
        saveBtnShow: true,
        avtivityBtnShow: true,
        id: row.id ? row.id : null,
        orgid: props.obj.orgid,
        zdlist: { D_BZ_XB, D_TB_XGFZSLB }
    };
    emits("changePage", "Details", arr);
};
//查看
const seeInfo = (row) => {
    let arr = {
        title: "相关方人员详情",
        saveBtnShow: false,
        avtivityBtnShow: false,
        id: row.id ? row.id : null,
        orgid: props.obj.orgid,
        zdlist: { D_BZ_XB, D_TB_XGFZSLB }
    };
    emits("changePage", "Details", arr);
};
//注销
function handledelete(row) {
    postApi({}, `/mosty-jcgl/relatedUser/del/${row.id}`).then(res => {
        ElMessage.success("删除成功");
        gettablist()
    })
}
//页码发生变化
const handleCurrentChange = (val) => {
    pageData.pageConfiger.pageCurrent = val;
    gettablist()
};
//查询条数发生变化
const handleSizeChange = (val) => {
    pageData.pageConfiger.pageSize = val;
    gettablist()
};
// 保存
const submitzh = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (zhFromobj.value.accountFlag == '1' && zhFromobj.value.phone.length < 3) {
                ElMessage.error('登录账号长度不能低于3位');
            } else if (zhFromobj.value.accountFlag == '1' && zhFromobj.value.userpwd.length < 8) {
                ElMessage.error('密码长度不能低于8位');
            } else if (zhFromobj.value.accountFlag == '1' && msgText.value != 3) {
                ElMessage.error("密码必须满足强密码要求!");
            } else {
                loadingshowzh.value = true
                postApi(zhFromobj.value, "/mosty-jcgl/relatedUser/edit").then(() => {
                    ElMessage.success("修改成功");
                    centerDialogVisible.value = false
                    gettablist()
                }).finally(() => {
                    loadingshowzh.value = false
                })
            }
        } else {
            ElMessage.error("请输入必填项!");
        }
    });
};
</script>

<style lang="scss" scoped>
::v-deep .el-divider--horizontal {
    margin: 12px 0;
}


.query-flex {
    display: flex;
    justify-content: space-between;

    .query-section {
        width: 68%;
    }

    .query-btn {
        width: 240px;
        display: flex;
        justify-content: flex-end;

        .toggle {
            height: 32px;
            cursor: pointer;
            display: flex;
            align-items: center;
            color: #0f3916;

            .el-icon {
                transform: rotate(90deg);
                transition: all 0.25s ease;
            }

            &.active {
                .el-icon {
                    transform: rotate(-90deg);
                }
            }
        }
    }
}

.button {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-bottom: 12px;
}

.flexs {
    display: flex;
    align-items: center;
}

.input_span {
    height: 8px;
    display: flex;
    width: 35%;

    span {
        display: inline-block;
        width: 30%;
        border-radius: 8px;
        margin-right: 3px;
        text-align: center;
        margin-top: 3px;
    }
}
</style>
