<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="1000"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑服务器' : '新增服务器'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <div style="background-color: #f3f3f3; padding: 8px">
      <a-card title="基本信息" :bordered="false">
        <a-form
          ref="formRef"
          :model="form"
          :rules="rules"
          :label-col="{ md: { span: 7 }, sm: { span: 4 }, xs: { span: 24 } }"
          :wrapper-col="{
            md: { span: 17 },
            sm: { span: 20 },
            xs: { span: 24 }
          }"
        >
          <a-row :gutter="16">
            <a-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 8 }
              "
            >
              <a-form-item label="公网IP" name="code">
                <a-input
                  allow-clear
                  :maxlength="20"
                  placeholder="请输入合法的IP地址"
                  v-if="editStatus"
                  v-model:value="form.code"
                />
                <span v-else class="ele-text-primary">{{ form.code }}</span>
              </a-form-item>
              <a-form-item label="品牌厂商" name="brand">
                <DictSelect
                  dict-code="serverBrand"
                  placeholder="请选择品牌厂商"
                  v-if="editStatus"
                  v-model:value="form.brand"
                />
                <span v-else class="ele-text-primary">{{ form.brand }}</span>
              </a-form-item>
              <a-form-item label="所属企业" name="companyName">
                <SelectCompany
                  :placeholder="`选择所属企业`"
                  v-model:value="form.companyName"
                  v-if="editStatus"
                  @done="chooseCompanyId"
                />
                <span v-else class="ele-text-primary">{{
                  form.companyName
                }}</span>
              </a-form-item>
              <a-form-item label="描述" name="name">
                <a-input
                  allow-clear
                  placeholder="请输入服务器描述"
                  v-if="editStatus"
                  v-model:value="form.name"
                />
                <span v-else class="ele-text-primary">{{ form.name }}</span>
              </a-form-item>
              <a-form-item label="服务器配置" name="configuration">
                <a-select
                  v-if="editStatus"
                  v-model:value="form.configuration"
                  mode="tags"
                  placeholder="请填写服务器配置"
                />
                <a-tag v-else v-for="item in form.configuration">
                  {{ item }}
                </a-tag>
              </a-form-item>
            </a-col>
            <a-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 8 }
              "
            >
              <a-form-item label="宝塔面板" name="panel">
                <a-input
                  allow-clear
                  placeholder="https://47.106.145.40:20780/603f8087"
                  v-model:value="form.panel"
                  v-if="editStatus"
                />
                <a
                  :href="form.panel"
                  target="_blank"
                  v-else
                  class="ele-text-primary"
                  >{{ form.panel }}</a
                >
              </a-form-item>
              <a-form-item label="宝塔面板账号" name="panelAccount">
                <a-input
                  allow-clear
                  :maxlength="20"
                  placeholder="宝塔面板账号"
                  v-if="editStatus"
                  v-model:value="form.panelAccount"
                />
                <span v-else class="ele-text-primary">{{
                  form.panelAccount
                }}</span>
              </a-form-item>
              <a-form-item label="宝塔面板密码" name="panelPassword">
                <a-input
                  allow-clear
                  :maxlength="20"
                  placeholder="宝塔面板密码"
                  v-if="editStatus"
                  v-model:value="form.panelPassword"
                />
                <span v-else class="ele-text-primary">{{
                  form.panelPassword
                }}</span>
              </a-form-item>
              <a-form-item label="开放端口" name="openPort">
                <a-select
                  v-if="editStatus"
                  v-model:value="form.openPort"
                  mode="tags"
                  placeholder="请选择开放端口"
                />
                <a-tag v-else v-for="item in form.openPort">
                  {{ item }}
                </a-tag>
              </a-form-item>
              <a-form-item label="状态" name="status">
                <DictSelect
                  dict-code="serverStatus"
                  placeholder="请选择状态"
                  v-if="editStatus"
                  v-model:value="form.status"
                />
                <template v-else>
                  <a-tag :color="form.status == '正常' ? 'green' : ''">
                    {{ form.status }}
                  </a-tag>
                </template>
              </a-form-item>
            </a-col>
            <a-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 8 }
              "
            >
              <a-form-item label="宝塔API接口秘钥" name="btSign">
                <a-input
                  allow-clear
                  :maxlength="50"
                  placeholder="宝塔API接口秘钥"
                  v-if="editStatus"
                  v-model:value="form.btSign"
                />
                <span v-else class="ele-text-primary">{{ form.btSign }}</span>
              </a-form-item>
            </a-col>
            <a-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 8 }
              "
            >
              <a-form-item label="排序" name="sortNumber">
                <a-input
                  allow-clear
                  :maxlength="20"
                  placeholder="排序"
                  v-if="editStatus"
                  v-model:value="form.sortNumber"
                />
                <span v-else class="ele-text-primary">{{
                  form.sortNumber
                }}</span>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
    </div>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, ipReg, isChinese } from 'ele-admin-pro';
  import { addAssets, updateAssets } from '@/api/oa/assets';
  import type { Assets } from '@/api/oa/assets/model';
  import { FormInstance, RuleObject } from 'ant-design-vue/es/form';
  import { Company } from '@/api/system/company/model';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { uploadFile } from '@/api/system/file';
  import { TOKEN_STORE_NAME } from '@/config/setting';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';

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

  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 maxable = ref(true);
  // 当期时间
  // 已上传数据
  const logo = ref<ItemType[]>([]);
  const assetsQrcode = ref<ItemType[]>([]);
  const images = ref<ItemType[]>([]);
  const editStatus = ref(true);
  // 日期范围选择
  const content = ref('');

  const token = localStorage.getItem(TOKEN_STORE_NAME);
  const formRef = ref<FormInstance | null>(null);

  const form = reactive<Assets>({
    type: '服务器',
    code: '',
    createTime: '',
    endTime: '',
    name: '',
    brand: undefined,
    account: '',
    password: '',
    panelAccount: '',
    panelPassword: '',
    panel: '',
    financeAmount: 0,
    financeYears: 0,
    financeRenew: 0,
    customerId: undefined,
    customerName: '',
    companyName: '',
    financeCustomerName: '',
    financeCustomerContact: '',
    financeCustomerPhone: '',
    brandAccount: '',
    brandPassword: '',
    btSign: '',
    openPort: '',
    configuration: '',
    comments: '',
    root: 'root',
    sortNumber: 100,
    status: '运行中',
    assetsId: 0,
    visibility: 'private',
    userList: [],
    userId: undefined,
    // 成员管理
    users: []
  });

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

  // 表单验证规则
  const rules = reactive({
    code: [
      {
        required: true,
        type: 'string',
        message: '请输入公网IP地址',
        trigger: 'blur'
      }
    ],
    companyName: [
      {
        required: true,
        type: 'string',
        message: '请选择所属企业',
        trigger: 'blur'
      }
    ],
    assetsCode: [
      {
        required: true,
        type: 'string',
        message: '请输入应用标识(英文字母)',
        trigger: 'blur',
        validator: async (_rule: RuleObject, value: string) => {
          if (isChinese(value)) {
            return Promise.reject('请输入正确的应用标识');
          }
          return Promise.resolve();
        }
      }
    ],
    assetsType: [
      {
        required: true,
        message: '请选择项目类型'
      }
    ],
    ipAddress: [
      {
        pattern: ipReg,
        message: 'IP地址不合法',
        type: 'string'
      }
    ],
    assetsStatus: [
      {
        required: true,
        type: 'string',
        message: '请选择应用状态',
        trigger: 'blur'
      }
    ]
  });

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

  // 所属用户
  const chooseCompanyId = (data: Company) => {
    form.companyName = data.companyName;
    form.companyId = data.companyId;
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form,
          content: content.value,
          openPort: form.openPort.toString(),
          configuration: form.configuration.toString()
        };
        const saveOrUpdate = isUpdate.value ? updateAssets : addAssets;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  // 上传文件:应用图标
  const onUploadIcon = (item) => {
    const { file } = item;
    logo.value = [];
    uploadFile(file)
      .then((data) => {
        logo.value.push({
          uid: data.id,
          url: data.url,
          status: 'done'
        });
        message.success('上传成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  const onUploadQrcode = (item) => {
    const { file } = item;
    assetsQrcode.value = [];
    uploadFile(file)
      .then((data) => {
        assetsQrcode.value.push({
          uid: data.id,
          url: data.url,
          status: 'done'
        });
        message.success('上传成功');
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  // 上传文件
  const onUpload = (item) => {
    const { file } = item;
    uploadFile(file)
      .then((data) => {
        images.value.push({
          uid: data.id,
          url: data.url,
          status: 'done'
        });
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  const reload = () => {
    loading.value = true;
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        content.value = '';
        logo.value = [];
        images.value = [];
        assetsQrcode.value = [];
        if (props.data) {
          assignObject(form, props.data);
          isUpdate.value = true;
          reload();
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
