<template>
  <Layout :class="prefixCls" v-bind="lockEvents">
    <!-- <LayoutFeatures /> -->
    <LayoutHeader />
    <Layout :class="[layoutClass]">
      <!-- 左边 -->
      <LayoutSideBar v-if="menus?.menus?.title != '首页' && menus?.menus?.title != '待办事项' && menus?.menus?.title != '空间一张图'" />
      <!-- 左边结束 -->
      <Layout
        :class="`${prefixCls}-main`"
        class="fixed right-0 bottom-0 top-[60px] overflow-auto"
        style="height: calc(100% - 60px)"
        :style="`width:${
          menus?.menus?.title != '首页' && menus?.menus?.title != '待办事项' && menus?.menus?.title != '空间一张图' ? 'calc(100% - 213px)' : '100vw'
        }`"
      >
        <LayoutMultipleHeader v-if="menus?.menus?.title != '首页' && menus?.menus?.title != '待办事项' && menus?.menus?.title != '空间一张图'" />
        <LayoutContent />
        <LayoutFooter />
      </Layout>
    </Layout>
    <a-modal
      v-model:visible="open"
      :centered="false"
      :closable="false"
      :keyboard="false"
      style="width: 40%"
      :maskClosable="false"
      :title="openTitle"
    >
      <div class="h-80">
        <p class="text-[#FBAF35] text-center py-2"
          >您是首次登录系统，为了您的安全，请修改初始密码。 新密码必须包括大小写字母、特殊符号、数字且密码长度不能小于8位
          特殊符号包含：!@#$%^&*_-{}</p
        >
        <BasicForm @register="registerForm" >
          
          <template #phone="{model, field}">
            <a-input v-model:value="model[field]" placeholder="请输入手机号" />
              <span style="color:#fbaf35">此手机号用于接收短信，请注意填写！</span>
          </template>
        </BasicForm>
        
      </div>

      <template #footer>
        <a-button type="primary" @click="handleSubmit">确定</a-button>
      </template>
    </a-modal>
    <a-modal
      v-model:visible="userqx"
      :centered="false"
      :closable="false"
      :keyboard="false"
      style="width: 40%"
      :maskClosable="false"
      title="用户权限有问题"
    >
      <div class="h-80">
        <p class="text-[#FBAF35] text-center py-2">请联系管理员修改用户权限问题</p>
      </div>

      <template #footer> </template>
    </a-modal>
  </Layout>
</template>

<script lang="ts">
  import { defineComponent, computed, unref, toRef, watch, ref } from 'vue';
  import { rules } from '/@/utils/helper/validator';
  import { Layout } from 'ant-design-vue';
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import menusStore from '/@/store/menu';
  import { useSplitMenu } from '/@/layouts/default/menu/useLayoutMenu';
  import LayoutHeader from './header/index.vue';
  import LayoutContent from './content/index.vue';
  import LayoutSideBar from './sider/index.vue';
  import LayoutMultipleHeader from './header/MultipleHeader.vue';
  import { useRoute } from 'vue-router';
  import { useHeaderSetting } from '/@/hooks/setting/useHeaderSetting';
  import { useMenuSetting } from '/@/hooks/setting/useMenuSetting';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useLockPage } from '/@/hooks/web/useLockPage';
  import { MenuModeEnum, MenuSplitTyeEnum } from '/@/enums/menuEnum';
  import { useAppInject } from '/@/hooks/web/useAppInject';
  import { useForm, BasicForm, FormSchema } from '/@/components/Form';
  import { useUserStore } from '/@/store/modules/user';
  import { updatePassword } from '@/api/common/api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import dayjs from 'dayjs';

  export default defineComponent({
    name: 'DefaultLayout',
    props: {
      splitType: {
        type: Number as PropType<MenuSplitTyeEnum>,
        default: MenuSplitTyeEnum.NONE,
      },

      // menu Mode
      menuMode: {
        type: [String] as PropType<Nullable<MenuModeEnum>>,
        default: '',
      },
    },
    components: {
      LayoutFeatures: createAsyncComponent(() => import('/@/layouts/default/feature/index.vue')),
      LayoutFooter: createAsyncComponent(() => import('/@/layouts/default/footer/index.vue')),
      LayoutHeader,
      LayoutContent,
      LayoutSideBar,
      LayoutMultipleHeader,
      Layout,
      BasicForm,
    },
    setup(props) {
      const { prefixCls } = useDesign('default-layout');
      const { getIsMobile } = useAppInject();
      const { getShowFullHeaderRef } = useHeaderSetting();
      const { getShowSidebar, getIsMixSidebar, getShowMenu } = useMenuSetting();
      const open = ref(false);
      const userqx = ref(false);
      const menus = menusStore();
      const { createMessage } = useMessage();
      const lockEvents = useLockPage();
      const route = useRoute();
      const { menusRef } = useSplitMenu(toRef(props, 'splitType'));
      watch(
        () => [route.fullPath, menusRef.value],
        (val) => {
          menusRef?.value.forEach((v: any) => {
            if (route.matched[0] && v.title == route.matched[0].meta.title) {
              console.log(val, 'val');
              menus.setMenus(v);
            }
          });
        }
      );

      const layoutClass = computed(() => {
        let cls: string[] = ['ant-layout'];
        if (unref(getIsMixSidebar) || unref(getShowMenu)) {
          cls.push('ant-layout-has-sider');
        }
        return cls;
      });

      // 获取当天日期
      const day = ref(dayjs().format('YYYY-MM-DD'));
      const userStore: any = useUserStore();
      // 当前标题
      const openTitle = computed(() => {
        if (userStore?.userInfo?.loginTenantId == 1) {
          return '首次登录修改密码';
        }
        if (userStore?.userInfo?.diffday > 90) {
          return '密码已超过90天未修改';
        }
        return '';
      });
      if (userStore?.userInfo?.loginTenantId == 1 || userStore?.userInfo?.diffday > 90) open.value = true;
      // 用户权限问题校验
      if (userStore?.userInfo?.userIdentity == 1) {
        // 省区 判断后四位是不是0000
        const res = userStore?.userInfo?.codeRegion.slice(-4);
        if (res !== '0000') {
          userqx.value = true;
        }
      } else if (userStore?.userInfo?.userIdentity == 2) {
        // 市
        const res = userStore?.userInfo?.codeRegion.slice(-2);
        if (res !== '00') {
          userqx.value = true;
        }
      } else if (userStore?.userInfo?.userIdentity == 3 || userStore?.userInfo?.userIdentity == 4) {
        // 县
        console.log(userStore?.userInfo, ' userStore?.userInfo');
        const res = userStore?.userInfo?.codeRegion ? userStore?.userInfo?.codeRegion.slice(-2) : '';
        if (res === '00') {
          userqx.value = true;
        }
      }
      //自定义表单字段
      const formSchemas: FormSchema[] = [
        {
          label: '用户名称',
          field: 'username',
          component: 'InputPassword',
          defaultValue: userStore?.userInfo?.username,
          required: true,
          show: false,
        },
        {
          label: '旧密码',
          field: 'oldpassword',
          component: 'InputPassword',
          required: true,
        },
        {
          label: '新密码',
          field: 'password',
          component: 'InputPassword',
          required: true,
          dynamicRules: () => {
            return [{ pattern: /^(?=.*[0-9])(?=.*[a-zA-Z])(.{8,20})$/, message: '密码格式有误', required: true }];
          },
        },
        {
          label: '重复新密码',
          field: 'confirmpassword',
          component: 'InputPassword',
          dynamicRules: ({ values }) => rules.confirmPassword(values, true),
          required: true,
        },
        {
          label: '手机号',
          field: 'phone',
          component: 'Input',
          slot:'phone',
          dynamicRules: () => {
            return [{ pattern: /^1[3456789]\d{9}$/, message: '手机号码格式有误', required: true }];
          },
        },
        {
          label: '收到账户的时间',
          field: 'day',
          component: 'DatePicker',
          defaultValue: day.value,
          required: true,
          componentProps: {
            disabled: true,
            //日期格式化，页面上显示的值
            format: 'YYYY-MM-DD',
            //返回值格式化（绑定值的格式）
            valueFormat: 'YYYY-MM-DD',
            //是否显示今天按钮
            showToday: true,
          },
        },
      ];
      const [registerForm, { validate }] = useForm({
        //注册表单列
        schemas: formSchemas,
        //不显示查询和重置按钮
        showActionButtonGroup: false,
      });

      //表单提交事件
      async function handleSubmit() {
        try {
          let values = await validate();
          //提交表单
          if (values.oldpassword == values.password) {
            createMessage.error('新密码不能与老密码一样');
            return;
          }
          await updatePassword(values);
          open.value = false;
          //刷新列表
        } finally {
          // open.value = false;
        }
      }
      return {
        getShowFullHeaderRef,
        getShowSidebar,
        prefixCls,
        getIsMobile,
        getIsMixSidebar,
        layoutClass,
        lockEvents,
        formSchemas,
        day,
        registerForm,
        handleSubmit,
        open,
        openTitle,
        userqx,
        menus,
      };
    },
  });
</script>
<style lang="less">
  @prefix-cls: ~'@{namespace}-default-layout';

  .@{prefix-cls} {
    display: flex;
    width: 100%;
    min-height: 100%;
    background-color: @content-bg;
    flex-direction: column;

    > .ant-layout {
      min-height: 100%;
    }

    &-main {
      width: 100%;
      margin-left: 1px;
    }
  }
</style>
