<!-- 编辑弹窗 -->
<template>
  <ele-modal
    width="70%"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="`服务器详情`"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <div style="background-color: #f3f3f3; padding: 8px">
      <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-card title="基本信息" :bordered="false">
          <template #extra>
            <a-button type="link" @click="handleEditStatus">{{ editStatus ? "预览" : "编辑" }}</a-button>
          </template>
          <a-row :gutter="16">
            <a-col
              v-bind="styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 8 }"
            >
              <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="公网IP" name="code">
                <a-input
                  allow-clear
                  :maxlength="20"
                  placeholder="请输入合法的公网IP，如：0.0.0.0"
                  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="configuration">
                <a-select
                  v-if="editStatus"
                  v-model:value="form.configuration"
                  mode="tags"
                  placeholder="请填写服务器配置"
                ></a-select>
                <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="http://ip:8888"
                  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-select>
                <a-tag v-else v-for="item in form.openPort">
                  {{ item }}
                </a-tag>
              </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="状态" 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-row>
        </a-card>
        <a-divider style="height: 8px" />
        <a-card title="成员管理" :bordered="false">
          <div class="content">
            <a-space
              style="margin-bottom: 15px"
            >
              <SelectUser
                :placeholder="`添加开发成员`"
                @done="addAssetsDevUser"
              />
            </a-space>
            <table
              class="ele-table ele-table-border ele-table-stripe ele-table-medium"
            >
              <thead>
              <tr>
                <th>角色</th>
                <th>用户</th>
                <th>邮箱</th>
                <th>手机号码</th>
                <th>加入时间</th>
                <th>操作</th>
              </tr>
              </thead>
              <tbody>
              <tr v-for="user in assetsUsers">
                <td>
                  <a-tag color="green" v-if="user.role === 10">体验成员</a-tag>
                  <a-tag color="orange" v-if="user.role === 20">开发成员</a-tag>
                  <a-tag color="red" v-if="user.role === 30">管理员</a-tag>
                </td>
                <td>
                  <a-avatar :src="user.avatar">
                    <template #icon>
                      <user-outlined />
                    </template>
                  </a-avatar>
                  <span style="padding-left: 5px">{{ user.nickname }}</span>
                </td>
                <td>{{ user.email }}</td>
                <td>{{ user.phone }}</td>
                <td>{{ user.createTime }}</td>
                <td>
                  <div v-if="user.role !== 30">
                    <a
                      @click="removeUser(user)"
                      v-if="user.status === 0"
                    >
                      移除
                    </a>
                    <a v-else>待评价</a>
                  </div>
                  <div v-else>
                    <a>转让</a>
                  </div>

                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </a-card>
        <a-divider v-if="editStatus" style="height: 8px" />
        <a-card v-if="editStatus" title="其他信息" :bordered="false">
          <template #extra>
            <a-button type="link" @click="handleEditStatus">{{ editStatus ? "预览" : "编辑" }}</a-button>
          </template>
          <a-row :gutter="16">
            <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-card>
        <a-divider style="height: 8px" />
        <a-card title="备注" :bordered="false">
          <template #extra>
            <a-button type="link" @click="handleEditStatus">{{ editStatus ? "预览" : "编辑" }}</a-button>
          </template>
          <!-- 编辑器 -->
          <byte-md-editor
            v-if="editStatus"
            v-model:value="form.comments"
            :locale="zh_Hans"
            :plugins="plugins"
            height="300px"
            :editorConfig="{ lineNumbers: true }"
          />
          <byte-md-viewer v-else :value="form.comments" :plugins="plugins" />
        </a-card>
      </a-form>
    </div>
  </ele-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, createVNode, computed } from "vue";
import { Form, message } from "ant-design-vue";
import { assignObject, ipReg, toDateString } from "ele-admin-pro";
import { useUserStore } from "@/store/modules/user";
import { useThemeStore } from "@/store/modules/theme";
import { storeToRefs } from "pinia";
// 中文语言文件
import zh_Hans from "bytemd/locales/zh_Hans.json";
// 链接、删除线、复选框、表格等的插件
// 插件的中文语言文件
import zh_HansGfm from "@bytemd/plugin-gfm/locales/zh_Hans.json";
import "bytemd/dist/index.min.css";
import "github-markdown-css/github-markdown-light.css";
import { Modal } from "ant-design-vue";
// import TinymceEditor from '@/components/TinymceEditor/index.vue';
import highlight from "@bytemd/plugin-highlight";
// 中文语言文件
import gfm from "@bytemd/plugin-gfm";
// // 预览界面的样式，这里用的 github 的 markdown 主题
import "github-markdown-css/github-markdown-light.css";
import {
  EyeOutlined,
  EyeInvisibleOutlined,
  EnvironmentOutlined
} from "@ant-design/icons-vue";
import { UploadOutlined } from "@/layout/menu-icons";
import { FormInstance, RuleObject } from "ant-design-vue/es/form";
import { Assets } from "@/api/oa/assets/model";
import { ItemType } from "ele-admin-pro/es/ele-image-upload/types";
import { User } from "@/api/system/user/model";
import { uploadFile } from "@/api/system/file";
import { FILE_SERVER, FILE_THUMBNAIL, TOKEN_STORE_NAME } from "@/config/setting";
import { listAssetsUser, addAssetsUser, removeAssetsUser } from "@/api/oa/assets/user/index";
import { AssetsUser } from "@/api/oa/assets/user/model";
import { addAssets, updateAssets } from "@/api/oa/assets";
import { isIP } from "ele-admin-pro";
import { Company } from "@/api/system/company/model";
import { Dayjs } from "dayjs";
import { listAppUser } from "@/api/oa/app/user";
import { pageCompany } from "@/api/system/company";

// 是否是修改
const isUpdate = ref(false);
const useForm = Form.useForm;
// 是否开启响应式布局
const themeStore = useThemeStore();
const { styleResponsive } = storeToRefs(themeStore);
const { darkMode } = 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 dayTime = toDateString(new Date());
// 已上传数据
const images = ref<ItemType[]>([]);
const assetsUsers = ref<AssetsUser[]>([]);
const selectUser = ref<string>();
const editStatus = ref(false);
const formRef = ref<FormInstance | null>(null);
// 类型 single|multiple
// const type = ref<string>('single');
// 日期范围选择
const dateRange = ref<[string, string]>(["", ""]);
const content = ref("");
const requirement = ref("");
// 插件
const plugins = ref([
  gfm({
    locale: zh_HansGfm
  }),
  highlight()
]);

// 购买日期
const startTime = ref<Dayjs>();
// 结束日期
const endTime = ref<Dayjs>();
const showAddUserForm = ref(false);

// 文件模型
interface FileItem {
  uid: string;
  name?: string;
  status?: string;
  response?: Response;
  thumbUrl?: string;
  downloadUrl?: string;
  url: string;
}

interface FileInfo {
  file: FileItem;
  fileList: FileItem[];
}

// 文件上传
const file1 = ref<FileItem[]>();
const file2 = ref<FileItem[]>();
const file3 = ref<FileItem[]>();

// 用户信息
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: "0",
  assetsId: 0,
  visibility: "private",
  userList: [],
  userId: undefined
});

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

// 表单验证规则
const rules = reactive({
  name: [
    {
      required: true,
      type: "string",
      message: "请输入服务器名称",
      trigger: "blur"
    }
  ],
  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();
      }
    }
  ],
  brand: [
    {
      required: true,
      type: "string",
      message: "请选择跟进状态",
      trigger: "blur"
    }
  ],
  companyName: [
    {
      required: true,
      type: "string",
      message: "请选择所属企业",
      trigger: "blur"
    }
  ]
  // assetsName: [
  //   {
  //     required: true,
  //     type: 'string',
  //     message: '请选择租赁单位',
  //     trigger: 'blur'
  //   }
  // ],
  // appRegion: [
  //   {
  //     required: true,
  //     type: 'string',
  //     message: '请输入服务器地址',
  //     trigger: 'blur'
  //   }
  // ]
});

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

const addUser = () => {
  showAddUserForm.value = true;
};

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


// 添加开发成员
const addAssetsDevUser = (data: User) => {
  addAssetsUser({
    userId: data.userId,
    assetsId: props.data?.assetsId,
    role: 20
  }).then((msg) => {
    message.success(msg);
    reload();
  })
    .catch((e) => {
      message.error(e.message);
    });
}

// 移除成员
const removeUser = (data: AssetsUser) => {
  removeAssetsUser(data.id)
    .then((msg) => {
      message.success(msg);
      reload();
    })
    .catch((e) => {
      message.error(e.message);
    });
};

const handleEditStatus = () => {
  editStatus.value = !editStatus.value;
};

// const chooseAssetsName = (data: Assets) => {
//   form.assetsName = data.assetsName;
// };

const onFile1 = (info: FileInfo) => {
  let resFileList = [...info.fileList];
  file1.value = resFileList.map((file) => {
    if (file.response) {
      file.url = file.response.url;
    }
    return file;
  });
  form.file1 = JSON.stringify(file1.value);
};

const config = ref({
  width: 1000,
  height: 500,
  images_upload_handler: (blobInfo, success, error) => {
    const file = blobInfo.blob();
    // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
    const formData = new FormData();
    formData.append("file", file, file.name);
    uploadFile(<File>file)
      .then((result) => {
        if (result.length) {
          if (file.size / 1024 / 1024 > 2) {
            error("图片大小不能超过 2MB");
          }
          success(FILE_SERVER + result.path);
        } else {
          error("上传失败");
        }
      })
      .catch((e) => {
        message.error(e.message);
      });
  }
});

// 上传文件
const onUpload = (item) => {
  const { file } = item;
  images.value = [];
  uploadFile(file)
    .then((data) => {
      images.value.push({
        uid: data.id,
        url: FILE_THUMBNAIL + data.path,
        status: "done"
      });
      message.success("上传成功");
    })
    .catch((e) => {
      message.error(e.message);
    });
};

/* 粘贴图片上传服务器并插入编辑器 */
const onPaste = (e) => {
  console.log(e);
  const items = (e.clipboardData || e.originalEvent.clipboardData).items;
  console.log(items);
  let hasFile = false;
  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf("image") !== -1) {
      let file = items[i].getAsFile();
      const item: ItemType = {
        file,
        uid: (file as any).lastModified,
        name: file.name
      };
      uploadFile(<File>item.file)
        .then((result) => {
          const addPath = "![" + result.name + "](" + FILE_SERVER + result.path + ")\n\r";
          content.value = content.value + addPath;
        })
        .catch((e) => {
          message.error(e.message);
        });
      hasFile = true;
    }
  }
  if (hasFile) {
    e.preventDefault();
  }
};

/* 保存编辑 */
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 reload = () => {
  loading.value = true;
  // 加载项目成员
  listAssetsUser({assetsId:props.data?.assetsId}).then(data => {
    assetsUsers.value = data
  })
  // 加载企业信息
  const companyId = props.data?.companyId;
  // pageCompany({companyId}).then(res => {
  //   form.tenantId = undefined;
  //   const list = res?.list;
  //   if(list && list.length > 0){
  //     form.tenantId = list[0].tenantId;
  //   }
  // })
};

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      content.value = "";
      requirement.value = "";
      if (props.data) {
        assignObject(form, props.data);
        images.value = [];

        // if (props.data.file1) {
        //   file1.value = JSON.parse(props.data.file1);
        // }
        if (props.data.openPort) {
          form.openPort = props.data.openPort.split(",");
        }
        if (props.data.configuration) {
          form.configuration = props.data.configuration.split(",");
        }
        isUpdate.value = true;
        reload();
      } else {
        isUpdate.value = false;
        editStatus.value = true;
      }
    } else {
      resetFields();
    }
  }
);
</script>

<style lang="less">
.tab-pane {
  min-height: 300px;
}

.ml-10 {
  margin-left: 5px;
}

.upload-text {
  margin-right: 70px;
}

.upload-image {
  margin-bottom: 30px;
  display: flex;
  justify-content: center;
}
</style>
