<!--
 * @Description: 项目管理
 * @Author: xiaofengzhou
 * @Email: 2946471396@qq.com
 * @Date: 2022-08-03 14:10:07
 * @LastEditTime: 2022-10-31 15:21:46
 * @LastEditors: xiaofengzhou
-->

<template>
  <a-layout>
    <a-layout-header>
      <a-row>
        <a-col :span="2" style="text-align:center">
          项目名称:
        </a-col>
        <a-col :span="4">
          <a-input v-model="projectName" placeholder="请输入项目名称" />
        </a-col>
        <a-col :span="18">
          &nbsp;&nbsp;
          <a-button type="normal" @click="clearInput()">重置</a-button>
          &nbsp;&nbsp;
          <a-button type="primary" @click="valueSearch">查询</a-button>
        </a-col>
      </a-row>
    </a-layout-header>
    <a-layout-content>

      <div class="table-btn">
        <a-button type="normal" @click="showRes">
          <span class="iconfont icon-repo" style="color: #006cff;font-size: 14px;">&nbsp;脚本库</span>
        </a-button>
        <a-button type="normal" @click="addNewProject">
          <span class="iconfont icon-add" style="color: #006cff;font-size: 14px;">新建项目</span>
        </a-button>
      </div>
      <a-table :dataSource="dataSource" :columns="columns" :pagination="false">
        <template slot="action" slot-scope="text, record">
          <a-spin tip="生成中" v-if="record.projectId === currentPublish">
            <div class="spin-content">
              <span>
                <a @click="handleEditFrom(record)">修改</a>&nbsp;
                <a @click="showScriptDown(record)">下载</a>&nbsp;
                <a @click="generateProjects(record)">生成</a>&nbsp;
                <a @click="showRealeaseModal(record)">发布</a>&nbsp;
                <a @click="showLogsModal(record)">日志</a>&nbsp;
                <a @click="removePromotShow(record)">删除</a>&nbsp;
                <a @click="copyProjects(record)">复制</a>&nbsp;
              </span>
            </div>
          </a-spin>

          <span v-else>
            <a @click="handleEditFrom(record)">修改</a>&nbsp;
            <a @click="showScriptDown(record)">下载</a>&nbsp;
            <a @click="generateProjects(record)">生成</a>&nbsp;
            <a @click="showRealeaseModal(record)">发布</a>&nbsp;
            <a @click="showLogsModal(record)">日志</a>&nbsp;
            <a @click="removePromotShow(record)">删除</a>&nbsp;
            <a @click="copyProjects(record)">复制</a>&nbsp;
          </span>


        </template>
        <template slot="tooltip" slot-scope="text, record">
          <a-tooltip>
            <template #title>
              项目名称:{{ record.projectName }}<br />
              Project Name:{{ record.projectNameEn }}
            </template>
            &nbsp;{{ record.projectName }}
          </a-tooltip>
        </template>
      </a-table>
      <a-pagination @change="onShowPageChange" v-model="pagination.current" :total="pagination.totalCount"
        :page-size="10" />
    </a-layout-content>

    <AddProjectModalVue ref="AddProjectModalVue" @AddProjectModalVue="AddProjectModalVue" />
    <ScriptManageModalVue ref="ScriptManageModalVue" />
    <ProjectRealeaseVue ref="ProjectRealeaseVue" @getData="reGetData" />
    <DownloadProjectModalVue ref="DownloadProjectModalVue" />
    <PublishLogs ref="PublishLogs" />
    <ConfirmDeletion :delete="hanDelOk" ref="ConfirmDeletion" />
    <GenerateLogs ref="GenerateLogs" @GenerateLogs="GenerateLogs" />
    <CopyProject ref="CopyProject" @CopyProject="CopyProject" />
  </a-layout>

</template>
<script>
import { time } from '../../../../packages/utils/time'
import ConfirmDeletion from '../../../components/ConfirmDeletion';
import PublishLogs from './publishLogs/PublishLogs.vue'
import DownloadProjectModalVue from './downloadProject/DownloadProjectModal.vue';
import ProjectRealeaseVue from './projectRelease/ProjectRealease.vue';
import AddProjectModalVue from './AddProjectModal.vue';
import ScriptManageModalVue from './scriptLibrary/ScriptManageModal.vue';
import CopyProject from './copyProject/CopyProject.vue'
import '../../../../static/icons2/iconfont.css'
import { delProject, manageProjectList, getPubKey } from "../../../../packages/api/manage.js";
import GenerateLogs from '../projectManage/generate/GenerateLogs.vue'
const dbtype = {
  0: 'oracle',
  1: 'pg',
  2: 'mysql'
}
export default {
  components: {
    AddProjectModalVue,
    ScriptManageModalVue,
    ProjectRealeaseVue,
    DownloadProjectModalVue,
    PublishLogs,
    ConfirmDeletion,
    GenerateLogs,
    CopyProject
  },
  props: [],
  data() {
    return {
      currentPublish: "",
      currentDel: '',
      searchDataSouce: {},
      dbtype,
      projectName: "",
      modalVisible: false,
      pagination: {
        current: 1,
        pageSize: 10,
        totalCount: 10,
      },
      action: 'view',
      dataSource: [],
      // 模板选择select
      allTempSel: [],
      columns: [
        {
          title: "ID",
          dataIndex: "num",
          key: "projectId",
        },
        {
          title: "项目名称",
          dataIndex: "projectName",
          key: "projectName",
          scopedSlots: { customRender: "tooltip" },

        },
        {
          title: "包名",
          dataIndex: "packageName",
          key: "packageName",
          align: 'center'
        },
        {
          title: "版本号",
          dataIndex: "version",
          key: "version",
          align: 'center'
        },
        {
          title: "数据库类型",
          dataIndex: "dbType",
          key: "dbType",
          align: 'center'
        },
        {
          title: "引用模板",
          dataIndex: "template.templateName",
          key: "templateName",
          align: 'center'
        },
        {
          title: "项目管理状态",
          dataIndex: "status",
          key: "status",
          customRender: (text, record, index) => {
            if (record.status === '0') {
              return "待配置"
            } else if (record.status === '1') {
              return "已配置"
            } else if (record.status === '2') {
              return "生成中"
            } else if (record.status === '3') {
              return "已生成"
            } else if (record.status === '4') {
              return "生成失败"
            } else if (record.status === '5') {
              return "发布中"
            } else if (record.status === '6') {
              return "已发布"
            } else if (record.status === '7') {
              return "部署失败"
            }
          },
          align: 'center'
        },
        {
          title: "操作人",
          dataIndex: "operator.userName",
          key: "userName",
        },
        {
          title: "操作时间",
          dataIndex: "createTime",
          key: "createTime",
          customRender: (text, record, index) => {
            if (record.updateTime !== null) {
              return time.formatTime(record.updateTime, "yyyy/MM/dd")
            } else {
              return time.formatTime(record.createTime, "yyyy/MM/dd")
            }

          },
          align: 'center'
        },

        {
          title: "操作栏",
          key: "action",
          scopedSlots: { customRender: "action" },
          customHeaderCell: () => ({
            style: {
              textAlign: 'center',  //头部单元格水平居中
            },
          }),
          align: 'center'
        },
      ],
      publicKey: '',
      isConnectWebSocket: false
    };
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo
    },
  },
  watch: {},
  created() {
    this.getData(1, 10)
    this.getPubKey()
  },

  mounted() {
    // this.initWebSocket()

  },
  methods: {
    reGetData() {
      // console.log("这个事件被触发了");
      this.getData(this.pagination.current, 10)

    },
    getPubKey() {
      getPubKey().then(res => {
        this.publicKey = res.message
        this.$store.dispatch("setPublicKey", res.message)
      })
    },

    AddProjectModalVue() {
      this.getData(this.pagination.current, 10)
    },
    GenerateLogs() {
      this.getData(this.pagination.current, 10)

    },
    // 项目生成
    generateProjects(record) {
      this.$refs.GenerateLogs.init(record)

      this.$refs.GenerateLogs.visible = true
      // 判断websocket是否连接成功
      // if (this.currentPublish !== "") {
      //   notification.warning({
      //     message: '系统提示',
      //     description: '当前有生成任务进行中,请等待',
      //     duration: 4
      //   })
      // } else {
      //   this.currentPublish = record.projectId
      //   generateProject(record.projectId).then((res) => {
      //     if (res) {
      //       notification.success({
      //         message: '系统提示',
      //         description: res.message,
      //         duration: 4
      //       })
      //       this.currentPublish = ""
      //     }
      //   }).catch(err => {
      //     if (err) {
      //       notification.error({
      //         message: '系统提示',
      //         description: "生成失败",
      //         duration: 4
      //       })
      //       this.currentPublish = ""
      //     }
      //   })
      // }

      // 连接websocket


    },
    // 页码计算
    calcPageNo(total, pageNo = 1, pageSize = 10, delNum = 1) {
      const restNum = total - pageSize * (pageNo - 1)
      let pageNoDiff = Math.floor((delNum - restNum) / pageSize) + 1
      pageNoDiff < 0 && (pageNoDiff = 0)
      pageNo = pageNo - pageNoDiff
      pageNo < 1 && (pageNo = 1)
      return pageNo
    },
    // 查询数据
    getData(pageNum = 1, pageSize = 10, projectName = '') {
      manageProjectList({ pageNum: pageNum, pageSize: pageSize, projectName: projectName }).then((res) => {
        let result = res.result.data
        result.map((item, index) => {
          item.key = item.projectId
          item.num = (this.pagination.current - 1) * 10 + index + 1
          item.middlewares.map((items, index) => {
            if (items.middlewareType === '0') {
              if (items && items.property && items.property.dbType !== undefined && items.property.dbType !== null) {
                item.dbType = this.dbtype[items.property.dbType]
              }
            }
          })
        })
        this.dataSource = result
        this.searchDataSouce = result
        this.pagination.totalCount = res.result.totalCount
      })
    },
    // 分页
    onShowPageChange(page, pagesize) {
      // 修改当前页码
      this.pagination.current = page
      this.getData(page, pagesize, this.projectName === "" ? "" : this.projectName)
    },
    // 查询
    valueSearch() {
      this.getData(1, 10, this.projectName)
    },

    // 显示日志
    showLogsModal(record) {
      this.$refs.PublishLogs.visible = true
      this.$refs.PublishLogs.init(record)
    },
    // 编辑
    handleEditFrom(record) {
      this.$refs.AddProjectModalVue.init('edit', JSON.parse(JSON.stringify(record)))
      this.$refs.AddProjectModalVue.visible = true
    },
    //清空查找条件
    clearInput() {

      this.projectName = "";
      // 重新请求列表数据
      this.getData(1, 10)

    },
    // 新建项目的时候把数据清空
    addNewProject() {
      this.$refs.AddProjectModalVue.init('add')
      this.$refs.AddProjectModalVue.visible = true
      this.$refs.AddProjectModalVue.publicKey = this.publicKey

    },
    showRealeaseModal(record) {
      this.$refs.ProjectRealeaseVue.visible = true
      this.$refs.ProjectRealeaseVue.init(record)
      this.$refs.ProjectRealeaseVue.publicKey = this.publicKey


    },
    // 脚本管理
    showRes() {
      this.$refs.ScriptManageModalVue.visible = true
    },
    // 脚本下载
    showScriptDown(record) {
      this.$refs.DownloadProjectModalVue.visible = true
      this.$refs.DownloadProjectModalVue.init(record)

    },
    // 删除确认提示
    removePromotShow(record) {
      this.$refs.ConfirmDeletion.init()
      this.currentDel = record.projectId
      this.$refs.ConfirmDeletion.visible = true
    },
    copyProjects(record) {
      this.$refs.CopyProject.init(record)
      this.$refs.CopyProject.visible = true
    },
    CopyProject() {
      this.getData(this.pagination.current, 10)
    },

    // 确认删除
    hanDelOk() {
      delProject(this.currentDel).then((res) => {
        this.$message.success("删除成功")
        this.$refs.ConfirmDeletion.visible = false
        let calcPage = this.calcPageNo(this.pagination.totalCount, this.pagination.current, 10, 1)
        this.getData(calcPage, 10)
      })
    }
  },
};
</script>
<style scoped lang="less">
.ant-layout-header {
  background: fixed white;
}

.ant-pagination {
  text-align: right;
  margin-top: 20px;
}

.ant-layout-content {
  // margin-top: 20px;
  /* // border: 1px solid red; */
}

.table-btn {
  text-align: right;
  // margin-bottom: 20px;
}

.table-btn button {
  margin-left: 5px;
}

.templateSet .ant-row {
  margin-top: 20px;
}

.databaseConfig {
  width: 220px;
  height: 30px;
  border-radius: 15px;
  text-align: center;
  background-color: #f0efef;
}

/deep/ .ant-table-tbody tr {
  background-color: white;
}
</style>
