<template>
  <div>
    <MOSTY.PageTree :pageTitle="'停用账号管理'" :isShowLeftTree="false">
      <template #serach>
        <el-divider />
        <MOSTY.Search :searchArr="searchArr" @submit="handleFilter" />
        <el-divider />
        <!-- <div class="btnBox">
          <el-button type="primary" @click="addUserHander">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
        </div> -->
      </template>
      <template #table>
        <div class="main-box">

          <div class="tabBox ml10" style="height: calc(100vh - 350px)">
            <el-table :data="tableData" border stripe style="width: 100%" :height="'100%'" :key="keyCount"
              v-loading="loading">
              <el-table-column sortable prop="userName" align="center" label="用户名"></el-table-column>
              <el-table-column sortable prop="loginName" align="center" label="账号"></el-table-column>
<!--              <el-table-column sortable prop="idEntityCard" align="center" label="身份证号"></el-table-column>-->
<!--              <el-table-column sortable prop="mobile" align="center" label="电话号码">-->
<!--                <template #default="{ row }">-->
<!--                  <span>{{ maskPhone(row.mobile) }}</span>-->
<!--                </template>-->
<!--              </el-table-column>-->
              <el-table-column align="center" sortable label="性别" width="80">
                <template #default="{ row }">
                  <dict-tag :options="D_BZ_XB" :value="row.sex" :tag="false" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" fixed="right" width="300">
                <template #default="{ row }">
                  <el-button @click="updateDict(row)" size="small">修改</el-button>
                  <el-button @click="enableRole(row)" size="small">移入</el-button>
                  <el-popconfirm v-if="getItem('USERID') == '000000'" confirm-button-text="是" cancel-button-text="否"
                    icon-color="red" title="确定要删除?" @confirm="delRole(row)">
                    <template #reference>
                      <el-button type="danger" size="small">删除</el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
            <div class="fenye">
              <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="listQuery.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.pageSize"
                layout="total, prev, pager, next, sizes, jumper" :total="total"></el-pagination>
            </div>
          </div>
        </div>
      </template>
    </MOSTY.PageTree>

    <!-- 弹窗 -->
    <div v-if="dialogFormVisible" class="dialog">
      <MOSTY.FromPage :title="isEdit ? '修改' : '新增'" @closeDialog="closeDialog">
        <template #content>
          <el-form class="mosty-from-wrap" ref="elform" :model="dialogForm" :inline="true" label-position="top"
            :rules="rules">
            <el-form-item label="部门:" prop="deptIds">
              <MOSTY.Department style="width: 100%" :searchType="'01'" placeholder="请选择部门" clearable :deptType="'01'"
                v-model="dialogForm.deptIds" />
            </el-form-item>
            <el-form-item label="聘用人员类别:" prop="outsourcingLevel">
              <MOSTY.DictRidioAndSelect selectType="select" :dictData="D_BZ_ZYWHRYLB"
                v-model="dialogForm.outsourcingLevel" :disabledItem="['2', '3']" />
            </el-form-item>
            <el-form-item label="岗位:" prop="positionName">
              <el-input v-model="dialogForm.positionName" readonly placeholder="请选择岗位"
                @click="showGwxz = true"></el-input>
            </el-form-item>
            <el-form-item label="职务:" prop="dutyName" v-if="dialogForm.outsourcingLevel == '1'">
              <el-input v-model="dialogForm.dutyName" readonly placeholder="请选择职务" @click="showZwxz = true"></el-input>
            </el-form-item>
            <el-form-item label="用户名:" prop="userName">
              <MOSTY.Other width="100%" placeholder="请输入用户名" clearable v-model="dialogForm.userName" />
            </el-form-item>
            <el-form-item label="登录账号:" prop="loginName">
              <el-input placeholder="请输入账号" v-model="dialogForm.loginName" type='text' clearable
                width="100%"></el-input>
            </el-form-item>
            <el-form-item label="密码:" v-if="!isEdit" prop="password">
              <el-input v-model="dialogForm.password" width="100%" @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-item label="身份证号" prop="idEntityCard">
              <MOSTY.IdentityCard width="100%" v-model="dialogForm.idEntityCard" @change="fn" clearable>
              </MOSTY.IdentityCard>
            </el-form-item>
            <el-form-item label="用户类型:" prop="userType">
              <MOSTY.DictRidioAndSelect selectType="select" :dictData="D_ORG_USERTYPE" v-model="dialogForm.userType"
                placeholder="请选择用户类型" />
            </el-form-item>
            <el-form-item label="电话号码:" prop="telePhone">
              <MaskInput v-model="dialogForm.telePhone" placeholder="请输入电话号码" style="width: 337px" />
            </el-form-item>
            <el-form-item label="移动电话:" prop="mobile">
              <MaskInput v-model="dialogForm.mobile" placeholder="请输入移动电话" style="width: 337px" />
            </el-form-item>
            <!-- <el-form-item label="电话号码:" prop="telePhone">
              <el-input v-model="dialogForm.telePhone" clearable />
            </el-form-item>
            <el-form-item label="移动电话:" prop="mobile">
              <el-input v-model="dialogForm.mobile" clearable type="number" />
            </el-form-item> -->
            <el-form-item label="民族:" prop="nation">
              <MOSTY.PackageSelect v-model="dialogForm.nation" dictEnum="NATION" clearable filterable
                style="width: 100%" />
            </el-form-item>
            <el-form-item label="性别:" prop="sex">
              <el-select style="width: 100%" v-model="dialogForm.sex" placeholder="请选择性别">
                <el-option v-for="(item, index) in D_BZ_XB" :key="index" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="文化程度:" prop="whcd">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_AQRYWHCD" v-model="dialogForm.whcd" selectType="select"
                placeholder="请选择文化程度" />
            </el-form-item>
            <el-form-item label="E-mail" prop="email">
              <el-input v-model="dialogForm.email" clearable />
            </el-form-item>
            <el-form-item label="出生日期：" prop="birthday">
              <el-date-picker v-model="dialogForm.birthday" style="width: 100%" type="data" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="请选择出生日期" :default-value="getDefaultDates"
                :disabled-date="disabledDate">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="政治面貌:" prop="politic">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_AQRYZZMM" v-model="dialogForm.politic" selectType="select"
                placeholder="请选择政治面貌" />
            </el-form-item>
            <el-form-item label="婚姻状况:" prop="marital">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_HYZK" v-model="dialogForm.marital" selectType="select"
                placeholder="请选择婚姻状况" />
            </el-form-item>
            <!-- <el-form-item label="人员类别:">
              <MOSTY.DictRidioAndSelect :dictData="D_ZDY_RYLB" v-model="dialogForm.type" selectType="select"
                placeholder="请选择人员类别" />
            </el-form-item> -->
            <el-form-item label="是否长期病假离岗人员:">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_SF" v-model="dialogForm.longTermSickLeave" selectType="select"
                placeholder="请选择是否长期病假离岗人员" />
            </el-form-item>

            <el-form-item style="width: 100%" label="备注">
              <el-input v-model="dialogForm.bz" show-word-limit maxlength="200" :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"></el-input>
            </el-form-item>
          </el-form>
        </template>
        <template #footer>

          <!-- 修改 -->
          <el-button v-if="isEdit" type="primary" @click="onSave" :loading="buttonLoading">修改</el-button>
          <el-button v-else-if="isEnableRole" type="primary" @click="enableSysUserRole" :loading="buttonLoading">移入</el-button>
          <!-- 新增 -->
          <el-button v-else type="primary" @click="onAdd">保存</el-button>
          <el-button @click="closeDialog">关闭</el-button>
        </template>
      </MOSTY.FromPage>


    </div>
    <!-- 岗位选择 -->
    <Gwxz v-model="showGwxz" @change="changeGwxz" />
    <!-- 职位选择 -->
    <Zwxz v-model="showZwxz" @change="changeZwxz" />

  </div>
</template>

<script setup>
import Gwxz from "@/views/systemConfig/user-list/components/Gwxz.vue"
import Zwxz from "@/views/systemConfig/user-list/components/Zwxz.vue"
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus";
import { filterqx } from "@/utils/auth.js";
import * as rule from "@/utils/rules.js";
import { getItem } from "@/utils/storage";
import MaskInput from "@/components/MaskInput.vue"
import { ref, watch, onMounted, getCurrentInstance, onUnmounted, reactive } from "vue";
import {
  getSysUserList,
  editSysUser,
  addUser,
  getUserInfoToId,
  gettyzhUserList,
  deleteSysUser,
  enableSysUser
} from "@/api/user-manage"
const { proxy } = getCurrentInstance();
const { D_BZ_SF, D_BZ_XB, D_ZDY_XNYH, D_ZDY_RYLB, D_BZ_HYZK, D_BZ_AQRYZZMM, D_ORG_USERTYPE, D_BZ_ZYWHRYLB, D_BZ_AQRYWHCD } =
  proxy.$dict("D_BZ_SF", "D_BZ_XB", "D_ZDY_XNYH", "D_ZDY_RYLB", "D_BZ_HYZK", "D_BZ_AQRYZZMM", "D_ORG_USERTYPE", "D_BZ_ZYWHRYLB", "D_BZ_AQRYWHCD");
const showZwxz = ref(false);
const showGwxz = ref(false);
const keyCount = ref(0); //tabel组件刷新值
const loading = ref(false)
const searchArr = reactive([

  {
    showType: "input",
    label: '用户名:',
    prop: "userName",
    width: '250px',
    placeholder: '请输入用户名或者账号'
  }
]);
const rules = ref({
  userName: [{ required: true, message: "请填写用户名" }],
  loginName: [{ required: true, message: "请填写登录账号" }],
  userType: [{ required: true, message: "请选择用户类型" }],
  sex: [{ required: true, message: "请选择性别" }],
  birthday: [{ required: false, message: "请选择出生日期" }],
  password: [{ required: true, message: "请填写密码" }],
  deptIds: [{ required: true, message: "请选择部门" }],
  inDustRialId: [{ required: true, message: "请填写警号" }],
  managerOrgId: [{ required: true, message: "请选择岗位" }],
  isVirtualUser: [{ required: true, message: "请选择虚拟用户" }],
  outsourcingLevel: [{ required: true, message: "请选择聘用人员类别" }],
  ...rule.identityCardRule({ require: false, validator: true }, "idEntityCard"),
  // ...rule.phoneRule({ validator: true, require: false }, "telePhone"),
  // ...rule.phoneRule({ validator: true, require: true }, "mobile"),
  telePhone: [{ required: false, max: 13, message: "电话号码格式不正确", trigger: "blur" }],
  mobile: [{ required: false, max: 11, message: "移动电话格式不正确", trigger: "blur" }],
  ...rule.emailRule({ validator: true, require: false, }, "email"),
  type: [{ required: true, message: "请输入人员类别" }],
  dutyName: [{ required: true, message: "请选择职务" }],
  positionName: [{ required: true, message: "请选择岗位" }],
  packageSelect: [{ required: true, message: "请选择", trigger: "change" }],
  other: [{ required: true, message: "自由发挥", trigger: "blur" }],

});
const elform = ref(null);
// const title = ref("");
const buttonLoading = ref(false);
//查询参数
const total = ref(0);
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 10,
  userName: "",
});
const isEdit = ref(true);
const isEnableRole = ref(true);
const dialogForm = ref({
  userName: "",
  deptIds: [],
  outsourcingLevel: '1',// 定死为“在册在岗”
});
const msgText = ref('')
// 数据相关
const tableData = ref([]);
const dialogFormVisible = ref(false);
onMounted(() => {
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
  getListData()
});
// 电话号码脱敏函数：保留前三后四，中间用****
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 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
    }
  }
}
//选择岗位
const changeGwxz = (val) => {
  dialogForm.value.positionId = val.id
  dialogForm.value.positionName = val.name
  showGwxz.value = false
}
//选择职务
const changeZwxz = (val) => {
  dialogForm.value.dutyCode = val.dutyCode
  dialogForm.value.dutyName = val.dutyName
  showZwxz.value = false
}
// 获取数据的方法
const getListData = async () => {

  loading.value = true
  const params = listQuery.value;
  const res = await gettyzhUserList(params).finally(() => {
    loading.value = false
  });

  if (res && res.records) {
    res.records.forEach(item => {
      if (item.idEntityCard && item.idEntityCard.length >= 2) {
        item.sex = Number(item.idEntityCard.substring(item.idEntityCard.length - 2, item.idEntityCard.length - 1)) % 2 == 0 ? '2' : '1'
      }
    });
  }
  tableData.value = res?.records;
  total.value = Number(res.total);

};

const delRole = (row) => {
  deleteSysUser({ id: row.id, type: '01' }).then(() => {
    ElMessage.success("删除成功");
    handleFilter();
  });
};
const handleFilter = (obj) => {
  if (obj) {
    listQuery.value.userName = obj.userName ? obj.userName : null
  }
  listQuery.value.pageCurrent = 1;
  getListData();
};
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getListData();
};
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  getListData();
};
/**修改字典 */
const updateDict = async (row) => {
  getUserInfoToId(row.id).then((res) => {
    dialogForm.value = res;
    dialogForm.value.loginName = res.loginName;
    dialogForm.value.nation = res.nation;
    dialogForm.value.isVirtualUser = res.isVirtualUser;
    isEnableRole.value = false;
    isEdit.value = true;
    // title.value = "修改用户信息";
    dialogFormVisible.value = true;
  });
};

/**修改字典 */
const enableRole = async (row) => {
  getUserInfoToId(row.id).then((res) => {
    dialogForm.value = res;
    dialogForm.value.loginName = res.loginName;
    dialogForm.value.nation = res.nation;
    dialogForm.value.isVirtualUser = res.isVirtualUser;
    isEnableRole.value = true;
    isEdit.value = false;
    // title.value = "移入用户";
    dialogFormVisible.value = true;
  });
};
//身份证号计算出生日期
function getBirthdayFromIdCard(idCard) {
  var birthday = "";
  if (idCard != null && idCard != "") {
    if (idCard.length == 15) {
      birthday = "19" + idCard.substr(6, 6);
    } else if (idCard.length == 18) {
      birthday = idCard.substr(6, 8);
    }
    birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
  }
  return birthday;
}
function fn(e) {
  let text = 0;
  if (e.length >= 17) {
    dialogForm.value.birthday = getBirthdayFromIdCard(e);
    text = e[e.length - 2] * 1;
    if (text % 2 === 0) {
      dialogForm.value.sex = "2";
    } else {
      dialogForm.value.sex = "1";
    }
  }
}


const addUserHander = () => {
  isEdit.value = false;
  dialogForm.value = {};
  dialogForm.value.loginName = null
  dialogForm.value.password = null
  dialogForm.value.outsourcingLevel = "1"
  dialogFormVisible.value = true;
};
const onSave = () => {
  elform.value.validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      if (typeof dialogForm.value.deptIds == 'string') {
        dialogForm.value.deptIds = dialogForm.value.deptIds.split(',')
        dialogForm.value.deptIds = dialogForm.value.deptIds[dialogForm.value.deptIds.length - 1]
      } else if (Array.isArray(dialogForm.value.deptIds)) {
        dialogForm.value.deptIds = dialogForm.value.deptIds[dialogForm.value.deptIds.length - 1]
      }
      dialogForm.value.deptIds = [dialogForm.value.deptIds]
      editSysUser(dialogForm.value).then(() => {
        dialogFormVisible.value = false;
        ElMessage.success("修改成功");
        buttonLoading.value = false;
        handleFilter();
      }).finally(() => {
        buttonLoading.value = false;
      });
    } else {
      ElMessage.error("请填写完必填项!");
      return false;
    }
  });
};

const enableSysUserRole = () => {
  elform.value.validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      if (typeof dialogForm.value.deptIds == 'string') {
        dialogForm.value.deptIds = dialogForm.value.deptIds.split(',')
        dialogForm.value.deptIds = dialogForm.value.deptIds[dialogForm.value.deptIds.length - 1]
      } else if (Array.isArray(dialogForm.value.deptIds)) {
        dialogForm.value.deptIds = dialogForm.value.deptIds[dialogForm.value.deptIds.length - 1]
      }
      dialogForm.value.deptIds = [dialogForm.value.deptIds]
      enableSysUser(dialogForm.value).then(() => {
        dialogFormVisible.value = false;
        ElMessage.success("启用成功");
        buttonLoading.value = false;
        handleFilter();
      }).finally(() => {
        buttonLoading.value = false;
      });
    } else {
      ElMessage.error("请填写完必填项!");
      return false;
    }
  });
};

//新增人员
const onAdd = () => {
  elform.value.validate((valid) => {
    if (valid) {
      dialogForm.value.deptIds = Array.isArray(dialogForm.value.deptIds) ? dialogForm.value.deptIds : dialogForm.value.deptIds.split(',');
      buttonLoading.value = true;
      if (dialogForm.value.password.length < 8) {
        ElMessage.error('密码长度不能低于8位');
      } else if (msgText.value != 3) {
        ElMessage.error("密码必须满足强密码要求!");
      } else {
        addUser(dialogForm.value).then((res) => {
          dialogFormVisible.value = false;
          ElMessage.success("新增成功");

          handleFilter();
        }).finally(() => {
          dialogForm.value.deptIds = dialogForm.value.deptIds ? dialogForm.value.deptIds[0] : null;
          buttonLoading.value = false;
        })
      }

    } else {
      ElMessage.error("请填写完必填项!");
      return false;
    }
  });
};



const closeDialog = () => {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      dialogForm.value = {};
      dialogForm.value.loginName = null
      dialogForm.value.password = null
      dialogFormVisible.value = false;
    })
    .catch(() => {
      // catch error
    })

};




onUnmounted(() => {
  proxy.mittBus.off("mittFn");
});
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";


.treeBox {
  overflow: auto;
  height: calc(100vh - 330px);
}

::v-deep .el-form {
  flex-wrap: wrap;
}

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

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

.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}
</style>
