<template>
  <div class="add-label-page">
    <!-- 自定义头部 -->
    <s-header :name="titleName" :noback="false" class="label-header" />

    <!-- 表单区域 -->
    <van-form @submit="onSubmit" class="label-form">
      <!-- 标签名称 -->
      <div class="form-section">
        <van-field
          v-model="cofficentForm.name"
          name="name"
          clearable
          required
          :border="false"
          :label="$t('labelMan.add.name')"
          :placeholder="$t('labelMan.add.namePlace')"
          :rules="[{ required: true, message: $t('labelMan.add.namePlace') }]"
          class="name-field"
        >
          <template #left-icon>
            <van-icon name="label-o" class="field-icon" />
          </template>
        </van-field>
      </div>

      <!-- 机器选择 -->
      <div v-if="cofficentForm.type === '1'" class="form-section">
        <van-field
          v-model="cofficentForm.equipmentNames"
          name="equipmentNames"
          readonly
          required
          :border="false"
          :label="$t('labelMan.add.machine')"
          :placeholder="$t('labelMan.add.machinePlace')"
          :rules="[
            { required: true, message: $t('labelMan.add.machinePlace') },
          ]"
          class="select-field"
          @click="busiEquipInpClk"
        >
          <template #left-icon>
            <van-icon name="desktop-o" class="field-icon" />
          </template>

          <template #right-icon>
            <div class="field-actions">
              <van-icon
                v-if="cofficentForm.equipmentNames"
                name="clear"
                class="clear-icon"
                @click="cofficentForm.equipmentNames = ''"
              />
              <van-icon name="arrow-down" class="arrow-icon" />
            </div>
          </template>
        </van-field>
      </div>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          class="submit-button"
        >
          {{ titleName }}
        </van-button>
      </div>
    </van-form>

    <!-- 机器选择弹窗 -->
    <kSelectPop
      ref="kSelectPopEquipRef"
      :selOptions="selEquipOptions"
      @selconfirm="selEquipConfirm"
      @searchData="searchEquData"
      :selTitleAndName="['name', 'id']"
    />
  </div>
</template>

<script>
// 导入选择组件
import kSelectPop from "../../components/commom/kSelectPop/index.vue";
// 导入公用方法
import { getLoginUser } from "../../common/js/utils";
// 导入接口
import {
  Api_getListAdmin,
  Api_getListEquipment,
  Api_postAddLabel,
  Api_postUpdateLabel,
} from "../../service/labelMan";
import sHeader from "../../components/SimpleHeader";
import { onMounted, ref } from "vue";
import { showToast } from "vant";
import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
export default {
  components: { sHeader, kSelectPop },
  setup() {
    const getAdminList = () => {
      Api_getListAdmin({ adminId: user.id }).then((res) => {
        console.log("res11", res);
        const { data } = res;
        if (data.code === "00000") {
          selAdminOptions.value = data.data;
        }
      });
    };
    const getEquipList = () => {
      Api_getListEquipment({ adminId: user.id }).then((res) => {
        console.log("res11", res);
        const { data } = res;
        if (data.code === "00000") {
          selEquipOptions.value = data.data;
        }
      });
    };
    // 点击商家列表
    const busiAdminInpClk = () => {
      if (cofficentForm.value.adminNames) {
        let list = cofficentForm.value.adminNames.split(",");
        kSelectPopAdminRef.value.selPopOpen(list);
      } else {
        kSelectPopAdminRef.value.selPopOpen();
      }
    };
    // 商家选择弹窗
    const selAdminOptions = ref([]);
    const kSelectPopAdminRef = ref(null);
    // 商家弹窗的确定按钮
    const selAdminConfirm = (e, e1) => {
      if (e.length > 0 && e1.length > 0) {
        cofficentForm.value.adminNames = e.join(",");
        cofficentForm.value.adminIds = e1.join(",");
      } else {
        cofficentForm.value.adminNames = "";
      }
      kSelectPopAdminRef.value.selPopClose();
    };

    const searchAdminData = (e) => {
      selAdminOptions.value = e;
    };

    const searchEquData = (e) => {
      selEquipOptions.value = e;
    };

    // 点击机器列表
    const busiEquipInpClk = () => {
      if (cofficentForm.value.equipmentNames) {
        let list = cofficentForm.value.equipmentNames.split(",");
        console.log(list, "list");
        kSelectPopEquipRef.value.selPopOpen(list);
      } else {
        kSelectPopEquipRef.value.selPopOpen();
      }
    };
    // 机器选择弹窗
    const selEquipOptions = ref([]);
    const kSelectPopEquipRef = ref(null);
    // 机器弹窗的确定按钮
    const selEquipConfirm = (e, e1) => {
      if (e.length > 0 && e1.length > 0) {
        cofficentForm.value.equipmentNames = e.join(",");
        cofficentForm.value.equipmentIds = e1.join(",");
      } else {
        cofficentForm.value.equipmentNames = "";
        cofficentForm.value.equipmentIds = "";
      }
      kSelectPopEquipRef.value.selPopClose();
    };

    // 获取登陆信息
    const user = getLoginUser();
    const { t } = useI18n();
    // 标题
    const titleName = ref(t("apkManage.add.addTitle"));
    const route = useRoute();
    // 刚进页面
    onMounted(() => {
      // 获取商家列表
      getAdminList();
      // 获取机器列表
      getEquipList();
      const row = route.query.row ? JSON.parse(route.query.row) : {};
      // 看路径有没有id，有就是编辑
      if (row.id) {
        titleName.value = t("apkManage.add.editTitle");
        cofficentForm.value = row;
        // 处理商家列表，把选中的显示在商家列表
        cofficentForm.value.adminNames = cofficentForm.value.adminNames
          ? JSON.parse(cofficentForm.value.adminNames).join(",")
          : "";
        // 处理机器列表，把选中的显示在机器列表
        cofficentForm.value.equipmentNames = cofficentForm.value.equipmentNames
          ? JSON.parse(cofficentForm.value.equipmentNames).join(",")
          : "";
      }
    });
    // 表单参数
    let cofficentForm = ref({
      adminId: user.id,
      adminIds: "",
      name: "",
      type: "1",
      adminNames: "",
      equipmentNames: "",
      equipmentIds: "",
    });
    // 路由
    const router = useRouter();
    // 点击提交
    const onSubmit = async () => {
      const param = Object.assign({}, cofficentForm.value);
      // 判断type清空商家或机器参数
      if (param.type === "0") {
        param.equipmentNames = "";
        param.equipmentIds = "";
        param.adminNames = JSON.stringify(param.adminNames.split(","));
        param.adminIds = JSON.stringify(param.adminIds.split(","));
      } else {
        param.adminNames = "";
        param.adminIds = "";
        param.equipmentNames = JSON.stringify(param.equipmentNames.split(","));
        param.equipmentIds = JSON.stringify(param.equipmentIds.split(","));
      }
      // 如果是编辑
      let res;
      if (cofficentForm.value.id) {
        res = await Api_postUpdateLabel(param);
      } else {
        res = await Api_postAddLabel(param);
      }
      const { data } = res;
      if (data.code === "00000" && cofficentForm.value.id) {
        showToast(t("labelMan.add.editSuccess"));
        setTimeout(() => {
          router.go(-1);
        }, 1000);
      } else if (data.code === "00000" && !cofficentForm.value.id) {
        showToast(t("labelMan.add.addSuccess"));
        setTimeout(() => {
          router.go(-1);
        }, 1000);
      }
    };
    return {
      onSubmit,
      cofficentForm,
      titleName,
      selAdminOptions,
      kSelectPopAdminRef,
      selAdminConfirm,
      selEquipOptions,
      kSelectPopEquipRef,
      selEquipConfirm,
      busiAdminInpClk,
      busiEquipInpClk,
      searchAdminData,
      searchEquData,
    };
  },
};
</script>

<style lang="less" scoped>
@primary-color: #4d6add;
@card-bg: #ffffff;
@text-dark: #333;
@text-light: #666;
@border-color: #e4e7ec;

.add-label-page {
  min-height: 100vh;
  background-color: #f5f8ff;
}

.label-header {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.label-form {
  padding: 16px;
}

.form-section {
  background-color: @card-bg;
  border-radius: 12px;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(77, 106, 221, 0.1);
  overflow: hidden;

  &:last-child {
    margin-bottom: 20px;
  }
}

.name-field,
.select-field {
  padding: 16px;

  :deep(.van-field__label) {
    font-weight: 500;
    color: @text-dark;
  }

  :deep(.van-field__control) {
    font-size: 15px;
    color: @text-dark;
  }

  .field-icon {
    font-size: 20px;
    color: @primary-color;
    margin-right: 10px;
  }

  .field-actions {
    display: flex;
    align-items: center;

    .clear-icon {
      color: #999;
      font-size: 18px;
      margin-right: 8px;
      padding: 4px;

      &:active {
        color: @primary-color;
      }
    }

    .arrow-icon {
      color: #999;
      font-size: 18px;
    }
  }
}

.form-actions {
  padding: 0 16px;

  .submit-button {
    height: 50px;
    background: linear-gradient(to right, #4d6add, #6a89ff);
    border: none;
    font-size: 16px;
    font-weight: 500;
    box-shadow: 0 6px 16px rgba(77, 106, 221, 0.3);
  }
}

@media (max-width: 480px) {
  .label-form {
    padding: 12px;
  }

  .form-section {
    margin-bottom: 12px;
  }

  .name-field,
  .select-field {
    padding: 12px;
  }

  .submit-button {
    height: 46px;
    font-size: 15px;
  }
}
</style>
