<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-form-item label="应用名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入应用名称"
              clearable
              size="small"
              style="width: 160px"
              @clear="handleQuery"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="应用别名" prop="alias">
            <el-input
              v-model="queryParams.alias"
              placeholder="请输入应用别名"
              clearable
              size="small"
              style="width: 160px"
              @clear="handleQuery"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="负责人" prop="contractInfo">
            <el-input
              v-model="queryParams.contractInfo"
              placeholder="请输入负责人"
              clearable
              size="small"
              style="width: 160px"
              @clear="handleQuery"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb20">
          <el-col :span="1.5">
            <el-button
              v-permisaction="['disposition:index:add']"
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-permisaction="['disposition:index:edit']"
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-permisaction="['disposition:index:delete']"
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除
            </el-button>
          </el-col>
        </el-row>

        <el-table
          v-loading="loading"
          :data="appsList"
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChang"
        >
          <el-table-column type="selection" width="55" align="center" header-align="center" />
          <el-table-column
            label="应用名称"
            prop="name"
            align="center"
            header-align="center"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <div style="cursor: pointer;" @click="go('/business-analysis/analysis/index',scope.row)">
                {{ scope.row.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="应用别名"
            header-align="center"
            prop="alias"
            align="center"
            :show-overflow-tooltip="true"
          />
          <!-- <el-table-column label="Apdex" header-align="center" prop="apdex" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.apdex}}</span>
            </template>
          </el-table-column>
          <el-table-column label="响应时间(ms)" header-align="center" prop="latency" align="center" width="120">
          <template slot-scope="scope">
              <span>{{scope.row.latency}}</span>
            </template>
          </el-table-column>
          <el-table-column label="吞吐率(rpm)" header-align="center" prop="rate" align="center" />
          <el-table-column label="错误率(%)" header-align="center" prop="errorRate" align="center" /> -->
          <el-table-column
            label="应用备注"
            header-align="center"
            prop="desc"
            align="center"
            :show-overflow-tooltip="true"
          />
          <!-- <el-table-column label="应用图片" prop="imgUrl" align="center">
            <template slot-scope="scope">
              <img :src='scope.row.imgUrl' style="width:40px;height:20px"/>
            </template>
          </el-table-column> -->
          <el-table-column
            label="负责人"
            header-align="center"
            prop="contractInfo"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="手机号码"
            header-align="center"
            prop="contractPhone"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                v-permisaction="['disposition:index:edit']"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改
              </el-button>
              <el-button
                v-if="scope.row.roleKey!=='admin'"
                v-permisaction="['disposition:index:delete']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        /> -->

        <!-- 添加或修改应用配置对话框 -->
        <el-dialog
          v-if="open"
          :title="title"
          :visible.sync="open"
          width="700px"
          :center="true"
          :close-on-click-modal="false"
        >
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="应用名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入应用名称" />
            </el-form-item>
            <el-form-item label="应用别名" prop="alias">
              <el-input v-model="form.alias" placeholder="请输入应用别名" :disabled="isEdit" />
            </el-form-item>
            <el-form-item label="关联服务" >
              <el-table
                :data="form.serviceIncluded"
                max-height="200"
                style="width: 100%"
              >
                <el-table-column
                  prop="serviceName"
                  label="已关联服务"
                  width="180"
                />
                <el-table-column
                  label="操作"
                  width="180"
                >
                  <template v-slot="{row}">
                    <el-button type="primary" icon="el-icon-remove" @click="() => unbindServiceFromApp(row)" />
                  </template>
                </el-table-column>
              </el-table>
              <el-table
                :data="form.serviceNotIncluded"
                max-height="200"
                style="width: 100%;margin-top:10px"
              >
                <el-table-column
                  prop="serviceName"
                  label="未关联服务"
                  width="180"
                />
                <el-table-column
                  label="操作"
                  width="180"
                >
                  <template v-slot="{row}">
                    <el-button
                      v-if="row.appName==='' || row.appName ===form.alias"
                      type="success"
                      icon="el-icon-circle-plus"
                      @click="() => pickService(row)"
                    />
                    <el-button
                      v-else
                      type="info"
                      icon="el-icon-error"
                      @click="() => handleAddInvalidService(row.serviceName, row.appName)"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item label="应用备注">
              <el-input v-model="form.desc" type="textarea" placeholder="请输入应用详情" />
            </el-form-item>
            <el-form-item label="应用图片" prop="imgUrl">
              <img v-if="form.imgUrl" :src="form.imgUrl" class="el-upload el-upload--picture-card" style="float:left">
              <el-upload
                ref="sys_app_logo"
                accept=".png,.jpg,.jpeg"
                :headers="headers"
                :file-list="appsfileList"
                :action="appsAction"
                style="float:left"
                :before-upload="beforeUpload"
                list-type="picture-card"
                :show-file-list="false"
                :on-success="uploadSuccess"
              >
                <i class="el-icon-plus" />
              </el-upload>
            </el-form-item>
            <el-form-item label="负责人" prop="contractInfo">
              <el-input v-model="form.contractInfo" placeholder="请输入负责人" />
            </el-form-item>
            <el-form-item label="手机号码" prop="contractPhone" style="margin-bottom: 0;">
              <el-input v-model="form.contractPhone" placeholder="请输入合作手机号" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
        <!-- <div class="back" @click="toggle()">
           <i class="iconfont icon-qiehuan1"></i>
         </div> -->
      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
import { listApps, singleApps, addOtApps, updateOtApps, delOtApps, appsScore, listAppServiceList } from '@/api/apps'
import { formatJson } from '@/utils'
import storage from '@/utils/storage'
import { getToken } from '@/utils/auth'

export default {
  name: 'Role',
  components: {},
  data() {
    return {
      times: {
        // start_time:Math.round((new Date().getTime())/1000 - (5*60)),
        // end_time:Math.round(new Date().getTime()/1000),
        start_time: 0,
        end_time: 0
      },
      appsList: [],
      // 应用数据列表
      appData: [],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      menuIdsChecked: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      isEdit: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        contractInfo: '',
        alias: '',
        name: '',
        pageIndex: 0,
        pageSize: 200,
        start_time: 0,
        end_time: 0
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '应用名称不能为空', trigger: 'blur' }
        ],
        alias: [
          { required: true, message: '应用别名不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '应用详情不能为空', trigger: 'blur' }
        ]
      },
      appsAction: process.env.VUE_APP_BASE_API + '/api/v1/public/uploadFile',
      appsfileList: [],
      headers: { 'Authorization': 'Bearer ' + getToken() },
      queryScore: {
        interval: 60,
        req_applist: []
      }
    }
  },
  watch: {
    '$store.state.time.globalTimes': {
      handler(newValue, oldValue) {
        if (newValue) {
          this.queryParams.start_time = newValue.startTime
          this.queryParams.end_time = newValue.endTime
          this.queryScore.interval = newValue.interval
          this.times.start_time = newValue.startTime
          this.times.end_time = newValue.endTime
          this.getList()
        }
      },
      // immediate: true,
      deep: true
    }
  },
  created() {
    const start_time = this.$store.state.time.globalTimes.startTime
    const end_time = this.$store.state.time.globalTimes.endTime
    this.queryParams.start_time = start_time
    this.queryParams.end_time = end_time

    this.getList()
  },
  methods: {
    unbindServiceFromApp(row) {
      if (this.form.serviceNotIncluded.findIndex(({ serviceName, appName }) => {
        return serviceName === row.serviceName
      }) < 0) {
        this.form.serviceNotIncluded.push(row)
      }
      const index = this.form.serviceIncluded.findIndex(e => {
        return e.serviceName === row.serviceName
      })
      this.form.serviceIncluded.splice(index, index !== -1 ? 1 : 0)
    },
    pickService(row) {
      this.form.serviceIncluded.push(row)
      const index = this.form.serviceNotIncluded.findIndex(e => {
        return e.serviceName === row.serviceName
      })
      this.form.serviceNotIncluded.splice(index, index !== -1 ? 1 : 0)
    },
    handleAddInvalidService(service, appName) {
      this.$message(`服务${service}已绑定到${appName}，解绑后才能操作`)
    },

    toggle() {
      this.$router.push({
        path: 'dashboard'
      })
    },
    getList() {
      this.loading = true
      listApps(this.queryParams).then(
        res => {
          if (res && res.code === 200) {
            this.appsList = res.data.list || []
          } else {
            this.appsList = []
          }
          this.loading = false
        }
      )
    },
    go(router, item) {
      const start_time = this.times.start_time
      const end_time = this.times.end_time
      this.$router.push({
        path: router,
        query: {
          id: item.id,
          app_alias: item.alias,
          start_time,
          end_time,
          item: item
        }
      })
      storage.set('appsItem', item)
    },
    beforeUpload(file) {
      const isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      const isJPG = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG/JPEG 格式!')
      }
      return isRightSize && isJPG
    },
    uploadSuccess(response, file, fileList) {
      this.form.imgUrl = process.env.VUE_APP_BASE_API + response.data.full_path
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        alias: undefined,
        desc: undefined,
        imgUrl: undefined,
        contractInfo: undefined,
        contractPhone: undefined,
        serviceIncluded: undefined,
        serviceNotIncluded: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // this.getMenuTreeselect(0)
      this.open = true
      this.title = '添加应用'
      this.isEdit = false
      listAppServiceList().then(res => {
        this.form.serviceIncluded = []
        this.form.serviceNotIncluded = res.data.fullServiceList || []
      })
    },
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.menuIdsChecked = []
      this.reset()
      const id = row.id || this.ids
      singleApps(id).then(response => {
        this.form = response.data
        const fullServiceList = this.form.fullServiceList || []
        this.form.serviceNotIncluded = fullServiceList.filter(e => {
          if (!e.serviceName) {
            return false
          }
          return e.appName !== this.form.alias
        })
        this.form.serviceIncluded = fullServiceList.filter(e => {
          if (!e.serviceName || !e.appName) {
            return false
          }
          return e.appName === this.form.alias
        })
        this.menuIdsChecked = response.data.menuIds
        this.title = '修改应用'
        this.isEdit = true
        this.open = true
        // this.getRoleMenuTreeselect(row, response.data.menuIds)
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const subData = Object.assign({}, this.form)
          subData.serviceNames = (subData.serviceIncluded || []).map(e => e.serviceName)
          delete subData.serviceIncluded
          delete subData.serviceNotIncluded
          if (this.form.id !== undefined) {
            updateOtApps(subData, this.form.id).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addOtApps(subData).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // const roleIds = (row.id && [row.id]) || this.ids
      const id = [row.id]
      this.$confirm('是否确认删除应用编号为"' + id + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delOtApps({ 'ids': id })
      }).then((response) => {
        this.getList()
        this.msgSuccess(response.msg)
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出所有角色数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['角色编号', '角色名称', '权限字符', '显示顺序', '状态', '创建时间']
          const filterVal = ['roleId', 'roleName', 'roleKey', 'roleSort', 'status', 'createdAt']
          const list = this.roleList
          const data = formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '角色管理',
            autoWidth: true, // Optional
            bookType: 'xlsx' // Optional
          })
          this.downloadLoading = false
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.iconfont {
  font-family: "iconfont" !important;
  font-size: 20px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-jiantou_zuoyouqiehuan:before {
  content: "\eb0d";
}

.icon-qiehuan:before {
  content: "\e606";
}

.icon-qiehuan1:before {
  content: "\e789";
}

::v-deep .el-card__body {
  position: relative !important;
}

.back {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 20px;
  height: 20px;
  cursor: pointer;
}
// ::v-deep .el-dialog__body{
//   max-height: 900px;
//   overflow: overlay;
// }
</style>
