<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
          colon
          :border="false"
          @click-input="busiEquipInpClk"
          readonly
          clearable
          v-model="cofficentForm.equipmentNames"
          :label="$t('accountPer.manageMachinesLabel')"
          :placeholder="$t('accountPer.manageMachinesPlaceholder')"
        >
          <template #right-icon>
            <div class="l-flex-RC">
              <van-icon
                v-if="cofficentForm.equipmentNames"
                @click="cofficentForm.equipmentNames = '';equipmentIds=''"
                class="o-mr-6"
                name="clear"
              />
              <van-icon @click="busiEquipInpClk" name="arrow-down" />
            </div>
          </template>
        </van-field>
        <!-- 操作 -->
        <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>
    <!-- 机器弹窗 -->
    <kSelectPop
      @selconfirm="selEquipConfirm"
      ref="kSelectPopEquipRef"
      :selOptions="selEquipOptions"
      :selTitleAndName="['name', 'id']"
    ></kSelectPop>
  </div>
</template>

<script>
// 导入选择组件
import kSelectPop from "../../components/commom/kSelectPop/index.vue";
import { onMounted, reactive, toRefs, ref } from "vue";
import sHeader from "../../components/SimpleHeader";
import { Toast } from "vant";
import {
  getSysRoleList,
  getEquipmentList,
  addLoginUser,
  updataLoginUser,
  deleteLoginUser,
} from "../../service/accountPar/index";
import { getLoginUser, styleUrl } from "../../common/js/utils";
import md5 from "js-md5";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";

export default {
  components: { sHeader, kSelectPop },
  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: "",
      companyType: "1",
    });
    const cofficentForm = ref({
      equipmentNames: "",
    });
    const pageTitle = ref("");
    onMounted(async () => {
      // 加载样式
      styleUrl('accountPer');
      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({ adminId: user.id });
      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") {
        if (data.data.length > 0) {
          // 将id转成字符串类型，解决选中问题
          data.data.forEach((item) => {
            item.id = item.id + "";
          });
        }
        selEquipOptions.value = data.data;
      } 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);
      }
    };
    // 点击机器列表
    const busiEquipInpClk = () => {
      if (addParams.equipmentIds) {
        let list = addParams.equipmentIds.split(",");
        console.log(list, "list");
        kSelectPopEquipRef.value.selPopOpen(list);
      } else {
        kSelectPopEquipRef.value.selPopOpen();
      }
    };
    // 机器选择弹窗
    const selEquipOptions = ref([]);
    const kSelectPopEquipRef = ref(null);
    // 机器弹窗的确定按钮
    const selEquipConfirm = (e) => {
      if (e.length > 0) {
        const list = [];
        // 根据id找到对应的name
        selEquipOptions.value.forEach(item=>{
          e.forEach(item1=>{
            if(item.id === item1){
              list.push(item.name);
            }
          })
        })
        cofficentForm.value.equipmentNames = list.join(",");
        addParams.equipmentIds = e.join(",");
      } else {
        cofficentForm.value.equipmentNames = "";
        addParams.equipmentIds = '';
      }
      kSelectPopEquipRef.value.selPopClose();
    };
    return {
      pageTitle,
      roleShow,
      roleText,
      roleOptions,
      onRoleFinish,
      equipmentIdShow,
      equipmentIdText,
      equipmentIdsOptions,
      onEquipmentIdFinish,
      ...toRefs(addParams),
      onSubmit,
      deleteLoginUserFun,
      selEquipOptions,
      kSelectPopEquipRef,
      selEquipConfirm,
      cofficentForm,
      busiEquipInpClk,
    };
  },
};
</script>

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