<template>
  <div class="app-container service-provider">
    <el-form :inline="true" :model="pagerDto">
      <el-form-item label="服务商名称">
        <el-input v-model="pagerDto.ProviderName" placeholder="请输入服务商名称" style="width: 240px;" />
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" :loading="dataLoading" @click="pagerSerach()">搜索</el-button>
        <el-button size="small" type="info" @click="addServiceProvider()">添加</el-button>
      </el-form-item>
    </el-form>
    <vxe-table ref="xProviderTable" border="full" :data="dataSource" show-overflow keep-source :edit-rules="rules"
      :edit-config="{ trigger: 'manual', mode: 'row', showStatus: false, autoClear: false, showIcon: false }">
      <vxe-column field="ProviderName" title="服务商名称" :edit-render="{ autofocus: '.vxe-input--inner', defaultValue: '' }">
        <template #edit="{ row }">
          <el-input v-model="row.ProviderName" />
        </template>
      </vxe-column>
      <vxe-column field="Remark" title="备注" :edit-render="{ autofocus: '.vxe-input--inner', defaultValue: '' }">
        <template #edit="{ row }">
          <el-input v-model="row.Remark" />
        </template>
      </vxe-column>
      <vxe-column field="StrReturnNodes" title="异常节点">
        <template #default="scoped">
          <el-popover v-if="scoped.row.ReturnNodes && scoped.row.ReturnNodes.length > 0" placement="top-start"
            title="异常节点" width="800" trigger="hover" :content="formatNodes()">
            <div v-for="(n, idx) in scoped.row.ReturnNodes" :key="idx" style="
                border-bottom: 1px solid #eee;
                margin-bottom: 3px;
                padding-bottom: 3px;
              ">
              {{ n.Node }} {{ n.CNNode }}
            </div>
            <div slot="reference" style="text-wrap: no-wrap; over-flow: hidden">
              {{ scoped.row.StrReturnNodes }}
            </div>
          </el-popover>
        </template>
      </vxe-column>
      <vxe-column title="操作" width="276">
        <template #default="{ row }">
          <template v-if="$refs.xProviderTable.isActiveByRow(row)">
            <vxe-button :loading="saveLoading" @click="saveRowEvent(row)">保存</vxe-button>
            <vxe-button @click="cancelRowEvent(row)">取消</vxe-button>
          </template>
          <template v-else>
            <vxe-button @click="editRowEvent(row)">编辑服务商</vxe-button>
          </template>
          <vxe-button status="primary" @click="editNodes(row)" :loading="editLoading"
            :disabled="!row.Id">编辑节点</vxe-button>
        </template>
      </vxe-column>
    </vxe-table>
    <el-pagination :page-sizes="[10, 20, 40, 100, 400]" :current-page="pagerDto.PageIndex"
      :page-size.sync="pagerDto.PageSize" background layout="prev, pager, next ,total ,jumper,sizes,slot "
      :total="pagerDto.total" @size-change="changePager" @current-change="pagerSerach" />
    <!-- 编辑节点 -->
    <el-dialog title="编辑节点" top="10vh" :visible.sync="dialogNodeEdit" :close-on-click-modal="false" width="820px">
      <div class="nodes-warp">
        <el-form :model="editNodeDto" label-width="100px" class="nodes-form">
          <el-form-item label="服务商名称">
            <div class="provider-name">
              <el-input v-model="editNodeDto.ProviderName" autocomplete="off" :disabled="true" />
            </div>
          </el-form-item>
          <el-form-item v-for="(domain, index) in editNodeDto.ReturnNodes" :key="index" :label="'异常节点' + (index + 1)"
            :prop="'ReturnNodes.' + index + '.Node'">
            <el-input v-model="domain.Node" placeholder="英文节点" />
            <el-input v-model="domain.CNNode" placeholder="中文节点" />
            <el-button style="float: left" type="danger" @click.prevent="removeReturnNode(domain)" plain>删除</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="addReturnNode" plain>新增节点</el-button>
        <el-button @click="dialogNodeEdit = false">取 消</el-button>
        <el-button type="primary" @click="postEditNode" :loading="editLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import VXETable from 'vxe-table'
import { _getEndServiceProviderPageResult, _AddOrEditProvider, _EditProviderNote } from '@/api/trakingMoreNode'
import { deepClone } from '@/utils'
export default {
  name: 'ServiceProvider',
  data() {
    return {
      pagerDto: {
        ProviderName: undefined,
        PageIndex: 0,
        PageSize: 20,
        total: 0,
      },
      rules: {
        ProviderName: [
          { required: true, message: "名称为必填项！" },
        ],
      },
      dataSource: [
        // {
        //   "StrReturnNodes": "",
        //   "ReturnNodes": [],
        //   "ProviderName": "测试服务商",
        //   "Id": 1,
        //   "CreateUserName": "刘正凯",
        //   "CreateTime": "2024-07-27T11:58:56.27",
        //   "UpdateUserName": "刘正凯",
        //   "UpdateTime": "2024-07-27T13:58:01.337",
        //   "Remark": "仅用于测试使用"
        // },
        // {
        //   "StrReturnNodes": "12;2342",
        //   "ReturnNodes": [
        //     {
        //       "Node": "12",
        //       "CNNode": "3232"
        //     },
        //     {
        //       "Node": "2342",
        //       "CNNode": "232"
        //     }
        //   ],
        //   "ProviderName": "测试服务商1",
        //   "Id": 2,
        //   "CreateUserName": "刘正凯",
        //   "CreateTime": "2024-07-27T13:59:10.757",
        //   "UpdateUserName": "刘正凯",
        //   "UpdateTime": "2024-07-27T13:59:25.003",
        //   "Remark": "仅测试啊"
        // },
        // {
        //   "StrReturnNodes": "",
        //   "ReturnNodes": [],
        //   "ProviderName": "测试服务商3",
        //   "Id": 3,
        //   "CreateUserName": "刘正凯",
        //   "CreateTime": "2024-07-27T14:31:53.867",
        //   "UpdateUserName": "刘正凯",
        //   "UpdateTime": "2024-07-27T14:31:53.867",
        //   "Remark": "热"
        // }
      ],
      dataLoading: false,
      isInsert: false,
      saveLoading: false,
      dialogNodeEdit: false,
      editLoading: false,
      editNodeDto: {
        ChannelId: undefined,
        Id: undefined,
        ProviderName: '',
        ReturnNodes: []
      }
    }
  },
  mounted() {
    this.pagerSerach(1)
  },
  methods: {
    formatNodes(nodes) {
      let content = ''
      if (nodes && nodes.length > 0) {
        nodes.map((i) => {
          content += `${i.Node}  ${i.CNNode} \r\n`
        })
      }
      return content
    },
    pagerSerach(index) {
      this.dataLoading = true
      if (index) {
        this.pagerDto.PageIndex = index
      }
      _getEndServiceProviderPageResult(this.pagerDto).then(res => {
        this.dataSource = res.Result
        this.pagerDto.total = res.TotalCount
      }).finally(() => { this.dataLoading = false })
    },
    changePager(v) {
      this.PageSize = v
      this.pagerSerach()
    },
    async checkAndEditRow() {
      const $table = this.$refs.xProviderTable
      const { fullData: tableData } = $table.getTableData();
      for (const row of tableData) {
        if (!row.Id) {
          await $table.setEditRow(row, 'Id');
          break;
        }
      }
    },
    async addServiceProvider(row) {
      if (!this.isInsert) {
        this.isInsert = true
        const $table = this.$refs.xProviderTable
        const record = {
          ProviderName: undefined,
          ReturnNodes: [],
          Remark: undefined,
        }
        const { row: newRow } = await $table.insertAt(record, row)
        await $table.setEditCell(newRow, 'ProviderName')
      } else {
        this.checkAndEditRow()
      }
    },
    editRowEvent(row) {
      const $table = this.$refs.xProviderTable
      $table.setActiveRow(row)
    },
    cancelRowEvent(row) {
      const $table = this.$refs.xProviderTable
      $table.clearActived().then(async () => {
        if (row.Id) {
          // 还原行数据
          $table.revertData(row)
          return
        }
        if (!row.ProviderName) {
          // 添加的删除
          const $table = this.$refs.xProviderTable
          await $table.remove(row);
          this.isInsert = false
        } else {
          $table.revertData(row)
        }
      })
    },
    async validRow(row) {
      const $table = this.$refs.xProviderTable
      const errMap = await $table.validate(row).catch(errMap => errMap)
      return !errMap
    },
    // 保存服务商
    async saveRowEvent(row) {
      debugger
      const $table = this.$refs.xProviderTable
      var isValid = await this.validRow(row)
      if (isValid) {
        const params = deepClone(row)
        delete params._X_ROW_KEY
        this.saveLoading = true
        _AddOrEditProvider(params).then(() => {
          VXETable.modal.message({ content: '保存成功！', status: 'success' })
          this.isInsert = false
          this.pagerSerach()
          $table.clearActived()
        }).finally(() => { this.saveLoading = false })
      }
    },
    // 编辑节点
    postEditNode() {
      if (this.editNodeDto.Id) {
        const params = deepClone(this.editNodeDto)
        delete params._X_ROW_KEY
        this.editLoading = true
        _EditProviderNote(params).then((response) => {
          this.pagerSerach()
          VXETable.modal.message({ content: '编辑成功！', status: 'success' })
          this.dialogNodeEdit = false
          this.editNodeDto.ReturnNodes = []
          this.editNodeDto.Id = undefined
          this.editNodeDto.ProviderName = ''
        }).finally(() => { this.editLoading = false })
      }
    },
    editNodes(row) {
      const params = deepClone({ ...row, ChannelId: row.Id })
      this.editNodeDto = params
      this.dialogNodeEdit = true
    },
    addReturnNode() {
      this.editNodeDto.ReturnNodes.push({
        Node: '',
        CNNode: ''
      })
    },
    removeReturnNode(item) {
      const index = this.editNodeDto.ReturnNodes.indexOf(item)
      if (index !== -1) {
        this.editNodeDto.ReturnNodes.splice(index, 1)
      }
    },
  }
}
</script>
<style scoped>
.service-provider {
  clear: both;
  padding: 10px;
}

.provider-name {
  display: flex;
}

.nodes-warp {
  max-height: 607px;
  overflow-y: auto;
}

.nodes-warp::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.nodes-warp::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.nodes-warp::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.nodes-warp::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.nodes-form ::v-deep .el-input {
  width: 88%;
  float: left;
  margin-right: 10px;
}
</style>
