<template>
  <div id="business-log">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item v-for="(item, i) in menuData" :key="i" :to="{ path: item.path }">{{ item.name }}</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="商户日志" name="first">
          <header>
            <el-button type="primary" @click="openDialog(false)">新建记录</el-button>
          </header>
          <el-table
            :data="tableData1"
            tooltip-effect="dark"
            style="width: 100%">
            <el-table-column
              label="记录标题"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.title }}
              </template>
            </el-table-column>
            <el-table-column
              label="创建时间"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.createTime | formatDate('ymd') }}<br>{{ row.createTime | formatDate('hms') }}
              </template>
            </el-table-column>
            <el-table-column
              label="更新时间"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.updateTime | formatDate('ymd') }}<br>{{ row.updateTime | formatDate('hms') }}
              </template>
            </el-table-column>
            <el-table-column
              label="创建人"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.creater || '--' }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="200">
              <template slot-scope="{row}">
                <el-button
                  @click.native.prevent="openDialog(true, row.id)"
                  type="text">
                  编辑
                </el-button>
                <el-button
                  @click.native.prevent="openDialog(true, row.id, true)"
                  type="text">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="接口清单" name="second">
          <div class="header">
            <el-radio-group v-model="apiTab" @change="apiTabChanged">
              <el-radio-button label="1">存储过程</el-radio-button>
              <el-radio-button label="2">ETL接口</el-radio-button>
              <el-radio-button label="3">第三方API</el-radio-button>
            </el-radio-group>
            <el-select v-model="apiSearch" filterable placeholder="请选择接口" clearable @change="getStorageProcessList()" v-if="apiTab == 1">
              <el-option
                v-for="item in apiOptions"
                :key="item.erpInterfaceId"
                :label="item.methodName"
                :value="item.methodName">
              </el-option>
            </el-select>
          </div>
          <el-table
            v-if="apiTab == 1"
            :data="tableData2"
            tooltip-effect="dark"
            style="width: 100%">
            <el-table-column
              label="分类"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.categoryName || '--' }}
              </template>
            </el-table-column>
            <el-table-column
              label="接口名称"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.methodName || '--' }}
              </template>
            </el-table-column>
            <el-table-column
              label="接口"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.methodDescribe || '--' }}
              </template>
            </el-table-column>
            <el-table-column
              label="使用渠道"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.accessChannelName || '--' }}
              </template>
            </el-table-column>
            <el-table-column
              label="接口说明"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.remark || '--' }}
              </template>
            </el-table-column>
            <el-table-column
              label="商户接口说明"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.enterpriseMethodDescribe || '--' }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="200">
              <template slot-scope="{row}">
                <el-button
                  @click.native.prevent="openEidtDialog(row.erpInterfaceId)"
                  type="text">
                  编辑
                </el-button>
                <el-button
                  @click.native.prevent="isToPage(row)"
                  type="text">
                  调用次数
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-table
            v-if="apiTab == 2"
            :data="tableData2"
            tooltip-effect="dark"
            style="width: 100%">
            <el-table-column
              label="ETL接口名称"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.method || '--' }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="200">
              <template slot-scope="{row}">
                <el-button
                  @click.native.prevent="$router.push({ path: '/api-count?name=平台运维&icon=icon-03&code=platform_operation&tabCode=platform_business_list', query: { id: row.method, from: 'ETL', enterpriseId } })"
                  type="text">
                  调用次数
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-table
            v-if="apiTab == 3"
            :data="tableData2"
            tooltip-effect="dark"
            style="width: 100%">
            <el-table-column
              label="API接口名称"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.interfaceName || '--' }}
              </template>
            </el-table-column>
            <el-table-column
              label="API接口"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.interfaceUrl || '--' }}
              </template>
            </el-table-column>
            <el-table-column
              label="近一个月调用次数"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.monthCount || '--' }}
              </template>
            </el-table-column>
            <el-table-column
              label="最近调用时间"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.lastVisitTime | formatDate('ymd') }}<br>{{ row.lastVisitTime | formatDate('hms') }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="200">
              <template slot-scope="{row}">
                <el-button
                  @click.native.prevent="$router.push({ path: '/api-count?name=平台运维&icon=icon-03&code=platform_operation&tabCode=platform_business_list', query: { id: row.interfaceUrl, enterpriseId, from: 3 } })"
                  type="text">
                  调用次数
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-if="tableData2.length && apiTab != 2"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.currentPage"
            :page-sizes="[20, 40, 60, 80]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next"
            :total="page.totalCount">
          </el-pagination>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <el-dialog
      :title="isEdit ? '编辑记录' : '新建记录'"
      :visible.sync="argDialog"
      width="600px"
      @closed="closedDialog('formLog')">
      <el-form label-width="80px" ref="formLog" :model="formLog" :rules="rules">
        <el-form-item label="记录标题" prop="title">
          <el-input v-model="formLog.title" placeholder="请输入记录标题" style="width: 406px;" maxlength="20" :disabled="isEdit || argDisabled"></el-input>
        </el-form-item>
        <el-form-item label="交接人" prop="heir">
          <el-input v-model="formLog.heir" placeholder="请输入交接人" style="width: 406px;" :disabled="argDisabled"></el-input>
        </el-form-item>
        <el-form-item label="交接对象" prop="obj">
          <el-input v-model="formLog.obj" placeholder="请输入交接对象" style="width: 406px;" :disabled="argDisabled"></el-input>
        </el-form-item>
        <el-form-item label="详情说明" prop="detail">
          <el-input type="textarea" v-model="formLog.detail" placeholder="请输入详情说明" style="width: 406px;" :rows="4" :disabled="argDisabled"></el-input>
        </el-form-item>
        <el-form-item label="附件地址" prop="address">
          <div v-for="(item, index) in formLog.address" :key="index" style="margin-bottom:10px">
            <el-input v-model="formLog.address[index]" placeholder="请输入附件地址" style="width: 406px;" :disabled="argDisabled"></el-input>
            <i class="el-icon-minus" style="margin-left:10px;cursor:pointer" @click="formLog.address.splice(index, 1)" v-if="formLog.address.length > 1 && !argDisabled"></i>
            <i class="el-icon-plus" style="margin-left:10px;cursor:pointer" @click="formLog.address.push('')" v-if="!argDisabled"></i>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="argDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmArg" v-if="!argDisabled">{{ isEdit ? '保存' : '确认新建' }}</el-button>
      </span>
    </el-dialog>
    
    <el-dialog
      title="编辑"
      :visible.sync="editDialog"
      width="600px"
      @closed="closedDialog('formEdit')">
      <el-form label-width="120px" ref="formEdit" :model="formEdit" :rules="rulesEdit" label-suffix="：">
        <el-form-item label="分类">{{ formEdit.categoryName || '--' }}</el-form-item>
        <el-form-item label="接口名称">{{ formEdit.methodName || '--' }}</el-form-item>
        <el-form-item label="接口">{{ formEdit.methodDescribe || '--' }}</el-form-item>
        <el-form-item label="使用渠道">{{ formEdit.accessChannelName || '--' }}</el-form-item>
        <el-form-item label="接口说明">{{ formEdit.remark || '--' }}</el-form-item>
        <el-form-item label="商户接口说明" prop="enterpriseMethodDescribe">
          <el-input type="textarea" v-model="formEdit.enterpriseMethodDescribe" placeholder="请输入商户接口说明" style="width: 406px;" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getRequest, postJson } from '@/api/api';
let origin = window.location.origin.indexOf('gicdev.demogic.com') != -1 ? 'https://www.gicdev.com' : window.location.origin;

export default {
  name: 'business-log',
  data() {
    return {
      menuData: [
        {
          name: '客户资料',
          path: '/business-list?name=平台运维&icon=icon-03&code=platform_operation&tabCode=platform_business_list'
        },
        {
          name: '商户日志',
          // path: '/api-retry'
        },
      ],
      activeName: 'first',
      search: {
        status: '',
        input: ''
      },
      tableData1: [],
      enterpriseId: undefined,
      argDialog: false,
      argDisabled: false,
      logId: undefined,
      isEdit: false,
      formLog: {
        title: '',
        heir: '',
        obj: '',
        detail: '',
        address: [''],
      },
      rules: {
        title: [{ required: true, message: '记录标题不能为空', trigger: 'blur' }],
        detail: [{ required: true, message: '详情说明不能为空', trigger: 'blur' }],
      },
      apiTab: '1',
      tableData2: [],
      page: {
        currentPage: 1,
        pageSize: 20,
        totalCount: 999
      },
      editDialog: false,
      formEdit: {},
      rulesEdit: {
        enterpriseMethodDescribe: [{ required: true, message: '商户接口说明不能为空', trigger: 'blur' }],
      },
      editId: undefined,
      apiOptions: [],
      apiSearch: '',
    }
  },
  mounted() {
    this.enterpriseId = this.$route.query.enterpriseId || '1af58390681811e69d0818c58a146fd2';
    this.getList();
    this.getStorageProcessList();
    this.getAllOptions();
    this.$emit('showTab', 'platform_business_list');
  },
  methods: {
    getList() {
      let params = {
        eid: this.enterpriseId
      }
      getRequest('/gic-platform-operation/enterpriseLog/getList', params).then(res => {
        if(res.data.code == 0) {
          this.tableData1 = res.data.result || [];
          this.menuData[0].name = res.data.eName ? `客户资料-${res.data.eName}` : '客户资料';
        }
      })
    },
    openDialog(bool, id, disabled) {
      this.argDialog = true;
      this.isEdit = bool;
      this.argDisabled = disabled || false;
      bool && getRequest('/gic-platform-operation/enterpriseLog/getOne', {id}).then(res => {
        if(res.data.code == 0) {
          this.logId = id;
          let result = res.data.result || {};
          let enterpriseLogDTO = result.enterpriseLogDTO || {};
          let enclosureUrlList = result.enclosureUrlList || [''];
          this.formLog = {
            ...this.formLog,
            title: enterpriseLogDTO.title || '',
            heir: enterpriseLogDTO.fromHandover || '',
            obj: enterpriseLogDTO.toHandover || '',
            detail: enterpriseLogDTO.explains || '',
            address: enclosureUrlList.length > 0 ? enclosureUrlList : [''],
          }
        }
      })
    },
    closedDialog(form) {
      this.$refs[form].resetFields();
    },
    confirmArg() {
      this.$refs.formLog.validate(valid => {
        if(valid) {
          const { title, heir, obj, detail, address } = this.formLog;
          let params = {
            enterpriseLogDTO: {
              toHandover: obj,
              fromHandover: heir,
              explains: detail,
              title,
              enterpriseId: this.enterpriseId
            },
            enclosureUrlList: address
          }
          if(this.isEdit) {
            params.enterpriseLogDTO.id = this.logId;
            this.axios.post(`${origin}/gic-platform-operation/enterpriseLog/update`, params).then(res => {
              if(res.data.code == 0) {
                this.argDialog = false;
                this.$message.success('保存成功');
                this.getList();
              }
            })
          } else {
            this.axios.post(`${origin}/gic-platform-operation/enterpriseLog/save`, params).then(res => {
              if(res.data.code == 0) {
                this.argDialog = false;
                this.$message.success('新建成功');
                this.getList();
              }
            })
          }
        }
      })
    },
    apiTabChanged(val) {
      this.tableData2 = [];
      this.page.currentPage = 1;
      val = +val;
      switch (val) {
        case 1:
          this.getStorageProcessList();
          break;
        case 2:
          this.getEtl();
          break;
        case 3:
          this.getApiList();
          break;
      }
    },
    getApiList() {
      const { currentPage, pageSize } = this.page;
      let params = {
        eid: this.enterpriseId,
        pageNum: currentPage,
        pageSize: pageSize,
      }
      getRequest('/gic-platform-operation/interface/getThirdList', params).then(res => {
        if(res.data.code == 0) {
          let result = res.data.result || {};
          this.page.totalCount = result.totalCount || 0;
          this.tableData2 = result.result || [];
        }
      })
    },
    getStorageProcessList() {
      const { currentPage, pageSize } = this.page;
      let params = {
        eid: this.enterpriseId,
        pageNum: currentPage,
        pageSize: pageSize,
        search: this.apiSearch
      }
      getRequest('/gic-platform-operation/interface/getSaveProcessList', params).then(res => {
        if(res.data.code == 0) {
          let result = res.data.result || {};
          this.page.totalCount = result.totalCount || 0;
          this.tableData2 = result.result || [];
        }
      })
    },
    getEtl() {
      getRequest('/gic-platform-operation/interface/getEtl', { eid: this.enterpriseId }).then(res => {
        if(res.data.code == 0) {
          let result = res.data.result || {};
          this.tableData2 = result.faceInfo.interfaceInfoes || [];
        }
      })
    },
    // 改变每页显示数量
    handleSizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
      this.apiTab == 3 && this.getApiList();
      this.apiTab == 1 && this.getStorageProcessList();
      this.apiTab == 2 && this.getEtl();
    },
    // 换页
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.apiTab == 3 && this.getApiList();
      this.apiTab == 1 && this.getStorageProcessList();
      this.apiTab == 2 && this.getEtl();
    },
    openEidtDialog(id) {
      this.editId = id;
      getRequest('/gic-platform-operation/interface/getOneInterface', { erpInterfaceId: id }).then(res => {
        if(res.data.code == 0) {
          this.editDialog = true;
          this.formEdit = res.data.result || {};
        }
      })
    },
    saveEdit() {
      this.$refs.formEdit.validate(valid => {
        if(valid) {
          let params = {
            desc: this.formEdit.enterpriseMethodDescribe,
            erpInterfaceId: this.editId
          };
          getRequest('/gic-platform-operation/interface/UpdateOne', params).then(res => {
            if(res.data.code == 0) {
              this.editDialog = false;
              this.$message.success('保存成功');
              this.getStorageProcessList();
            }
          })
        }
      })
    },
    getAllOptions() {
      getRequest('/gic-platform-operation/interface/getAll', {}).then(res => {
        if(res.data.code == 0) {
          this.apiOptions = res.data.result || [];
        }
      })
    },
    isToPage(row) {
      row.openStatus == 0 ? this.$router.push({ path: '/api-count?name=平台运维&icon=icon-03&code=platform_operation&tabCode=platform_business_list', query: { id: row.methodName, from: 'PRO', enterpriseId: this.enterpriseId } }) : this.$message.warning('【接口运行情况】接口尚未开启，请确认');
    }
  },
  filters: {
    formatDate(val, format) {
      if(!val) return '--';
      val = new Date(val);
      let y = val.getFullYear();
      let m = (val.getMonth() + 1).toString().padStart(2, '0');
      let d = val.getDate().toString().padStart(2, '0');
      let h = val.getHours().toString().padStart(2, '0');
      let mm = val.getMinutes().toString().padStart(2, '0');
      let s = val.getSeconds().toString().padStart(2, '0');
      if(format == 'ymd') {
        return `${y}-${m}-${d}`;
      } else if(format == 'hms') {
        return `${h}:${mm}:${s}`;
      }
      return `${y}-${m}-${d}\xa0\xa0\xa0${h}:${mm}:${s}`
    }
  }
}
</script>
<style lang="scss" scoped>
#business-log {
  .el-breadcrumb {
    padding: 20px;
    border-bottom: 1px solid #DCDFE6;
  }
  .content {
    padding: 20px;
  }
  background-color: #fff;
  header {
    text-align: right;
    margin-bottom: 20px;
  }
  .header {
    display: flex;
    justify-content: space-between;
    margin: 10px 0 20px;
  }
}
.el-pagination {
  text-align: right;
  margin-top: 20px;
}
</style>