<template>
  <!-- 角色权限 - 添加角色 -->
  <div class="rolePage flex-col">
    <s-header :name="pageTitle" :noback="false"></s-header>
    <div class="accountPerBox flex-col">
      <van-form @submit="onSubmit">
        <van-field v-model="roleName" name="roleName" :label="$t('role.roleNameLabel')"
          :placeholder="$t('role.roleNamePlaceholder')"
          :rules="[{ required: true, message: $t('role.roleNamePlaceholder') }]" />
        <van-checkbox-group v-model="roleMenuCode" style="
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: flex-start;
          ">
          <van-checkbox v-for="(item, index) in menuCodeList" :key="index" :name="item.value"
            style="width: 160px; padding: 10px">{{ item.label }}</van-checkbox>
        </van-checkbox-group>
        <!-- 操作 -->
        <van-row justify="space-around" style="padding: 1em">
          <van-button span="5" round type="primary" style="height: 2em; padding: 0 2em" native-type="submit">
            {{ pageTitle }}
          </van-button>
        </van-row>
      </van-form>
    </div>
    <!-- <van-popup v-model:show="roleShow" round position="bottom">
      <van-cascader
          v-model="roleList"
          :title="$t('role.pleaseSelectARole')"
          :options="roleOptions"
          @close="roleShow = false"
          @finish="onRoleFinish"
      />
    </van-popup>
    <van-popup v-model:show="equipmentIdShow" round position="bottom">
      <van-cascader
          v-model="equipmentIds"
          :title="$t('role.pleaseSelectAPattern')"
          :options="equipmentIdsOptions"
          @close="equipmentIdShow = false"
          @finish="onEquipmentIdFinish"
      />
    </van-popup> -->
  </div>
</template>

<script>
import { onMounted, reactive, toRefs, ref } from "vue";
import sHeader from "../../components/SimpleHeader";
import { showFailToast, showSuccessToast } from "vant";
// import { getSysRoleList, getEquipmentList } from "../../service/accountPar/index";
import { addSysRole, updateSysRole } from "../../service/role/index";
import { getLoginUser, $M_Menus, styleUrl } from "../../common/js/utils";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";

export default {
  components: { sHeader },
  setup() {
    // 引入语言
    const { t } = useI18n();
    const router = useRouter();
    const user = getLoginUser();
    const pageTitle = ref("");
    const roleName = ref("");
    // 设置的权限
    const menuCodeList = ref([]);
    const roleMenuCode = ref([]);
    // const roleShow = ref(false);
    const roleText = ref("");
    // const roleOptions = ref([]);
    // const onRoleFinish = ({ selectedOptions }) => {
    //   roleShow.value = false;
    //   roleText.value = selectedOptions[0].text;
    // };
    // const equipmentIdShow = ref(false);
    const equipmentIdText = ref("");
    const equipmentIdsOptions = ref([]);
    // const onEquipmentIdFinish = ({ selectedOptions }) => {
    //   equipmentIdShow.value = false;
    //   equipmentIdText.value = selectedOptions[0].text;
    // };
    let addParams = reactive({
      username: "",
      password: "",
      name: "",
      phone: "",
      isEnabled: true,
      // roleList: "",
      equipmentIds: "",
    });
    let roleItem = null;
    onMounted(async () => {
      // 加载样式
      styleUrl('role');
      roleItem = localStorage.getItem("roleItem");
      if (roleItem) {
        roleItem = JSON.parse(roleItem);
        roleName.value = roleItem.roleName;
        roleMenuCode.value = roleItem.menuCodesJson;
        pageTitle.value = t("role.modifyRole");
      } else {
        pageTitle.value = t("role.addRole");
      }
      // 设置菜单权限
      menuSet();
      // getSysRoleListFun();
      // getEquipmentListFun();
    });
    // 设置菜单权限
    const menuSet = () => {
      // 如果不是admin管理员权限type=0，要删除 广告管理M5，杉德分账M10，系统脱机M17，apk管理M19
      if (user.type !== 0) {
        delete $M_Menus['M5'];
        delete $M_Menus['M10'];
        delete $M_Menus['M17'];
        delete $M_Menus['M19'];
      }
      // 如果是商家，进一步删除 账户操作M3，订单导出M9，
      if (user.type === 2) {
        delete $M_Menus['M3'];
        delete $M_Menus['M9'];
      }

      for (const key in $M_Menus) {
        console.log(key);
        if (key === "M21") {
          continue;
        }
        menuCodeList.value.push({
          label: $M_Menus[key],
          value: key
        });
      }
    };
    // 获取角色下拉列表
    // const getSysRoleListFun = async () => {
    //   const { data } = await getSysRoleList();
    //   if (data.code === "00000") {
    //     roleOptions.value = data.data.map((item) => {
    //       return { text: item.label, value: item.value };
    //     });
    //   } else {
    //     showFailToast(data.message);
    //   }
    // };
    // 获取机器下拉
    // const getEquipmentListFun = async () => {
    //   const { data } = await getEquipmentList({ adminId: user.id });
    //   if (data.code === "00000") {
    //     equipmentIdsOptions.value = data.data.map((item) => {
    //       return { text: item.name, value: item.id };
    //     });
    //     equipmentIdsOptions.value.unshift({
    //       text: t("role.whole"),
    //       value: "all",
    //     });
    //   } else {
    //     showFailToast(data.message);
    //   }
    // };

    const onSubmit = async () => {
      if (roleItem) {
        updateSysRoleFun();
      } else {
        addSysRoleFun();
      }
    };
    const addSysRoleFun = async () => {
      const params = {
        adminId: user.id,
        roleName: roleName.value,
        menuCodeList: roleMenuCode.value,
      };
      const { data } = await addSysRole(params);
      if (data.code === "00000") {
        showSuccessToast(t("role.roleAddedSuccessfully"));
        // router.push("/role");
        router.go(-1);
      } else {
        showFailToast(`${t("role.failedToAddRole")} ${data.message}`);
      }
      console.log("onSubmit", data);
    };
    const updateSysRoleFun = async () => {
      const params = {
        adminId: user.id,
        roleId: roleItem.roleId,
        roleName: roleName.value,
        menuCodeList: roleMenuCode.value,
      };
      const { data } = await updateSysRole(params);
      if (data.code === "00000") {
        showSuccessToast(t("role.successfullyModifiedRole"));
        // router.go(-1);
        router.replace("/role");
      } else {
        showFailToast(`${t("role.failedToModifyRole")} ${data.message}`);
      }
      console.log("onSubmit", data);
    };
    return {
      pageTitle,
      roleName,
      menuCodeList,
      roleMenuCode,
      // roleShow,
      roleText,
      // roleOptions,
      // onRoleFinish,
      // equipmentIdShow,
      equipmentIdText,
      equipmentIdsOptions,
      // onEquipmentIdFinish,
      ...toRefs(addParams),
      onSubmit,
    };
  },
};
</script>

<style lang="less" scoped>
@import "../../common/style/common.less";
</style>
