<template>
    <div>
        <!-- 查询 -->
        <div class='tabox'>
            <div class="headBox">
                <MOSTY.Search :searchArr="searchArr" @submit="onSearch" />
                <el-button type="primary" @click="addUserHander" v-if='props.isEdit'>
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <span>新增</span>
                </el-button>
            </div>
            <MOSTY.Table :table-columns="pageData.tableColumns" :tableData="pageData.tableData" :key="inkey"
                :tableloading="tableloading" :tableHeight="'40vh'" :isSort="true">
                <template #sex="{ row }">
                    <dict-tag :options="D_BZ_XB" :value="row.sex" :tag="false" />
                </template>
                <template #zslx="{ row }">
                    <dict-tag :options="D_TB_ZSLB" :value="row.zslx" :tag="false" />
                </template>
                <template #mobile="{ row }">
                    <span>{{ maskPhone(row.mobile) }}</span>
                </template>
                <template #actions="{ row }">
                    <span class="operedit flexs" @click="editInfo(row)" v-if='isAuth && isEdit'>
                        <el-icon>
                            <EditPen />
                        </el-icon>编辑</span>
                    <el-popconfirm v-if='isAuth && isEdit' 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' && isEdit" @click="zhInfo(row)">
                        <el-icon>
                            <Setting />
                        </el-icon>账号管理</span>
                </template>
            </MOSTY.Table>
            <div class="fenye">
                <MOSTY.Pages :pageSizeArr="[8, 10, 20, 50, 100]" :pageConfiger="pageData.pageConfiger"
                    @changeNo="handleCurrentChange" @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>
    <!-- 选择相关方人员 -->
    <xgfryadd v-model="chooseUserVisible" :Single="false" :data="memberList" :leaderid="leaderid"
        :relatedid="props.obj.id" :editObj="editObj" :obj="props.obj" @choosedUsers="getSonValue">
    </xgfryadd>
</template>
<script setup>
import * as MOSTY from "@/components/MyComponents/index";
import { reactive, ref, onMounted, getCurrentInstance, watch, nextTick } from "vue";
import { postApi, getApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import xgfryadd from "./tab/xgfryadd.vue";

const { proxy } = getCurrentInstance();
const { D_TB_ZSLB, D_BZ_XB, D_BZ_JHZT, D_TB_XGFZSLB } = proxy.$dict("D_TB_ZSLB", "D_BZ_XB", "D_BZ_JHZT", "D_TB_XGFZSLB");

const emits = defineEmits(["handleChange", "searchChange"]);
const props = defineProps({
    relatedtype: {
        default: () => ({}),
        type: Object,
    },
    obj: {
        default: () => ({}),
        type: Object,
    },
    // 是否可以编辑
    isEdit: {
        type: Boolean,
        default: true,
    },
});
const searchArr = reactive([
    {
        showType: "input",
        prop: "xm",
        width: '250px',
        placeholder: "请输入姓名查询"
    },
    {
        showType: "cascader",
        prop: "belongOrgId",
        placeholder: "请选择属地管理单位",
        width: '250px',
        showAllLevels: false,
        props: {
            children: "children",
            label: "orgname",
            value: "orgcode",
            checkStrictly: false
        },
        lazy: false,
        options: [],
        checkStrictly: false
    }
]);
const inkey = ref(1);
const tableloading = ref(false);
const chooseUserVisible = ref(false);
const memberList = ref([]);
const leaderid = ref("");
const pageData = reactive({
    listQuery: {
        pageCurrent: 1,
        pageSize: 5,
        id: props.obj.id,
    },
    pageConfiger: {
        pageSize: 8,
        pageCurrent: 1,
        total: 0,
    },
    tableColumns: [
        // {
        //     title: "所属相关方",
        //     prop: "relatedname",
        //     sortable: true,
        // },
        // {
        //     title: "归口管理单位",
        //     prop: "orgname",
        //     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,
            slot: true,
        },
        // {
        //     title: "账号",
        //     prop: "phone",
        //     sortable: true,
        // },
        {
            title: "操作",
            prop: "actions",
            slot: true,
        },
    ],
    tableData: [],
});
const msgText = ref(0); // 密码强度指示器（数字）
const isAuth = ref(true); // 是否可操作（留着可通过外部逻辑设置）
const zhFromobj = ref({}); // 账号管理表单数据
const centerDialogVisible = ref(false);
const ruleFormRef2 = ref();
const loadingshowzh = ref(false);
const onSearch = (obj) => {
    pageData.listQuery.xm = obj.xm || '';
    pageData.listQuery.belongOrgId = obj.belongOrgId ? obj.belongOrgId[obj.belongOrgId.length - 1] : "";
    pageData.listQuery.pageCurrent = 1;
    getzblist();
};

onMounted(() => {
    if (props.isEdit) {
        inkey.value++;
    } else {
        inkey.value++;
    }
    // 获取筛选条件
    getSelectBelongOrgId()
    // 首次获取列表
    getzblist();
});


watch(
    () => props.obj.id,
    (newVal) => {
        if (newVal) {
            pageData.listQuery.id = newVal;
            // 同步 pageConfiger 的 id（如需要）
            pageData.pageConfiger.pageCurrent = 1;
            getzblist();
        }
    },
    { immediate: true }
);
const getSelectBelongOrgId = () => {
    getApi({ type: '03' }, "/mosty-base/deptFeign/getTempDeptAndJgbm")
        .then((res) => {
            if (res && res.length > 0) {
                searchArr[1].options = res
            }
        });
}
function getzblist() {
    tableloading.value = true;

    const params = {
        ...pageData.listQuery,
        pageCurrent: pageData.pageConfiger.pageCurrent,
        pageSize: pageData.pageConfiger.pageSize,
    };
    getApi(params, "/mosty-jcgl/relatedpartyinfo/getRelatedUserPage")
        .then((res) => {
            pageData.tableData = res.records ? res.records : [];
            memberList.value = res.records ? res.records.map((item) => item.id) : [];
            pageData.pageConfiger.total = res.total || 0;
        })
        .finally(() => {
            tableloading.value = false;
        });
}
const editObj = ref({});
// 新增弹窗
function addUserHander() {
    editObj.value = {
        title: "相关方人员新增",
        id: null,
        saveBtnShow: true,
        orgid: props.obj.orgid,
        zdlist: { D_BZ_XB, D_TB_XGFZSLB },
    };
    chooseUserVisible.value = true;
}
// 电话号码脱敏函数：保留前三后四，中间用****
const maskPhone = (num) => {
    if (!num) return ""
    const str = String(num)
    if (str.length < 7) return str // 太短不脱敏
    return str.replace(/^(\d{3})\d{4}(\d+)$/, "$1****$2")
}
// 账号管理
function zhInfo(val) {
    zhFromobj.value = JSON.parse(JSON.stringify(val || {}));
    centerDialogVisible.value = true;
    handleInput(zhFromobj.value.userpwd || "");
}
const closeDialog = () => {
    centerDialogVisible.value = false;
}
// 密码强度检测
function handleInput(val) {
    if (!val) {
        msgText.value = 0;
        return;
    }
    if (/[\u4e00-\u9fa5]/.test(val)) {
        // 密码中包含中文，提示并视为弱
        ElMessage.error("密码不符合要求");
        msgText.value = 1;
        return;
    }
    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) => 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;
    }
}
// 详情数据
const infoData = ref([])
// 修改
const editInfo = (row) => {
    editObj.value = {
        title: "相关方人员编辑",
        id: row.id ? row.id : null,
        saveBtnShow: true,
        orgid: props.obj.orgid,
        zdlist: { D_BZ_XB, D_TB_XGFZSLB },
    };
    infoData.value = []
    infoData.value.push(row)
    chooseUserVisible.value = true;
};
// 查看
const seeInfo = (row) => {
    editObj.value = {
        title: "相关方人员详情",
        id: row.id ? row.id : null,
        saveBtnShow: false,
        orgid: props.obj.orgid,
        zdlist: { D_BZ_XB, D_TB_XGFZSLB },
    };
    infoData.value = []
    infoData.value.push(row)
    chooseUserVisible.value = true;
};

// 删除
function handledelete(row) {
    postApi({}, `/mosty-jcgl/relatedUser/del/${row.id}`).then(res => {
        ElMessage.success("删除成功");
        getzblist()
    })
}

function getSonValue(value) {
    if (value) getzblist();
}

// 页码发生变化
const handleCurrentChange = (val) => {
    pageData.pageConfiger.pageCurrent = val;
    pageData.listQuery.pageCurrent = val;
    getzblist();
};

// 查询条数发生变化
const handleSizeChange = (val) => {
    pageData.pageConfiger.pageSize = val;
    pageData.listQuery.pageSize = val;
    getzblist();
};

// 账号管理弹窗
const submitzh = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid) => {
        if (valid) {
            // 账号存在且校验
            if (zhFromobj.value.accountFlag == "1" && zhFromobj.value.phone && zhFromobj.value.phone.length < 3) {
                ElMessage.error("登录账号长度不能低于3位");
                return;
            }
            if (zhFromobj.value.accountFlag == "1" && zhFromobj.value.userpwd && zhFromobj.value.userpwd.length < 8) {
                ElMessage.error("密码长度不能低于8位");
                return;
            }
            if (zhFromobj.value.accountFlag == "1" && msgText.value != 3) {
                ElMessage.error("密码必须满足强密码要求!");
                return;
            }
            loadingshowzh.value = true;
            postApi(zhFromobj.value, "/mosty-jcgl/relatedUser/edit")
                .then(() => {
                    ElMessage.success("修改成功");
                    centerDialogVisible.value = false;
                    getzblist();
                })
                .finally(() => {
                    loadingshowzh.value = false;
                });
        } else {
            ElMessage.error("请输入必填项!");
        }
    });
};
</script>


<style lang="scss" scoped>
.headBox {
    display: flex;
    justify-content: space-between;
    width: 100%;
    margin-bottom: 10px;
}

.top_ul {
    display: flex;
    justify-content: start;
    flex-wrap: wrap;

    >li {
        width: 15%;
        height: 83px;
        margin: 6px 32px;
    }
}
</style>