<template>
  <div class="app_container">
    <div class="content flex">
      <!-- 左侧产线列表 -->
      <div class="left_box">
        <div class="title flex mb-4 justify-between">
          <div class="logtitle">
            <div class="line"></div>
            {{ $t("SERVICE_MANAGEMENT") }}
          </div>
          <a-button class="add-btn" type="primary" @click="handleAdd">
            <a-icon type="plus" /> {{ $t("ADD") }}
          </a-button>
        </div>
        <div ref="line_box" class="line_box">
          <a-list
            class="cursor"
            :loading="loading"
            item-layout="horizontal"
            :data-source="clientData"
          >
            <a-list-item
              slot="renderItem"
              slot-scope="item"
              class="status_card justify-between cursor"
              :class="{ active: clientId === item.id }"
              @click="handleItem(item)"
            >
              <div class="flex">
                <div class="left_content flex flex-wrap">
                  <div class="title_card flex">
                    <div class="status_title">
                      {{ item.serverName }}
                    </div>
                  </div>
                  <div class="duration flex">
                    {{ item.serverPath }}
                  </div>
                </div>
              </div>
              <div class="btn_list">
                <a-button
                  :title="$t('LOG_MONITOR')"
                  type="link"
                  class="btn_realTime btn"
                  @click="handleRealTimeMointor(item)"
                >
                  <Icon type="icon-data-fund" :size="16" />
                </a-button>
                <a-button
                  :title="$t('EDIT')"
                  type="link"
                  class="btn_edit btn"
                  @click="handleEdit(item)"
                >
                  <Icon type="icon-edit-edit" :size="16" />
                </a-button>
                <a-button
                  :title="$t('DELETE')"
                  type="link"
                  class="btn_disable btn"
                  @click="handleDelete(item)"
                >
                  <a-icon type="delete" style="color: #f5222f" />
                </a-button>
              </div>
            </a-list-item>
          </a-list>
        </div>
      </div>
      <!-- 右侧产线设备列表 -->
      <div class="right_box" style="width: 100%">
        <MomTable
          ref="MomTable"
          row-key="code"
          :query-param="queryParam"
          :query-param-item="queryParamItem"
          :columns="columns"
          :data-source="client_log_list"
          :page.sync="page"
          :total="total"
          :show-util-operator="false"
          :action-buttons="tableAction"
          :pagination="false"
          :mega-extend="{
            rowIndex: false,
            rowAction: {
              width: 62,
            },
          }"
          @search="search"
        >
          <div slot="toolbar">
            <div class="log_box">
              <div class="logtitle">
                <div class="line"></div>
                {{ $t("LOG_FILE") }}
              </div>
            </div>
          </div>
        </MomTable>
      </div>
    </div>

    <!-- 编辑抽屉 -->
    <MegaDrawer
      width="520"
      :title="$t('SERVER_CONFIG')"
      :visible="drawerVisible"
      @close="drawerVisible = false"
      @cancel="handleCancel"
      @ok="handleSave"
    >
      <a-form-model
        slot="main"
        ref="ruleForm"
        layout="vertical"
        :model="form"
        :rules="rules"
      >
        <a-form-model-item :label="$t('SERVER_NAME')" prop="serverName">
          <a-input
            v-model="form.serverName"
            :placeholder="$t('PLACEENTER')"
            @change="
              form.serverName = form.serverName.slice(0, 64).replace(/\s+/g, '')
            "
          />
        </a-form-model-item>
        <!-- <a-form-model-item :label="$t('PROTOCOL_TYPE')" prop="protocolType">
          <a-radio-group v-model="form.protocolType">
            <a-radio
              v-for="item in protocolTypeList"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</a-radio
            >
          </a-radio-group>
        </a-form-model-item> -->
        <a-form-model-item :label="$t('LOG_LEVEL')" prop="logLevel">
          <a-radio-group v-model="form.logLevel">
            <a-radio
              v-for="item in logLevelList"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</a-radio
            >
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item :label="$t('PROJECT_PATH')" prop="serverPath">
          <a-input v-model="form.serverPath" :placeholder="$t('PLACEENTER')" />
        </a-form-model-item>
        <a-form-model-item
          :label="$t('DOMAIN_NAME_PATH')"
          prop="domainServerPath "
        >
          <a-input
            v-model="form.domainServerPath"
            :placeholder="$t('PLACEENTER')"
          />
        </a-form-model-item>
        <a-form-model-item :label="$t('LOG_PATH')" prop="logPath">
          <a-input v-model="form.logPath" :placeholder="$t('PLACEENTER')" />
        </a-form-model-item>
      </a-form-model>
    </MegaDrawer>
  </div>
</template>
<script>
import { deleteLeafArray } from "@mega-apps/utils";
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: {
    MegaDrawer,
    Icon,
  },
  data() {
    return {
      drawerVisible: false, // 抽屉是否显示字段
      loading: false, // 加载
      clientData: [], // 产线列表数据
      client_log_list: [], // 产线设备数据
      // 查询的表单的配置项
      queryParam: {
        logId: "",
        startTime: this.formatDate(new Date()),
        endTime: "",
      },
      form: {
        id: "",
        serverName: "",
        logLevel: "INFO",
        // protocolType: "http",
        serverPath: "",
        logPath: "/app/logs/",
      }, // 表单
      columns: [
        {
          dataIndex: "fileName", // 文件名称
          sorter: false,
          title: () => this.$t("FILE_NAME"),
          ellipsis: true,
        },
        {
          dataIndex: "fileSize", // 文件大小
          sorter: false,
          ellipsis: true,
          title: () => this.$t("FILE_SIZE"),
        },
        {
          dataIndex: "filePath", // 文件路径
          sorter: false,
          ellipsis: true,
          title: () => this.$t("FILE_PATH"),
        },
      ],
      page: 1, // 页码
      total: 0,
      tableAction: [
        (h, value, a, b) => {
          const { text, record } = value;
          if (record.dirFlag === false) {
            return (
              <span
                onClick={() => this.handleDownload(record)}
                style="cursor: pointer;"
                title={this.$t("DOWNLOAD")}>
                {<Icon type="icon-cur-cloud-download" size={16} />}
              </span>
            );
          }
          return null;
        },
      ],
      isLoading: false,
      logLevelList: [
        {
          label: "INFO",
          value: "INFO",
        },
        {
          label: "DEBUG",
          value: "DEBUG",
        },
      ],
      // protocolTypeList: [
      //   {
      //     label: "http",
      //     value: "http",
      //   },
      //   {
      //     label: "https",
      //     value: "https",
      //   },
      // ],
      clientId: "",
      curLogData: null,
    };
  },
  computed: {
    rules() {
      return {
        serverName: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
        logLevel: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        // protocolType: [
        //   {
        //     required: true,
        //     message: this.$t("PLACESELECT"),
        //     trigger: "change",
        //   },
        // ],
        serverPath: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          // {
          //   // eslint-disable-next-line require-await
          //   validator: async (_rule, value) => {
          //     if (!/^http:\/\//.test(value)) {
          //       // eslint-disable-next-line prefer-promise-reject-errors
          //       return Promise.reject(this.$t("WRONG_PATH"));
          //     }
          //     return Promise.resolve();
          //   },
          //   trigger: "blur",
          // },
        ],
        logPath: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      };
    },
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        logId: {
          itemType: "input",
          label: () => `${this.$t("LOG")}ID`,
        },
        startTime: {
          itemType: "date",
          showTime: true,
          format: "YYYY-MM-DD HH:mm",
          valueFormat: "YYYY-MM-DD HH:mm",
          label: () => this.$t("START_TIME"),
        },
        endTime: {
          itemType: "date",
          showTime: true,
          format: "YYYY-MM-DD HH:mm",
          valueFormat: "YYYY-MM-DD HH:mm",
          label: () => this.$t("END_TIME"),
        },
      });
    },
  },
  created() {
    this.getClientData();
  },
  methods: {
    handleAdd() {
      this.form = {
        id: "",
        serverName: "",
        // protocolType: "http",
        logLevel: "INFO",
        serverPath: "",
        logPath: "/app/logs/",
      }; // 表单
      this.drawerVisible = true;
    },
    handleEdit(item) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/monitor/log/client/get-by-id/${item.id}`
        )
        .then((res) => {
          const { data } = res.data;
          this.form = { ...data };
          this.drawerVisible = true;
        });
    },
    handleDelete({ id }) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("DELETE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/monitor/log/client/${id}`)
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.getClientData();
            });
        },
      });
    },
    // 获取产线列表
    getClientData() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/monitor/log/client/list`)
        .then((res) => {
          this.isLoading = true;
          const { data } = res.data;
          if (data && data.length > 0) {
            if (this.clientData.length === 0) {
              this.clientId = data[0].id;
            }
            this.clientData = data;
            let index = 0;
            if (this.clientId) {
              index = data.findIndex((item) => item.id === this.clientId);
            }
            this.getClientLogData(data[index]);
          } else {
            this.clientData = [];
          }
        });
    },
    handleRealTimeMointor({ id }) {
      window.open(`/upms/system/monitor/logMonitor/realTime?id=${id}`);
    },
    // 获取产线设备列表
    getClientLogData(item) {
      this.curLogData = item;
      const url =
        item.domainServerPath && item.domainServerPath != null
          ? item.domainServerPath
          : item.serverPath;
      this.$axios
        .get(
          // `${item.protocolType}://${item.serverPath}/api/monitor/log/list-file`,
          `${url}/api/monitor/log/list-file`,
          {
            headers: { Authorization: "" },
            params: {
              page: "1",
              size: "50",
              logPath: item.logPath,
              startTime: this.queryParam.startTime,
              endTime: this.queryParam.endTime,
            },
          }
        )
        .then((res) => {
          const { data } = res.data;
          deleteLeafArray(data, "children");
          this.client_log_list = data || [];
        });
    },
    search(params) {
      if (!this.curLogData) return;
      const searchParams = {
        ...params,
        logPath: this.curLogData.logPath,
      };
      const url =
        this.curLogData.domainServerPath &&
        this.curLogData.domainServerPath != null
          ? this.curLogData.domainServerPath
          : this.curLogData.serverPath;
      this.$axios
        .get(`${url}/api/monitor/log/list-file`, {
          headers: { Authorization: "" },
          params: searchParams,
        })
        .then((res) => {
          const { data } = res.data;
          deleteLeafArray(data, "children");
          this.client_log_list = data || [];
        });
    },
    formatDate(value) {
      const date = new Date(value);
      const y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? `0${MM}` : MM;
      let d = date.getDate();
      d = d < 10 ? `0${d}` : d;
      return `${y}-${MM}-${d} 00:00`;
    },
    formatDateTime(value) {
      const date = new Date(value);
      const y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? `0${MM}` : MM;
      let d = date.getDate();
      d = d < 10 ? `0${d}` : d;
      let h = date.getHours();
      h = h < 10 ? `0${h}` : h;
      let m = date.getMinutes();
      m = m < 10 ? `0${m}` : m;
      return `${y}-${MM}-${d} ${h}:${m}`;
    },
    handleItem(data) {
      this.clientId = data.id;
      this.getClientLogData(data);
    },
    // 保存
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            this.$axios
              .put(
                `${ApiConstant.PREFIX_CORE}/api/monitor/log/client`,
                this.form
              )
              .then(() => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.getClientData();
                this.handleCancel();
              });
          } else {
            this.$axios
              .post(
                `${ApiConstant.PREFIX_CORE}/api/monitor/log/client`,
                this.form
              )
              .then(() => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.getClientData();
                this.handleCancel();
              });
          }
        }
      });
    },
    handleDownload({ filePath }) {
      window.open(
        `${
          ApiConstant.PREFIX_CORE
        }/api/monitor/log/download?filePath=${encodeURIComponent(filePath)}`
      );
    },
    // 取消
    handleCancel() {
      this.drawerVisible = false;
    },
  },
};
</script>
<style lang="less" scoped>
@import (optional, once) "@/theme";

.app_container {
  flex-wrap: wrap;
}
.status_list {
  width: 100%;
  height: 52px;
  border-bottom: 2px solid #eff2f4;
  padding-left: 28px;
  .status_item {
    height: 100%;
    align-items: center;
    font-size: 16px;
    font-weight: 400;
    color: #666;
    margin-right: 36px;
    .status_item_color {
      width: 14px;
      height: 14px;
      border-radius: 2px;
      margin-right: 8px;
    }
  }
}
.title {
  align-items: center;
  margin-top: 14px;
  i {
    margin-right: 5px;
  }
}
.left_box {
  max-width: 485px;
  border-right: solid 2px #eef1f4;
  padding: 0 25px;
  min-height: 100%;
  .add-btn {
    padding: 0 10px;
    background-color: @primary-color !important;
  }
}
.right_box {
  width: calc(100% - 500px);
}
.num_box {
  min-height: 48px;
  align-items: center;
  padding: 10px 20px;
  background: rgba(14, 168, 208, 0.1);
  border: 1px solid rgba(14, 168, 208, 0.6);
  border-radius: 8px;
  margin: 20px 0;
  .num_item {
    width: 200px;
    height: 100%;
    align-items: center;
    font-size: 16px;
    font-weight: 400;
    color: @primary-color;
  }
}
.line_box {
  width: 435px;
}
.status_card {
  width: 100%;
  margin-bottom: 12px;
  padding: 18px;
  min-width: 415px;
  height: 75px;
  background: #f5f7fb;
  border: 1px solid #dfe2e8;
  border-radius: 4px;
  .flex {
    align-items: center;
  }
  .btn_list {
    margin-top: -7px;
    width: 80px;
    text-align: right;
  }
  .status_icon_box {
    position: relative;
    width: 39px;
    height: 39px;
    margin-right: 18px;
  }
  .title_card {
    width: 100%;
    .status_title {
      font-size: 16px;
      font-weight: 400;
      color: #333;
    }
  }
  .duration {
    font-size: 14px;
    font-weight: 400;
    color: #999;
  }
  .gray {
    margin: 0;
    display: inline;
    font-size: 14px;
    color: #999;
  }
  &:hover {
    box-shadow: 0 0 6px #3db8d8;
    color: #3db8d8;
    // .title_card {
    //   .status_title {
    //     color: #3db8d8;
    //   }
    // }
    // .duration {
    //   color: #3db8d8;
    // }
    .gray {
      color: gray;
    }
  }
  &.active {
    background: rgba(61, 184, 216, 0.15);
    color: #333;
    border-left: solid 5px #0ea9d2;
  }
}
.gray {
  color: gray;
}
.client_log_list {
  .eqp_item {
    width: 100%;
    min-width: 186px;
    height: 105px;
    border-radius: 8px;
    overflow: hidden;
    background: #fff;
    box-shadow: 0 1px 6px #cfd7e8;
    .eqp_item_top {
      align-items: center;
      width: 100%;
      height: 33px;
      font-size: 14px;
      font-weight: 400;
      color: #fff;
      span {
        margin-left: 12px;
      }
    }
    .eqp_item_con {
      width: 100%;
      height: 72px;
      margin-top: 5px;
      .eqp_item_l {
        width: 60px;
        height: 60px;
        overflow: hidden;
        margin-left: 5px;
        margin-right: 10px;
        img {
          width: 100%;
        }
      }
      .eqp_item_r {
        font-size: 16px;
        font-weight: 400;
        color: #666;
        .eqp_item_code {
          font-size: 14px;
          color: #999;
          margin-top: 5px;
        }
      }
    }
  }
}
.btn {
  padding: 0;
  margin: 0;
  background: none !important;
  box-shadow: none;
  border: none;
}
.btn_edit i {
  font-size: 14px;
  color: #3dc2e5;
}
.btn_disable .icon-jinyong1 {
  margin-left: 8px;
  font-size: 16px;
  color: #fc4343;
}
.btn_disable .icon-qiyong {
  margin-left: 8px;
  font-size: 17px;
  color: #52fc43;
}
.log_box {
  padding: 6px;
}
.logtitle {
  display: flex;
  align-items: center;
  font-size: 16px;
  padding-bottom: 0;
}
.line {
  width: 4px;
  height: 16px;
  background: linear-gradient(180deg, #01c9fe, #0ea9d2);
  margin-right: 12px;
}
.btn_box {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  text-align: center;
}
/deep/ .ant-checkbox-wrapper {
  margin-right: 30px;
}

/deep/ .ant-list-split .ant-list-item.status_card:last-child {
  border-bottom: 1px solid #dfe2e8;
}
</style>
