<template>
  <!-- 新增账号 -->
  <div class="accountPerPage">
    <s-header :name="pageTitle" :noback="false"></s-header>
    <div class="accountPerBox">
      <van-form @submit="onSubmit" class="modern-form">
        <!-- 表单字段 -->
        <van-field
          v-model="username"
          :label="$t('accountPer.usernameLabel')"
          :placeholder="$t('accountPer.usernamePlaceholder')"
          left-icon="user-o"
          class="modern-field"
          :rules="[
            {
              pattern: /^(?:[a-zA-Z][a-zA-Z0-9]*|[\w.-]+@[\w.-]+\.[a-zA-Z]{2,})$/,
              message: $t('register.usernameRequired'),
            },
          ]"
        />

        <van-field
          v-model="password"
          type="password"
          :label="$t('accountPer.passwordLabel')"
          :placeholder="passwordPlaceholder"
          left-icon="lock"
          class="modern-field"
        />

        <van-field
          v-model="name"
          :label="$t('accountPer.nameLabel')"
          :placeholder="$t('accountPer.namePlaceholder')"
          left-icon="contact"
          class="modern-field"
          :rules="[
            { required: true, message: $t('accountPer.namePlaceholder') },
          ]"
        />

        <!-- <van-field v-model="phone" :label="$t('accountPer.phoneLabel')" :placeholder="$t('accountPer.phonePlaceholder')"
          left-icon="phone" class="modern-field"
          :rules="[{ required: true, message: $t('accountPer.phonePlaceholder') }]" /> -->

        <!-- 类型选择 -->
        <van-field name="radio" v-if="user.type === 0" class="radio-field">
          <template #input>
            <van-radio-group v-model="type" class="radio-group">
              <van-radio name="1" class="radio-item">公司人员</van-radio>
              <van-radio name="4" class="radio-item">营销经理</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <!-- 角色选择 -->
        <van-field
          v-model="roleText"
          is-link
          readonly
          :label="$t('accountPer.roleLabel')"
          :placeholder="$t('accountPer.rolePlaceholder')"
          left-icon="friends-o"
          class="modern-field"
          @click="roleShow = true"
          :rules="[
            { required: true, message: $t('accountPer.rolePlaceholder') },
          ]"
        />

        <!-- 启用开关 -->
        <van-field class="switch-field">
          <template #input>
            <div class="switch-container">
              <van-switch v-model="isEnabled" size="20px" />
              <span class="switch-label">{{
                $t("accountPer.startOrNot")
              }}</span>
            </div>
          </template>
        </van-field>

        <!-- 设备管理 -->
        <van-field
          v-model="cofficentForm.equipmentNames"
          :label="$t('accountPer.manageMachinesLabel')"
          :placeholder="$t('accountPer.manageMachinesPlaceholder')"
          left-icon="cluster-o"
          class="modern-field"
          readonly
          clearable
          @click="busiEquipInpClk"
          :rules="[
            {
              required: true,
              message: $t('accountPer.manageMachinesPlaceholder'),
            },
          ]"
        >
          <template #right-icon>
            <div class="field-icons">
              <van-icon
                v-if="cofficentForm.equipmentNames"
                name="clear"
                @click="
                  cofficentForm.equipmentNames = '';
                  equipmentIds = '';
                "
              />
              <van-icon name="arrow" @click="busiEquipInpClk" />
            </div>
          </template>
        </van-field>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <van-button
            round
            type="primary"
            native-type="submit"
            class="submit-btn"
          >
            {{ $t("accountPer.submit") }}
          </van-button>
          <van-button
            v-if="pageTitle === $t('accountPer.modifyAccount')"
            round
            type="danger"
            class="delete-btn"
            @click="deleteLoginUserFun"
          >
            {{ $t("accountPer.delete") }}
          </van-button>
        </div>
      </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"
      @searchData="searchEquData"
      :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 {
  showFailToast,
  showSuccessToast,
  showToast,
  showNotify,
  showConfirmDialog,
} 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, 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;
    };
    const passwordPlaceholder = ref("");
    const passwordPattern = ref(/^(?=.*[a-zA-Z])(?=.*\d).{10,}$/);
    const havePassword = ref(true);
    const isUserName = ref(false);
    let addParams = reactive({
      username: "",
      password: "",
      name: "",
      phone: "",
      type: user.type === 0 ? "1" : "",
      isEnabled: true,
      roleList: "",
      equipmentIds: "",
      companyType: "0",
    });
    const cofficentForm = ref({
      equipmentNames: "",
    });
    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;
        isUserName.value = true;
        addParams.name = accoutPerSet.name;
        addParams.phone = accoutPerSet.phone;
        addParams.isEnabled = accoutPerSet.isEnabled;
        addParams.roleList = accoutPerSet.roleList[0];
        console.log(addParams.roleList);
        addParams.equipmentIds = accoutPerSet.equipmentIds;
        havePassword.value = false;
        passwordPlaceholder.value = t("accountPer.editPasswordPlaceholder");
      } else {
        pageTitle.value = t("accountPer.addAccount");
        passwordPlaceholder.value = t("register.passwordPlaceholder");
        havePassword.value = true;
      }
      getSysRoleListFun();
      getEquipmentListFun();
    });
    // 获取角色下拉列表
    const getSysRoleListFun = async () => {
      const { data } = await getSysRoleList({ adminId: user.id });
      if (data.code === "00000") {
        console.log();
        roleOptions.value = data.data
          .filter((item) => item.label !== "商家")
          .map((item) => ({
            text: item.label,
            value: item.value,
          }));

        if (pageTitle.value === t("accountPer.modifyAccount")) {
          roleText.value = roleOptions.value.filter(
            (v) => v.value === addParams.roleList
          )[0].text;
          console.log(roleOptions.value);
        }
      } else {
        showFailToast(data.message);
      }
    };

    const searchEquData = (e) => {
      selEquipOptions.value = e;
    };
    // 获取机器下拉
    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;
        if (addParams.equipmentIds != null) {
          const list = addParams.equipmentIds.split(",");
          const listName = [];
          // 根据id找到对应的name
          selEquipOptions.value.forEach((item) => {
            list.forEach((item1) => {
              if (item.id === item1) {
                listName.push(item.name);
              }
            });
          });
          cofficentForm.value.equipmentNames = listName.join(",");
        }
      } else {
        showFailToast(data.message);
      }
    };

    const onSubmit = async () => {
      let params = { adminId: user.id };
      if (addParams.username === "admin") {
        showNotify({ type: "danger", message: t("register.A0201") });
        return false;
      }
      if (addParams.password != "") {
        if (!passwordPattern.value.test(addParams.password)) {
          showNotify(t("register.passwordPlaceholder"));
          return false;
        }
      }
      params = Object.assign({ adminId: user.id }, addParams);
      if (params.password !== "") {
        params.password = md5(params.password);
      }
      params.roleList = [params.roleList];
      if (pageTitle.value === t("accountPer.modifyAccount")) {
        const { data } = await updataLoginUser(params);
        if (data.code === "00000") {
          showSuccessToast(t("accountPer.successfullyModifiedTheAccount"));
          router.replace("/accountPer");
        } else {
          showFailToast(t("accountPer.failedToModifyTheAccount"), data.message);
        }
      } else {
        const { data } = await addLoginUser(params);
        if (data.code === "00000") {
          showSuccessToast(t("accountPer.accountAddedSuccessfully"));
          router.replace("/accountPer");
        } else if (data.code === "A0201") {
          showToast(t("accountPer.accountNameExists"));
        } else {
          showFailToast(t("accountPer.failedToAddAccount"), data.message);
        }
      }
    };
    const deleteLoginUserFun = () => {
      showConfirmDialog({
        title: t("user.tips"),
        message: t("accountPer.delTips"),
      }).then(async () => {
        const params = {
          adminId: user.id,
          id: addParams.id,
        };
        const { data } = await deleteLoginUser(params);
        if (data.code === "00000") {
          showSuccessToast(t("accountPer.successfullyDeletedTheAccount"));
          setTimeout(() => {
            router.go(0);
          }, 1000);
        } else {
          showFailToast(t("accountPer.failedToDeleteTheAccount"), data.message);
        }
      });
    };
    // 点击机器列表
    const busiEquipInpClk = () => {
      if (cofficentForm.value.equipmentNames) {
        let list = cofficentForm.value.equipmentNames.split(",");
        kSelectPopEquipRef.value.selPopOpen(list);
      } else {
        kSelectPopEquipRef.value.selPopOpen();
      }
    };
    // 机器选择弹窗
    const selEquipOptions = ref([]);
    const kSelectPopEquipRef = ref(null);
    // 机器弹窗的确定按钮
    const selEquipConfirm = (e, e1) => {
      if (e.length > 0) {
        cofficentForm.value.equipmentNames = e.join(",");
        addParams.equipmentIds = e1.join(",");
      } else {
        cofficentForm.value.equipmentNames = "";
        addParams.equipmentIds = "";
      }
      kSelectPopEquipRef.value.selPopClose();
    };
    return {
      user,
      pageTitle,
      roleShow,
      roleText,
      roleOptions,
      onRoleFinish,
      equipmentIdShow,
      equipmentIdText,
      equipmentIdsOptions,
      onEquipmentIdFinish,
      ...toRefs(addParams),
      onSubmit,
      deleteLoginUserFun,
      selEquipOptions,
      kSelectPopEquipRef,
      selEquipConfirm,
      cofficentForm,
      busiEquipInpClk,
      havePassword,
      passwordPlaceholder,
      passwordPattern,
      isUserName,
      searchEquData,
    };
  },
};
</script>

<style lang="less" scoped>
@import "../../common/style/common.less";
@primary-color: #4d6add;
@danger-color: #ff6b6b;

.modern-form {
  padding: 16px;

  .modern-field {
    margin-bottom: 16px;
    border-radius: 8px;
    background: #f8f9ff;

    :deep(.van-field__label) {
      color: #666;
      font-size: 14px;
    }

    :deep(.van-field__control) {
      color: #333;
      font-size: 14px;
    }

    :deep(.van-field__left-icon) {
      color: @primary-color;
      margin-right: 8px;
    }
  }

  .radio-field {
    :deep(.van-field__body) {
      padding: 8px 0;
    }
  }

  .radio-group {
    display: flex;
    gap: 24px;

    .radio-item {
      margin: 0;

      :deep(.van-radio__label) {
        color: #333;
      }
    }
  }

  .switch-field {
    :deep(.van-field__body) {
      padding: 8px 0;
    }

    .switch-container {
      display: flex;
      align-items: center;

      .switch-label {
        margin-left: 12px;
        color: #333;
        font-size: 14px;
      }
    }
  }

  .action-buttons {
    margin-top: 24px;
    display: flex;
    flex-direction: column;
    gap: 16px;

    .submit-btn {
      background: @primary-color;
      width: 100%;
      height: 44px;
    }

    .delete-btn {
      background: @danger-color;
      width: 100%;
      height: 44px;
    }
  }

  .field-icons {
    display: flex;
    align-items: center;
    gap: 8px;

    .van-icon {
      color: #c0c4cc;
      font-size: 18px;
    }
  }
}
</style>
