<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑云服务器' : '添加云服务器'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="服务器名称" name="name">
        <a-input
          allow-clear
          placeholder="请输入服务器名称"
          v-model:value="form.name"
        />
      </a-form-item>
      <a-form-item label="服务器IP" name="code">
        <a-input
          allow-clear
          placeholder="请输入服务器IP"
          v-model:value="form.code"
        />
      </a-form-item>
      <a-form-item label="宝塔面板" name="panel">
        <a-input
          allow-clear
          placeholder="请输入宝塔面板"
          v-model:value="form.panel"
        />
      </a-form-item>
      <a-form-item label="宝塔面板账号" name="panelAccount">
        <a-input
          allow-clear
          placeholder="请输入宝塔面板账号"
          v-model:value="form.panelAccount"
        />
      </a-form-item>
      <a-form-item label="宝塔面板密码" name="panelPassword">
        <a-input
          allow-clear
          placeholder="请输入宝塔面板密码"
          v-model:value="form.panelPassword"
        />
      </a-form-item>
<!--      <a-form-item label="服务器类型" name="type">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入服务器类型"-->
<!--          v-model:value="form.type"-->
<!--        />-->
<!--      </a-form-item>-->
      <a-form-item label="供应商" name="brand">
        <DictSelect
          dict-code="serverBrand"
          placeholder="请选择品牌厂商"
          v-model:value="form.brand"
          @change="onBrand"
        />
      </a-form-item>
      <a-form-item label="服务器配置" name="configuration">
        <a-textarea
          :rows="3"
          :maxlength="200"
          placeholder="请填写服务器配置"
          v-model:value="form.configuration"
        />
      </a-form-item>
      <a-form-item label="root账号" name="account">
        <a-input
          allow-clear
          placeholder="请输入初始账号"
          v-model:value="form.account"
        />
      </a-form-item>
      <a-form-item label="服务器密码" name="password">
        <a-input
          allow-clear
          placeholder="请输入初始密码"
          v-model:value="form.password"
        />
      </a-form-item>
      <a-form-item label="供应商登录账号" name="brandAccount">
        <a-input
          allow-clear
          placeholder="请输入供应商登录账号"
          v-model:value="form.brandAccount"
        />
      </a-form-item>
      <a-form-item label="供应商登录密码" name="brandPassword">
        <a-input
          allow-clear
          placeholder="请输入供应商登录密码"
          v-model:value="form.brandPassword"
        />
      </a-form-item>
<!--      <a-form-item label="合同金额" name="financeAmount">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入合同金额"-->
<!--          v-model:value="form.financeAmount"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="购买年限" name="financeYears">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入购买年限"-->
<!--          v-model:value="form.financeYears"-->
<!--        />-->
<!--      </a-form-item>-->
<!--      <a-form-item label="续费金额" name="financeRenew">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入续费金额"-->
<!--          v-model:value="form.financeRenew"-->
<!--        />-->
<!--      </a-form-item>-->
      <a-form-item label="开放端口" name="openPort">
        <a-select
          v-model:value="form.openPort"
          mode="tags"
          placeholder="请选择开放端口"
        ></a-select>
      </a-form-item>
      <a-form-item label="购买时间" name="startTime">
        <a-date-picker
          v-model:value="form.startTime"
          placeholder="购买时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </a-form-item>
      <a-form-item label="到期时间" name="endTime">
        <a-date-picker
          v-model:value="form.endTime"
          placeholder="到期时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </a-form-item>
      <a-form-item label="宝塔接口秘钥" name="btSign">
        <a-input
          allow-clear
          placeholder="请输入宝塔接口秘钥"
          v-model:value="form.btSign"
        />
      </a-form-item>
      <a-form-item label="排序" name="sortNumber">
        <a-input-number
          :min="0"
          :max="9999"
          class="ele-fluid"
          placeholder="请输入排序号"
          v-model:value="form.sortNumber"
        />
      </a-form-item>
      <a-form-item label="描述" name="comments">
        <a-textarea
          :rows="5"
          :maxlength="200"
          placeholder="请输入描述"
          v-model:value="form.comments"
        />
      </a-form-item>
<!--      <a-form-item label="状态" name="status">-->
<!--        <a-radio-group v-model:value="form.status">-->
<!--          <a-radio :value="0">显示</a-radio>-->
<!--          <a-radio :value="1">隐藏</a-radio>-->
<!--        </a-radio-group>-->
<!--      </a-form-item>-->
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, uuid } from 'ele-admin-pro';
  import { addOaAssets, updateOaAssets } from '@/api/oa/oaAssets';
  import { OaAssets } from '@/api/oa/oaAssets/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { isIP } from "ele-admin-pro";
  import { FormInstance, RuleObject } from "ant-design-vue/es/form";
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import {decrypt, encrypt} from "@/utils/common";

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  const brand = ref('');
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: OaAssets | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 表格选中数据
  const formRef = ref<FormInstance | null>(null);
  const images = ref<ItemType[]>([]);

  // 用户信息
  const form = reactive<OaAssets>({
    assetsId: undefined,
    name: undefined,
    code: undefined,
    type: undefined,
    brand: undefined,
    configuration: undefined,
    account: 'root',
    password: undefined,
    brandAccount: undefined,
    brandPassword: undefined,
    panel: undefined,
    panelAccount: undefined,
    panelPassword: undefined,
    financeAmount: undefined,
    financeYears: undefined,
    financeRenew: undefined,
    financeCustomerName: undefined,
    financeCustomerContact: undefined,
    financeCustomerPhone: undefined,
    customerId: undefined,
    customerName: undefined,
    openPort: undefined,
    content: undefined,
    startTime: undefined,
    endTime: undefined,
    isTop: undefined,
    visibility: undefined,
    btSign: undefined,
    comments: undefined,
    companyId: undefined,
    userId: undefined,
    userIds: undefined,
    organizationId: undefined,
    status: undefined,
    tenantId: undefined,
    createTime: undefined,
    sortNumber: 100
  });

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    name: [
      {
        required: true,
        type: 'string',
        message: '请填写服务器名称',
        trigger: 'blur'
      }
    ],
    endTime: [
      {
        required: true,
        type: 'date',
        message: '请选择到期时间',
        trigger: 'change'
      }
    ],
    code: [
      {
        required: true,
        type: "string",
        message: "请输入合法的IP地址",
        trigger: "blur",
        validator: async (_rule: RuleObject, value: string) => {
          if (!isIP(value)) {
            const msg = "请输入合法的IP地址";
            try {
              if (!isIP(value)) {
                return Promise.reject(msg);
              }
            } catch (_e) {
              return Promise.reject(msg);
            }
          }
          return Promise.resolve();
        }
      }
    ],
  });

  const onBrand = (index: number,item: any) => {
    console.log(index)
    brand.value = item.label;
  }

  const { resetFields } = useForm(form, rules);

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form,
          brand: brand.value,
          panelPassword: encrypt(form.panelPassword),
          password: encrypt(form.password),
          brandPassword: encrypt(form.brandPassword),
          btSign: encrypt(form.btSign),
          openPort: JSON.stringify(form.openPort),
        };
        const saveOrUpdate = isUpdate.value ? updateOaAssets : addOaAssets;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        images.value = [];
        if (props.data) {
          assignObject(form, props.data);
          if(props.data.panelPassword){
            form.panelPassword = decrypt(props.data.panelPassword);
            form.password = decrypt(props.data.password);
            form.brandPassword = decrypt(props.data.brandPassword);
            form.btSign = decrypt(props.data.btSign);
          }
          if(props.data.openPort){
            form.openPort = JSON.parse(props.data.openPort);
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>
