<template>
  <div class="project_content">
    <el-card shadow="never" class="commont-cart">
      <div class="search-header">
        <div class="tool-common-wrap">
          <div class="title">项目列表</div>
          <div class="search-wrap">
            <quick-query class="search-title" ref="quick" :placeholder="placeholder" :is-date="false"
              @quickSearch="quickSearch" />
          </div>
          <div class="btn-wrap">
            <el-button @click="rest()"> 刷新 </el-button>
            <el-button type="primary" @click="userHandle('add')">添加</el-button>
          </div>
        </div>
      </div>
      <!-- 项目列表-卡片模式 -->
      <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)">
              <div class=" clear-fix">
                <div class="clear-fixs">
                  <div class="button-right">
                    <el-tooltip class="item float-r margin-l10"  content="删除" placement="top">
                      <el-button type="text" class="el-icon-delete" @click.stop="handleDelete(item)" />
                    </el-tooltip>
                    <el-tooltip class="item float-r" content="编辑" placement="top">
                      <el-button type="text" class="el-icon-edit"  @click.stop="projectEdit(item.id)" />
                    </el-tooltip>
                  </div>

                  <!-- <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> -->
                  <h2 class="hiddenText" :title="item.name">
                    {{ item.name }}
                  </h2>
                </div>

                <!-- <p class="hiddenText1" :title="item.description">这是个描述信息业务流程管理平台</p> -->
                <p>代理服务数量: <span>{{ item.proxyServiceNum }}</span> </p>
                <p>业务服务数量: <span>{{ item.businessServiceNum }}</span> </p>
                <p>消息流数量: <span>{{ item.flowNum }}</span> </p>
                <!-- <p>适配器数量: <span>{{item.connectorNum}}</span>     </p> -->
                <p>适配器数量: <span>{{ item.resourceFileNum }}</span> </p>
                <p>资源文件数量: <span>{{ item.resourceFileNum }}</span> </p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
    <el-pagination small :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 QuickQuery from '@/components/quickquery/QuickQuery'
import { createNamespacedHelpers } from 'vuex'
// const { mapGetters, mapMutations } = createNamespacedHelpers('app')
const { mapMutations } = createNamespacedHelpers('app')

export default {
  mixins: [EsbServiceListMixins],
  components: {
    ProjectInfo,
    QuickQuery
  },
  data() {
    return {
      projectList: [],
      page: {
        pageNum: 0,
        pageSize: 8,
        total: 0
      },
      btncontent: '确定',
      quickQueryKeys: ['name', 'description'],
      sort: {
        orderby: 'createon',
        sort: 'desc'
      },
      placeholder: '名称、描述',
      value: false, // 是否显示弹框
      ProjectInfo: {}// 详情
    }
  },
  mounted() {
  },
  watch: {
    $route: {
      handler: function(to, from, next) {
        console.log(to, from, next, '!login')
      },
      immediate: true
    }
  },
  methods: {
    ...mapMutations(['setProjectID', 'setProjectName']),
    handleDelete(item, event) {
      if (item.proxyServiceNum > 0 || item.businessServiceNum > 0 || item.flowNum > 0 || item.connectorNum > 0 || item.resourceFileNum > 0) {
        this.$message.warning('项目中已有文件')
        return
      }
      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 (let i = 0; i < proxyData.length; i++) {
              arr.push(proxyData[i].name)
              // console.log(arr);
            }
            const businessData = errData.data[0].BUSINESS || []
            const businessArr = []
            for (let 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({
        logic: this.logic,
        filters: this.filters,
        ...this.sort,
        ...this.page
      }).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()
    },
    quickQueryData() {
      this.tableLoading = true
      queryProjectList({
        logic: this.logic,
        filters: this.filters,
        ...this.sort,
        ...this.page
      }).then(rt => {
        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
        }
      }).catch(e => {
        this.tableLoading = false
        return Promise.reject(e)
      })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.search-wrap {
  position: absolute;
  top: 12 0px;
  right: 165px;
}

.title {
  position: relative;
  top: 20px;
  font-size: 16px;
  font-weight: bold;
  padding-left: 10px;
  width: 100px;
}

.el-icon-delete {
  color: #fff;
  content: "\E78C";
}
.el-icon-edit{
    color: #fff;
}

.project_content {
  background-color: #ffffff;
  padding-bottom: 20px;
}

.hiddenText {
  color: #fff;
  margin-top: 3px;
  margin-left: 10px;
}

.el-pagination {
  text-align: center;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.button-right {
 
  margin-right: 8px;
}

.cardList:nth-of-type(1) {
  padding-top: 20px;
}

.hiddenText1 {
  color: gray;
}

.clear-fixs {
  border-radius: 3px;
  transform: translateX(-14px);
  width: 110%;
  margin: -14px, 6px, 0, 0;
  word-break: break-all;
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 16px;
  margin-top: -14px;
  padding-left: -14px;
  background: rgb(73, 99, 220);
}

p {
  margin-top: 3px;
}

span {
  font-size: 17px;
  color: rgb(73, 99, 220);
}
</style>
