<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="75%"
    :visible="visible"
    :confirm-loading="loading"
    :maxable="maxAble"
    :title="isUpdate ? '编辑服务器' : '添加服务器'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    :maskClosable="false"
    @ok="save"
  >
    <a-tabs v-model:activeKey="activeKey" type="card">
      <a-tab-pane key="1" tab="基本信息">
        <a-form
          :label-col="{ md: { span: 8 }, sm: { span: 24 } }"
          :wrapper-col="{ md: { span: 24 }, sm: { span: 24 } }"
          layout="vertical"
        >
          <a-form-item label="服务器名称" v-bind="validateInfos.name">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入服务器名称"
              v-model:value="form.name"
              @blur="validate('name', { trigger: 'blur' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="服务器IP" v-bind="validateInfos.code">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入合法的公网IP，如：0.0.0.0"
              v-model:value="form.code"
            />
          </a-form-item>
          <a-form-item label="品牌厂商" v-bind="validateInfos.brand">
            <brand-select
              v-model:value="form.brand"
              @blur="validate('brand', { trigger: 'blur' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="所属客户" v-bind="validateInfos.companyId">
            <SelectCompany
              :placeholder="`请选择客户`"
              v-model:value="form.customerName"
              @done="onSelect"
            />
          </a-form-item>
          <a-form-item label="备注" v-bind="validateInfos.comments">
            <!-- 编辑器 -->
            <byte-md-editor
              v-model:value="form.comments"
              :locale="zh_Hans"
              :plugins="plugins"
              height="300px"
              :editorConfig="{ lineNumbers: true }"
            />
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="2" tab="账号密码">
        <a-form
          :label-col="{ md: { span: 8 }, sm: { span: 24 } }"
          :wrapper-col="{ md: { span: 24 }, sm: { span: 24 } }"
          layout="vertical"
        >
          <a-form-item label="宝塔面板" v-bind="validateInfos.panel">
            <a-input
              allow-clear
              placeholder="http://ip:8888"
              v-model:value="form.panel"
              @blur="validate('panel', { trigger: 'blur' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="宝塔面板账号" v-bind="validateInfos.panelAccount">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="宝塔面板账号"
              v-model:value="form.panelAccount"
              @blur="
                validate('panelAccount', { trigger: 'blur' }).catch(() => {})
              "
            />
          </a-form-item>
          <a-form-item
            label="宝塔面板密码"
            v-bind="validateInfos.panelPassword"
          >
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="宝塔面板密码"
              v-model:value="form.panelPassword"
              @blur="
                validate('panelPassword', { trigger: 'blur' }).catch(() => {})
              "
            />
          </a-form-item>
          <a-form-item label="宝塔API接口秘钥" v-bind="validateInfos.btSign">
            <a-input
              allow-clear
              :maxlength="50"
              placeholder="宝塔API接口秘钥"
              v-model:value="form.btSign"
              @blur="validate('btSign', { trigger: 'blur' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="服务器账号" v-bind="validateInfos.account">
            <a-input v-model:value="form.account" placeholder="root" />
          </a-form-item>
          <a-form-item label="服务器密码" v-bind="validateInfos.password">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="服务器密码"
              v-model:value="form.password"
              @blur="validate('password', { trigger: 'blur' }).catch(() => {})"
            />
          </a-form-item>
          <a-form-item label="厂商登录账号" v-bind="validateInfos.brandAccount">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="请输入阿里云/腾讯登录账号"
              v-model:value="form.brandAccount"
            />
          </a-form-item>
          <a-form-item label="登录密码" v-bind="validateInfos.brandPassword">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="登录密码"
              v-model:value="form.brandPassword"
            />
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="3" tab="其他配置">
        <a-form
          :label-col="{ md: { span: 8 }, sm: { span: 24 } }"
          :wrapper-col="{ md: { span: 24 }, sm: { span: 24 } }"
          layout="vertical"
        >
          <a-form-item label="服务器配置" v-bind="validateInfos.configuration">
            <configuration-select
              v-model:value="form.configuration"
              @blur="
                validate('configuration', { trigger: 'blur' }).catch(() => {})
              "
            />
          </a-form-item>
          <a-form-item label="购买日期">
            <a-date-picker
              class="ele-fluid"
              placeholder="请选择购买日期"
              v-model:value="startTime"
            />
          </a-form-item>
          <a-form-item label="结束日期">
            <a-date-picker
              class="ele-fluid"
              placeholder="请选择结束日期"
              v-model:value="endTime"
            />
          </a-form-item>
          <a-form-item label="开放端口" v-bind="validateInfos.openPort">
<!--            <port-select-->
<!--              v-model:value="form.openPort"-->
<!--              @blur="validate('openPort', { trigger: 'blur' }).catch(() => {})"-->
<!--            />-->
          </a-form-item>
          <a-form-item label="状态" v-bind="validateInfos.status">
            <a-select
              optionFilterProp="label"
              placeholder="请选择状态"
              :options="serverStatus"
              allow-clear
              v-model:value="form.status"
            />
          </a-form-item>
          <a-form-item label="排序" v-bind="validateInfos.sortNumber">
            <a-input
              allow-clear
              :maxlength="20"
              placeholder="排序"
              v-model:value="form.sortNumber"
            />
          </a-form-item>
        </a-form>
      </a-tab-pane>
    </a-tabs>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, ipReg } from 'ele-admin-pro';
  import type { Assets } from '@/api/oa/assets/model';
  import BrandSelect from './brand-select.vue';
  import SelectUser from '@/components/SelectUser/index.vue';
  import ConfigurationSelect from './configuration-select.vue';
  import PortSelect from './port-select.vue';
  import { addAssets, updateAssets } from '@/api/oa/assets';
  import dayjs from 'dayjs';
  import type { Dayjs } from 'dayjs';
  import { getDictionaryOptions } from '@/utils/common';
  import { UserVisibility } from '@/api/user/visibility/model';
  // 中文语言文件
  import zh_Hans from 'bytemd/locales/zh_Hans.json';
  import 'bytemd/dist/index.min.css';
  import 'github-markdown-css/github-markdown-light.css';
  // // 链接、删除线、复选框、表格等的插件
  import gfm from '@bytemd/plugin-gfm';
  // // 插件的中文语言文件
  import zh_HansGfm from '@bytemd/plugin-gfm/locales/zh_Hans.json';
  // 中文语言文件
  import 'bytemd/dist/index.min.css';
  import highlight from '@bytemd/plugin-highlight-ssr';
  import 'highlight.js/styles/default.css';
  import { Company } from "@/api/system/company/model";

  const useForm = Form.useForm;
  // 是否是修改
  const isUpdate = ref(false);
  // 是否显示最大化切换按钮
  const maxAble = ref(true);
  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Assets | null;
  }>();

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

  // 提交状态
  const loading = ref(false);
  const serverStatus = getDictionaryOptions('serverStatus');
  const users = ref<UserVisibility[]>([]);
  // 用户信息
  const form = reactive<Assets>({
    code: '',
    createTime: '',
    endTime: '',
    name: '',
    brand: undefined,
    account: '',
    password: '',
    configuration: '不详',
    panelAccount: '',
    panelPassword: '',
    panel: '',
    financeAmount: 0,
    financeYears: 0,
    financeRenew: 0,
    customerId: undefined,
    customerName: '',
    financeCustomerName: '',
    financeCustomerContact: '',
    financeCustomerPhone: '',
    brandAccount: '',
    brandPassword: '',
    btSign: '',
    openPort: '80',
    comments: '',
    root: 'root',
    sortNumber: 100,
    status: '0',
    type: '',
    assetsId: 0,
    visibility: 'private',
    userList: [],
    userId: undefined
  });

  // 选项卡位置
  const activeKey = ref('1');
  // 购买日期
  const startTime = ref<Dayjs>();
  // 结束日期
  const endTime = ref<Dayjs>();
  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    name: [
      {
        required: true,
        type: 'string',
        message: '请输入服务器名称',
        trigger: 'blur'
      }
    ],
    userId: [
      {
        required: true,
        type: 'number',
        message: '请选择客户'
      }
    ],
    code: [
      {
        required: true,
        type: 'string',
        message: '请输入IP地址',
        trigger: 'blur'
      },
      {
        pattern: ipReg,
        message: 'IP地址不合法',
        type: 'string'
      }
    ],
    brand: [
      {
        required: true,
        type: 'string',
        message: '请选项服务器厂商',
        trigger: 'blur'
      }
    ],
    configuration: [
      {
        required: true,
        type: 'string',
        message: '请选择服务器配置',
        trigger: 'blur'
      }
    ],
    openPort: [
      {
        required: true,
        type: 'any',
        message: '请选择服务器已开放端',
        trigger: 'blur'
      }
    ],
    panel: [
      {
        required: true,
        type: 'string',
        message: '请填写面板地址',
        trigger: 'blur'
      }
    ],
    panelAccount: [
      {
        required: true,
        type: 'string',
        message: '请填写面板登录账号',
        trigger: 'blur'
      }
    ],
    panelPassword: [
      {
        required: true,
        type: 'string',
        message: '请填写面板登录密码',
        trigger: 'blur'
      }
    ],
    status: [
      {
        required: true,
        type: 'string',
        message: '服务器状态',
        trigger: 'blur'
      }
    ],
    visibility: [
      {
        required: true,
        type: 'string',
        message: '请设置可见性'
      }
    ]
  });

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

  const onSelect = (data: Company) => {
    form.customerId = data.companyId;
    form.customerName = data.companyName;
  };

  // 插件
  const plugins = ref([
    gfm({
      locale: zh_HansGfm
    }),
    highlight()
  ]);

  /* 保存编辑 */
  const save = () => {
    validate()
      .then(() => {
        loading.value = true;
        const data = {
          ...form,
          startTime: startTime.value?.format('YYYY-MM-DD HH:mm:ss'),
          endTime: endTime.value?.format('YYYY-MM-DD HH:mm:ss')
        };
        // 转字符串
        data.openPort = data.openPort.toString();
        const saveOrUpdate = isUpdate.value ? updateAssets : addAssets;
        console.log(data);
        saveOrUpdate(data)
          .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) {
        if (props.data) {
          loading.value = false;
          assignObject(form, props.data);
          if (props.data.startTime) {
            startTime.value = dayjs(props.data.startTime, 'YYYY-MM-DD');
            endTime.value = dayjs(props.data.endTime, 'YYYY-MM-DD');
          } else {
            startTime.value = undefined;
            endTime.value = undefined;
          }
          if (props.data.openPort) {
            form.openPort = props.data.openPort.split(',');
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        startTime.value = undefined;
        endTime.value = undefined;
      }
    }
  );
</script>
<style lang="less">
  .tab-pane {
    min-height: 300px;
  }
</style>
