<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="username"
          name="username"
          label="{{$t('accountPer.usernameLabel')}}"
          :placeholder="$t('accountPer.usernamePlaceholder')"
          :rules="[{ required: true, message: $t('accountPer.usernamePlaceholder') }]"
        />
        <van-field
          v-model="password"
          name="password"
          type="password"
          label="{{$t('accountPer.passwordLabel')}}"
          :placeholder="$t('accountPer.passwordPlaceholder')"
        />
        <van-field
          v-model="name"
          name="name"
          label="{{$t('accountPer.nameLabel')}}"
          :placeholder="$t('accountPer.namePlaceholder')"
          :rules="[{ required: true, message: $t('accountPer.namePlaceholder') }]"
        />
        <van-field
          v-model="phone"
          name="phone"
          label="{{$t('accountPer.phoneLabel')}}"
          :placeholder="$t('accountPer.phonePlaceholder')"
          :rules="[{ required: true, message: $t('accountPer.phonePlaceholder') }]"
        />
        <van-field
          v-model="roleText"
          is-link
          readonly
          label="{{$t('accountPer.roleLabel')}}:"
          :placeholder="$t('accountPer.rolePlaceholder')"
          @click="roleShow = true"
        />
        <div class="van-cell van-field">
          <div class="van-cell__title van-field__label">
            <label id="van-field-4-label" for="van-field-4-input">{{$t('accountPer.setUp')}}:</label>
          </div>
          <div class="van-cell__value van-field__value">
            <div class="van-field__body">
              <van-switch v-model="isEnabled" /><span>{{$t('accountPer.startOrNot')}}</span>
            </div>
          </div>
        </div>
        <van-field
          v-model="equipmentIdText"
          is-link
          readonly
          label="{{$t('accountPer.manageMachinesLabel')}}:"
          :placeholder="$t('accountPer.manageMachinesPlaceholder')"
          @click="equipmentIdShow = true"
        />
        <!-- 操作 -->
        <van-row justify="space-around" style="padding: 1em">
          <van-button
            span="5"
            round
            type="primary"
            style="height: 2em; padding: 0 2em"
            native-type="submit"
            >{{$t('accountPer.submit')}}</van-button
          >
        </van-row>
        <van-row
          justify="space-around"
          style="padding: 1em"
          v-if="pageTitle === $t('accountPer.modifyAccount')"
        >
          <van-button
            span="5"
            round
            type="danger"
            style="height: 2em; padding: 0 2em"
            @click="deleteLoginUserFun()"
            >{{$t('accountPer.delete')}}</van-button
          >
        </van-row>
      </van-form>
    </div>
    <van-popup v-model:show="roleShow" round position="bottom">
      <van-cascader
        v-model="roleList"
        title="{{$t('accountPer.rolePlaceholder')}}"
        :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('accountPer.manageMachinesPlaceholder')}}"
        :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,
  addLoginUser,
  updataLoginUser,
  deleteLoginUser,
} from "@/service/accountPar/index";
import { getLoginUser } from "@/common/js/utils";
import md5 from "js-md5";
import { useRouter } from "vue-router";
import { useI18n } from 'vue-i18n';

export default {
  components: { sHeader, navBar },
  setup() {
    const { t } = useI18n();
    const router = useRouter();
    const user = getLoginUser();
    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: "",
    });
    const pageTitle = ref("");
    onMounted(async () => {
      let accoutPerSet = localStorage.getItem("accoutPerSet");
      if (accoutPerSet) {
        pageTitle.value = t('accountPer.modifyAccount');
        accoutPerSet = JSON.parse(accoutPerSet);
        addParams.id = accoutPerSet.id;
        addParams.username = accoutPerSet.username;
        addParams.name = accoutPerSet.name;
        addParams.phone = accoutPerSet.phone;
        addParams.isEnabled = accoutPerSet.isEnabled;
        addParams.roleList = accoutPerSet.roleList[0];
        addParams.equipmentIds = accoutPerSet.equipmentIds;
      } else {
        pageTitle.value = t('accountPer.addAccount');
      }
      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 };
        });
        if (pageTitle.value === t('accountPer.modifyAccount')) {
          roleText.value = roleOptions.value.filter(
            (v) => v.value === addParams.roleList
          )[0].text;
        }
      } 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.toString() };
        });
        equipmentIdsOptions.value.unshift({ text: t('accountPer.whole'), value: "all" });
        if (pageTitle.value === t('accountPer.modifyAccount')) {
          equipmentIdText.value = equipmentIdsOptions.value.filter(
            (v) => v.value === addParams.equipmentIds
          )[0].text;
        }
      } else {
        Toast.fail(data.message);
      }
    };

    const onSubmit = async () => {
      let params = { adminId: user.id };
      params = Object.assign({ adminId: user.id }, addParams);
      if (params.password !== "") {
        params.password = md5(params.password);
      }
      params.roleList = [params.roleList];
      // if (params.equipmentIds !== 'all') {
      //   params.equipmentIds= [params.equipmentIds];
      // }
      if (pageTitle.value === t('accountPer.modifyAccount')) {
        delete params.password;
        const { data } = await updataLoginUser(params);
        if (data.code === "00000") {
          Toast.success(t('accountPer.successfullyModifiedTheAccount'));
          router.push("/accountPer");
        } else {
          Toast.fail(t('accountPer.failedToModifyTheAccount'), data.message);
        }
        console.log("onSubmit", data);
      } else {
        const { data } = await addLoginUser(params);
        if (data.code === "00000") {
          Toast.success(t('accountPer.accountAddedSuccessfully'));
          router.push("/accountPer");
        } else {
          Toast.fail(t('accountPer.failedToAddAccount'), data.message);
        }
        console.log("onSubmit", data);
      }
    };
    const deleteLoginUserFun = async () => {
      const params = {
        adminId: user.id,
        id: addParams.id,
      };
      const { data } = await deleteLoginUser(params);
      if (data.code === "00000") {
        Toast.success(t('accountPer.successfullyDeletedTheAccount'));
        router.push("/accountPer");
      } else {
        Toast.fail(t('accountPer.failedToDeleteTheAccount'), data.message);
      }
    };
    return {
      pageTitle,
      roleShow,
      roleText,
      roleOptions,
      onRoleFinish,
      equipmentIdShow,
      equipmentIdText,
      equipmentIdsOptions,
      onEquipmentIdFinish,
      ...toRefs(addParams),
      onSubmit,
      deleteLoginUserFun,
    };
  },
};
</script>

<style lang="less" scoped>
@import "../../common/style/common.less";
@import "./index.less";
/deep/ .van-switch {
  width: 38px;
  height: 18px;

  .van-switch__node {
    width: 18px;
    height: 18px;
  }

  &.van-switch--on .van-switch__node {
    transform: translate(calc(38px - 18px));
  }
}
</style>
