<template>
  <!-- 角色权限 - 添加角色 -->
  <div class="accountPerPage 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="角色名称"
          :placeholder="'请输入角色名称'"
          :rules="[{ required: true, message: '请输入角色名称' }]"
        />
        <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: 50%; padding: 1em;">{{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"
            >添加角色</van-button
          >
        </van-row>
      </van-form>
    </div>
    <van-popup v-model:show="roleShow" round position="bottom">
      <van-cascader
        v-model="roleList"
        title="请选择角色"
        :options="roleOptions"
        @close="roleShow = false"
        @finish="onRoleFinish"
      />
    </van-popup>
    <van-popup v-model:show="equipmentIdShow" round position="bottom">
      <van-cascader
        v-model="equipmentIds"
        title="请选择花型"
        :options="equipmentIdsOptions"
        @close="equipmentIdShow = false"
        @finish="onEquipmentIdFinish"
      />
    </van-popup>
    <nav-bar></nav-bar>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs, ref } from "vue";
import navBar from "@/components/NavBar";
import sHeader from "@/components/SimpleHeader";
import { Toast } from "vant";
import { getSysRoleList, getEquipmentList } from "@/service/accountPar/index";
import { addSysRole, updateSysRole } from "@/service/role/index";
import { getLoginUser } from "@/common/js/utils";
import { useRouter } from "vue-router";

export default {
  components: { sHeader, navBar },
  setup() {
    const router = useRouter();
    const user = getLoginUser();
    const pageTitle = ref('');
    const roleName = ref('');
    const menuCodeList = ref([
      { label: '设备管理', value: 'M1' },
      { label: '设备查看', value: 'M2' },
      { label: '分销设置', value: 'M3' },
      { label: '报警历史', value: 'M4' },
      { label: '广告管理', value: 'M5' },
      { label: '任务消息', value: 'M6' },
      { label: '优惠码', value: 'M7' },
      { label: '账号权限', value: 'M8' },
      { label: '订单导出', value: 'M9' },
      { label: '杉德分账', value: 'M10' },
      { label: '销售排行', value: 'M11' },
      { label: '提现账号', value: 'M12' },
      { label: '备用提现账号', value: 'M13' },
      { label: '数据概览', value: 'M14' },
      { label: '订单数据', value: 'M15' },
      { label: '订单退款', value: 'M16' },
      { label: '系统脱机', value: 'M17' }
    ]);
    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 () => {
      roleItem = localStorage.getItem('roleItem');
      if (roleItem) { 
        roleItem = JSON.parse(roleItem);
        roleName.value = roleItem.roleName;
        roleMenuCode.value = roleItem.menuCodesJson;
        pageTitle.value = '修改角色';
      } else {
        pageTitle.value = '添加角色';
      }
      getSysRoleListFun();
      getEquipmentListFun();
    });
    // 获取角色下拉列表
    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 { Toast.fail(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: '全部', value: 'all' })
      } else { Toast.fail(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') {
        Toast.success('添加角色成功');
        router.push('/role');
      } else { Toast.fail(`添加角色失败 ${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') {
        Toast.success('修改角色成功');
        router.push('/role');
      } else { Toast.fail(`修改角色失败 ${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";
@import "./index.less";
</style>
