<template>
  <div class="inventory-add">
    <div class="left">
      <div class="left-center">
        <div>
          <ya-button
            :plain="isHost ? false : true"
            :type="isHost ? 'primary' : ''"
            class="left-btn"
            @click="choseCheck(true)"
            >主机</ya-button
          >
        </div>
        <div class="line"></div>
        <div>
          <div class="flex-x-st" v-for="(item, index) in portList" :key="index">
            <img
              class="img1 cursor"
              @click="delPort(item, index)"
              src="../../../assets/image/collection/img4.png"
              alt=""
              style="position: relative"
            />
            <div
              class="port-btn cursor"
              :class="item.active ? 'active-btn' : ''"
              @click="chosePort(item, index)"
            >
              <span>{{ item.port }}</span>
            </div>
          </div>
        </div>
        <el-input
          class="portInput"
          v-if="inputVisible"
          ref="InputRef"
          v-model="inputValue"
          @keyup.enter="handleInputConfirm"
          @blur="handleInputConfirm"
          :onkeyup="choseInput"
        />
        <div v-else class="port cursor" @click="choseCheck(false)">
          <span>+端口</span>
        </div>
      </div>
    </div>
    <div class="right">
      <div class="submit">
        <ya-button :loading="btnLoading" type="primary" @click="subMit"
          >一键提交</ya-button
        >
      </div>
      <div class="right-content">
        <Host
          :dictArr="dictArr"
          :hostData="hostData"
          :showHost="isHost"
          v-show="isHost"
          ref="hostRef"
          @getFormData="getFormData"
        ></Host>
        <Apply
          :deptList="applyDeptList"
          :dictArr="dictArr"
          :applyData="applyData"
          v-show="!isHost"
          ref="applyRef"
          @getFormData="getApplyData"
          @getFormApplyData="getFormApplyData"
          @clearRules="clearRules"
        ></Apply>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { unflattenObject } from 'yuan-plus';
import { ref, reactive, onMounted, nextTick, watch } from 'vue';
import type { FormInstance, FormRules, ElInput } from 'element-plus';
import { yaMessage, yaConfirmMessage } from 'yuan-plus';
import Host from './components/host.vue';
import Apply from './components/apply.vue';
import {
  getDictTypeList,
  getDeptList,
  firstLevelList,
  getSubDeptTreeById,
} from '../../../api/common';
import {
  add,
  update,
  singleAsset,
} from '../../../api/collection/infoCollection/inventory';
import { useRoute, useRouter } from 'vue-router';
const router = useRouter();
const Route = useRoute();

const portList = ref([]);
const inputValue = ref('');
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();
const btnLoading = ref(false); // 提交按钮加载动画
const hostRef = ref();
const applyRef = ref();
const isHost = ref(true); // 切换主机
const isAddPort = ref(true); // 是点击端口还是点击提交
/**
 * @description 端口号保存
 */
const handleInputConfirm = () => {
  if (inputValue.value) {
    let result = portList.value.find((item) => {
      return item.port == inputValue.value;
    });
    if (result) {
      yaMessage('已存在当前端口！', 'warning');
    } else {
      isHost.value = false;
      let data = JSON.parse(JSON.stringify(hostData.value));
      let obj = {
        port: inputValue.value,
        active: true,
        name: data.name,
        feature: {
          position: data.position || '',
          importanceLevel: data.feature.importanceLevel || '',
          assetTagCodeSet: data.assetTagCodeSet || [],
          companyId: data.feature.companyId || '',
          deptId: data.deptId || '',
          contact: data.feature.contact || '',
          contactMobile: data.feature.contactMobile || '',
          contactEmail: data.feature.contactEmail || '',
          isOwn: data.feature.isOwn || '',
          businessSystem: data.feature.businessSystem || '',
          networkUnitType: data.feature.networkUnitType || '',
          ratingObjectName: data.feature.ratingObjectName || '',
          ratingLevel: data.feature.ratingLevel || '',
        },
      };
      portList.value.push(obj);
      resetPort(inputValue.value);
      applyData.value = obj;
      inputVisible.value = false;
      inputValue.value = '';
      clearRules();
      toTop();
    }
  } else {
    inputVisible.value = false;
    inputValue.value = '';
  }
};
/**
 * @description 初始化端口选中状态
 */
const resetPort = (e) => {
  portList.value.forEach((item, i) => {
    if (e == item.port) {
      item.active = true;
    } else {
      item.active = false;
    }
  });
};
/**
 * @description 主机切换
 */
const choseCheck = (e) => {
  if (e) {
    isHost.value = true;
    toTop();
    resetPort('reset');
  } else {
    isAddPort.value = true;
    if (isHost.value) {
      getRules();
    } else {
      crossRules();
    }
  }
};
/**
 * @description 主机规则通过后触发
 */
const crossRules = () => {
  // 通过form规则后触发
  if (isAddPort.value) {
    inputVisible.value = true;
    inputValue.value = '';
    nextTick(() => {
      InputRef.value!.input!.focus(); // 获取焦点
    });
  } else {
    subMitInfo();
  }
};
/**
 * @description 删除端口
 */
const delPort = (e, i) => {
  portList.value.splice(i, 1);
  if (portList.value.length > 0) {
    portList.value[portList.value.length - 1].active = true;
    applyData.value = portList.value[portList.value.length - 1];
  } else {
    isHost.value = true;
  }
};
/**
 * @description 端口值校验
 */
const choseInput = () => {
  inputValue.value = inputValue.value.replace(/[^\d]/g, '');
  if (inputValue.value > 65535) {
    inputValue.value = 65535;
  }
};
/**
 * @description 端口切换
 */
const applyDeptList = ref([]);
const chosePort = (e, index) => {
  isHost.value = false;
  portList.value.forEach((item) => {
    if (item.port == e.port) {
      item.active = true;
      applyData.value = item;
    } else {
      item.active = false;
    }
  });
  if (e.feature.companyId) {
    getSubDeptTreeById({ deptId: e.feature.companyId }).then((res) => {
      const { code, data } = res || {};
      if (code === 200) {
        applyDeptList.value = restDataOne(data);
      }
    });
  }

  toTop();
  clearRules();
};
/**
 * @description 触发form表单校验
 */
const getRules = () => {
  hostRef.value.getHostForm();
};
const getAppRules = () => {
  applyRef.value.getHostForm();
};
/**
 * @description 清除规则
 */
const clearRules = () => {
  applyRef.value.clearRules();
};
/**
 * @description 提交
 */
const subMit = () => {
  isAddPort.value = false;
  if (isHost.value) {
    getRules();
  } else {
    getAppRules();
  }
};
/**
 * @description 提交数据
 */
const subMitInfo = () => {
  let list = portList.value.map((item) => {
    return unflattenObject(item);
  });
  let obj = {
    appAssetList: list,
    ...hostData.value,
  };
  btnLoading.value = true;
  let send;
  if (Route.query.code) {
    send = update;
  } else {
    send = add;
  }
  send(obj)
    .then((res) => {
      btnLoading.value = false;
      if (res.code == 200) {
        yaMessage(res.message, 'success');
        router.go(-1);
      }
    })
    .catch(() => {
      btnLoading.value = false;
    });
};
/**
 * @description 获取主机数据
 */
const hostData = ref({});
const getFormData = (e) => {
  hostData.value = e;
  crossRules();
};
/**
 * @description 获取应用data
 */
const applyData = ref({});
const getApplyData = (e) => {
  portList.value.forEach((item) => {
    if (item.port == e.port) {
      Object.assign(item, e);
    }
  });
};
const getFormApplyData = (e) => {
  subMitInfo();
};
/**
 * @description 回到顶部
 */
const toTop = () => {
  document.getElementsByClassName('ya-right')[0].scrollTop = 0;
  document.getElementsByClassName('ya-right')[1].scrollTop = 0;
};

/**
 * @description: 字典数据初始化
 */
const resetDictData = (e) => {
  let list = e.map((item) => {
    return {
      label: item.dictName,
      value: item.dictValue,
    };
  });
  return list;
};
const dictArr = ref({
  importanceLevelList: [], // 资产重要级别
  ratingLevelList: [], // 定级级别
  protectionLevelList: [], // 等保级别
  companyIdList: [], //所属单位
  networkUnitTypeList: [], // 网络单元类型
  positionList: [], // 资产所在区域
  deptList: [], //所属部门
});
const getDictList = () => {
  // 资产重要级别
  getDictTypeList({ dictType: 'importanceLevel' }).then((res) => {
    if (res.code == 200) {
      dictArr.value.importanceLevelList = resetDictData(res.data);
    }
  });
  // 定级级别
  getDictTypeList({ dictType: 'ratingLevel' }).then((res) => {
    if (res.code == 200) {
      dictArr.value.ratingLevelList = resetDictData(res.data);
    }
  });
  // 等保级别
  getDictTypeList({ dictType: 'protectionLevel' }).then((res) => {
    if (res.code == 200) {
      dictArr.value.protectionLevelList = resetDictData(res.data);
    }
  });
  // 所属部门
  firstLevelList({}).then((res) => {
    if (res.code == 200) {
      dictArr.value.companyIdList = res.data
        ? res.data.map((item) => {
            item.label = item.deptName;
            item.value = item.id;
            return item;
          })
        : [];
    }
  });
  // 网络单元类型
  getDictTypeList({ dictType: 'networkUnitType' }).then((res) => {
    if (res.code == 200) {
      dictArr.value.networkUnitTypeList = resetDictData(res.data);
    }
  });
  // 资产所在区域
  getDictTypeList({
    dictType: 'position',
    needChild: true,
    needChildTree: true,
    dictKey: 'position',
    needRoot: true,
  }).then((res) => {
    if (res.code == 200) {
      dictArr.value.positionList = restData(res.data);
    }
  });
};
const restData = (data) => {
  data = data.map((item) => {
    return {
      ...item,
      label: item.dictName,
      children: item.childList ? restData(item.childList) : item.childList,
    };
  });
  return data;
};
const restDataOne = (data) => {
  data = data.map((item) => {
    return {
      ...item.data,
      label: item.data.deptName,
      children: item.children ? restDataOne(item.children) : item.children,
    };
  });
  return data;
};
/**
 * @description 获取详情
 */
const getDeatil = () => {
  singleAsset({ hostCode: Route.query.code }).then((res) => {
    if (res.code == 200) {
      hostData.value = res.data.hostAsset;
      applyData.value = res.data.appAssetList;
      portList.value = res.data.appAssetList;
      if (hostData.value.feature && hostData.value.feature.companyId) {
        getOneDept(hostData.value.feature.companyId);
      }
    }
  });
};
const getOneDept = (id) => {
  // 获取部门层级
  getSubDeptTreeById({ deptId: id }).then((res) => {
    const { code, data } = res || {};
    if (code === 200) {
      dictArr.value.deptList = data ? restDataOne(data) : [];
    }
  });
};
onMounted(() => {
  getDictList();
  if (Route.query.code) {
    getDeatil();
  }
});
</script>

<style lang="scss" scoped>
.inventory-add {
  display: flex;
  
  .cursor {
    cursor: pointer;
  }

  .left {
    border-right: 1px solid var(--el-border-color);
    padding-right: 12px;
    overflow-y: auto;
    width: 120px;

    .flex-x-st {
      display: flex;
      justify-content: flex-start;
    }

    .img1 {
      position: relative;
      width: 16px;
      height: 16px;
      top: 22px;
    }

    .left-center {
      padding-top: 20px;
      padding-left: 20px;
      position: relative;
    }

    .line {
      position: absolute;
      left: 25px;
      top: 40px;
      height: calc(100% - 55px);
      width: 7px;
      border-left: 1px solid var(--el-border-color);
      border-bottom: 1px solid var(--el-border-color);
    }

    .left-btn {
      width: 88px;
      z-index: 1;
      position: relative;
    }

    .active-btn {
      background: var(--el-color-primary);
      border: 1px solid var(--el-color-primary) !important;
      color: #fff !important;
    }

    .port-btn {
      // margin: 12px 0;
      margin-top: 12px;
    }

    .port,
    .port-btn {
      width: 70px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 2px;
      border: 1px dashed var(--el-border-color);
      font-weight: 400;
      color: var(--el-color-primary);
      font-size: 14px;
      position: relative;
    }

    .port-btn {
      color: #919396;
    }

    .port {
      margin-left: 16px;
      margin-top: 12px;
      margin-bottom: 16px;
    }

    .portInput {
      margin-top: 12px;
      height: 30px;
      line-height: 30px;
      width: 72px;
      position: relative;
      left: 18px;
    }
  }

  .right {
    flex: 1;
    display: flex;
    flex-direction: column;
    .right-content {
      flex: 1;
      overflow: hidden;
    }
    .submit {
      display: flex;
      justify-content: flex-end;
      margin-top: 16px;
      margin-right: 16px;
    }
  }
}
</style>
