<template>
  <div class="addIdx">
    <s-header :name="titleName" :noback="false"></s-header>
    <van-form show-error-message @submit="onSubmit">
      <div class="kBordBott cust_vantBorder">
        <van-field colon :border="false" required v-model="cofficentForm.name" clearable name="name"
                   :label="$t('labelMan.add.name')" :placeholder="$t('labelMan.add.namePlace')" :rules="[
            {
              required: true,
              message: $t('labelMan.add.namePlace'),
            },
          ]" />
      </div>
      <div class="kBordBott">
        <van-field colon :border="false" required clearable name="type" :label="$t('labelMan.add.type')"
                   :placeholder="$t('labelMan.add.typePlace')" :rules="[
            {
              required: true,
              message: $t('labelMan.add.typePlace'),
              trigger: ['onChange', 'onSubmit'],
            },
          ]">
          <template #input>
            <van-radio-group v-model="cofficentForm.type" direction="horizontal">
              <van-radio name="0">{{ $t("labelMan.merchant") }}</van-radio>
              <van-radio name="1">{{ $t("labelMan.machine") }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>
      </div>
      <div v-if="cofficentForm.type === '0'" class="kBordBott cust_vantBorder">
        <van-field colon :border="false" required @click-input="busiAdminInpClk" readonly clearable
                   v-model="cofficentForm.adminNames" name="adminNames" :label="$t('labelMan.add.merchant')"
                   :placeholder="$t('labelMan.add.merchantPlace')" :rules="[
            {
              required: true,
              message: $t('labelMan.add.merchantPlace'),
            },
          ]">
          <template #right-icon>
            <div class="l-flex-RC">
              <van-icon v-if="cofficentForm.adminNames" @click="cofficentForm.adminNames = ''" class="o-mr-6"
                        name="clear" />
              <van-icon @click="busiAdminInpClk" name="arrow-down" />
            </div>
          </template>
        </van-field>
      </div>
      <div v-if="cofficentForm.type === '1'" class="kBordBott cust_vantBorder">
        <van-field colon :border="false" required @click-input="busiEquipInpClk" readonly clearable
                   v-model="cofficentForm.equipmentNames" name="equipmentNames" :label="$t('labelMan.add.machine')"
                   :placeholder="$t('labelMan.add.machinePlace')" :rules="[
            {
              required: true,
              message: $t('labelMan.add.machinePlace'),
            },
          ]">
          <template #right-icon>
            <div class="l-flex-RC">
              <van-icon v-if="cofficentForm.equipmentNames" @click="cofficentForm.equipmentNames = ''" class="o-mr-6"
                        name="clear" />
              <van-icon @click="busiEquipInpClk" name="arrow-down" />
            </div>
          </template>
        </van-field>
      </div>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          {{ titleName }}
        </van-button>
      </div>
    </van-form>
    <!-- 商家弹窗 -->
    <kSelectPop @selconfirm="selAdminConfirm" ref="kSelectPopAdminRef" :selOptions="selAdminOptions" @searchData="searchAdminData"
                :selTitleAndName="['username', 'id']"></kSelectPop>
    <!-- 机器弹窗 -->
    <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 { getLoginUser, styleUrl } 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;
          // selEquipOptions.value = data.data.slice(0, 8);
        }
      });
    };
    // 点击商家列表
    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) => {
      // console.log("用户列表", e);
      selAdminOptions.value = e;
    }

    const searchEquData = (e) => {
      // console.log("设备列表", 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(() => {
      styleUrl('labelMan');
      // 获取商家列表
      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: "0",
      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>
</style>