<template>
  <div class="project_content">
    <el-card shadow="never" class="commont-cart">
      <el-form ref="searchForm" :model="searchForm" @submit.native.prevent class="clear-fix">
        <div class="left-content">
          <el-row class="tool-common-wrap">
            <el-col :span="24">
              <div class="search-wrap">
                <el-input placeholder="请输入搜索内容" v-model="searchForm.subject" clearable @keyup.enter.native="search">
                  <span slot="append" @click="search"><i class="iconfont icon-sousuo2"/></span>
                </el-input>
              </div>
              <div class="operate-wrap">
                <el-tooltip effect="dark" content="添加" :enterable="false" placement="top">
                  <el-button type="text" icon="el-icon-circle-plus-outline" @click="userHandle('add')" />
                </el-tooltip>
              </div>
              <reload class="float-r" />
            </el-col>
          </el-row>
        </div>
      </el-form>
      <!-- 项目列表-卡片模式 -->
      <el-row :gutter="20" class="cardList" v-for="(o, index) in tableList" :key="index">
        <el-col :span="6" v-for="(item, tIndex) in o" :key="tIndex"  :offset="0" >
          <el-card :body-style="{ padding: '0px'}" >
            <div style="padding: 14px;cursor: pointer;" @click="projectDetail(item.id)">
              <div class=" clear-fix">
                <p class="clear-fix">
                  <el-button @click.stop="handleDelete(item,)" class="float-r margin-l10" type="danger" icon="el-icon-delete" circle></el-button>
                  <el-button @click.stop="projectEdit(item.id)" class="float-r" type="primary" icon="el-icon-edit" circle></el-button>
                </p>
                <h2>
                  {{ item.name }}
                </h2>
                <p style="padding:5px 0">描述：{{item.description}}</p>
                <p>代理服务数量: <span>{{parseInt(Math.random()*10)+1}}</span>     </p>
                <p>业务服务数量: <span>{{parseInt(Math.random()*10)+1}}</span>     </p>
                <p>消息流数量: <span>{{parseInt(Math.random()*10)+1}}</span>     </p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

            <el-pagination
              :page-size="page.pageSize"
              :current-page.sync="page.pageNum"
              background
              @current-change="getDataNext"
              :total="page.total"
            />
      <project-info :ProjectInfo="ProjectInfo" @confirm="handleSubmit()" :value="value"  @changedialog="changechangeValue"  />

  </div>
</template>

<script>
import ProjectInfo from './ProjectInfo'
import { queryProjectList, getProjectListDetail, deleteProjectList } from '@/api/project_list'
import EsbServiceListMixins from '@/mixins/esb_service_list_mixins'
import { createNamespacedHelpers } from 'vuex'
const { mapGetters, mapMutations } = createNamespacedHelpers('app')
export default {
  mixins: [EsbServiceListMixins],
  components: {
    ProjectInfo
  },
  data() {
    return {
      projectList: [],
      page: {
        pageNum: 0,
        pageSize: 8,
        total: 0
      },
      btncontent: '确定',
      value: false, // 是否显示弹框
      ProjectInfo: {}// 详情
    }
  },
  mounted() {

  },
  methods: {
    ...mapMutations(['setProjectID', 'setProjectName']),
    handleDelete(item, event) {
      this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableLoading = true
        deleteProjectList(item.id).then((rt) => {
          if (rt.status === '200') {
            this.tableLoading = false
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getDataCurrent()
          } else {
            // 删除失败
            this.$message({
              message: '删除失败',
              type: 'error'
            })
          }
        }).catch(e => {
          this.tableLoading = false
          if (e.response.data.status === '500') {
            const errData = e
            // console.log(errData.data[0].PROXY[0].name);
            const proxyData = errData.data[0].PROXY || []
            const arr = []
            for (var i = 0; i < proxyData.length; i++) {
              arr.push(proxyData[i].name)
              // console.log(arr);
            }
            const businessData = errData.data[0].BUSINESS || []
            const businessArr = []
            for (var i = 0; i < businessData.length; i++) {
              businessArr.push(businessData[i].name)
              // console.log(businessArr);
            }

            const flowData = errData.data[0].FLOW || []
            const flowArr = []
            for (var i = 0; i < flowData.length; i++) {
              flowArr.push(flowData[i].name)
              // console.log(flowArr);
            }

            // console.log(arr);
            this.$message({
              message: `删除失败,正被以下资源依赖：${arr}、${businessArr}、${flowArr}`,
              type: 'error'
            })
          }
        })
      }).catch(() => {})
    },
    handleCurrentChange() {},
    // 打开弹框，添加或删除
    userHandle(type) {
      if (type === 'add') {
        // this.handleCurrentChange({})
        this.ProjectInfo = {}
        this.value = true
      }
      if (type === 'edit') {
        this.value = true
      }
    },
    // 关闭
    changechangeValue(val) {
      if (val == false) {
        this.value = false
      }
    },
    projectDetail(val) {
      this.setProjectID(val.id)
      this.setProjectName(val.id)
      localStorage.setItem('projectID', val.id)
      localStorage.setItem('projectName', val.name)
      this.$router.push({
        path: '/project_list/project_page'
      })
    },
    // 详情

    async projectEdit(id, event) {
      this.tableLoading = true
      const rt = await getProjectListDetail(id).catch(e => {
        this.tableLoading = false
        return Promise.reject(e)
      })

      if (rt.status === '200') {
        this.ProjectInfo = rt.data
        this.userHandle('edit')
      }
    },

    // 数组处理
    flitterArr(arr) {
      const baseArray = [1, 2, 3, 4, 5, 6, 7, 8]
      const len = arr.length
      const n = 4 // 假设每行显示4个
      const lineNum = len % 4 === 0 ? len / 4 : Math.floor((len / 4) + 1)
      const res = []
      for (let i = 0; i < lineNum; i++) {
        // slice() 方法返回一个从开始到结束（不包括结束）选择的数组的一部分浅拷贝到一个新数组对象。且原始数组不会被修改。
        const temp = arr.slice(i * n, i * n + n)
        res.push(temp)
      }
      return res
    },
    // 获取列表
    async getData() {
      this.tableLoading = true
      // const rt = await queryProxyService({
      const rt = await queryProjectList({
        filters: [
          {
            key: 'name',
            opt: 'LIKE',
            type: 'S',
            value: this.searchForm.subject
          }
          // {
          //   key: 'description',
          //   opt: 'LIKE',
          //   type: 'S',
          //   value: this.searchForm.subject
          // },
        ],
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize
      }).catch(e => {
        this.tableLoading = false
        return Promise.reject(e)
      })

      if (rt.status === '200') {
        this.tableLoading = false
        this.tableList = this.flitterArr(rt.data.list || [])
        this.page.total = rt.data.total
        return Promise.resolve(rt)
      } else {
        this.tableLoading = false
      }
    },
    getDataNext(val) {
      // 分页
      this.page.pageNum = val
      this.getData()
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.project_content{
  background-color: #ffffff;
  padding-bottom: 20px;
}
.el-pagination{
  text-align: center;
}
 .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .cardList:nth-of-type(1) {
      padding-top: 20px;
    }
</style>
