<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-07-31 20:25:44
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-24 09:37:28
 -->
<template>
  <div>
    <div class="search-wrap m-b-20 flex flex-space-between">
      <div class="font-0">
        <el-input
          v-model="searchValue"
          clearable
          class="w-320"
          placeholder="请输入版本号"
          @keyup.native="value => searchData(value)"
          @clear="clearInput">
          <i
            slot="prefix"
            class="el-input__icon el-icon-search" />
        </el-input>
        <el-select
          v-model="status"
          class="w-137 m-l-10"
          placeholder="请选择"
          @change="changeStatus">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value" />
        </el-select>
      </div>

      <div class="search-wrap-right">
        <el-radio-group
          v-model="sceneCode"
          @change="changeType">
          <el-radio-button
            v-for="(item, index) in envOptions"
            :key="index"
            :label="item.sceneCode">
            {{ item.sceneName }}
          </el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <div class="table-wrap">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%">
        <el-table-column
          prop="version"
          label="版本号"
          show-overflow-tooltip />
        <el-table-column
          prop="status"
          label="状态"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <!-- <span v-if="scope.row.status == 0">删除</span>
            <span v-if="scope.row.status == 1">更新修改</span>
            <span v-if="scope.row.status == 2">发布 </span>
            <span v-if="scope.row.status == 3">历史发布版本</span>
            <span v-if="scope.row.status == 4">下线</span> -->
            {{ scope.row.stateName }}
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <div class="color-606266 line-18">
              {{ scope.row.createTime | timeStampToYmd }}
            </div>
            <div class="color-606266 line-18">
              {{ scope.row.createTime | timeStampToHms }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="发布时间"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <div
              v-if="scope.row.publishTime"
              class="color-606266 line-18">
              {{ scope.row.publishTime | timeStampToYmd }}
            </div>
            <div
              v-if="scope.row.publishTime"
              class="color-606266 line-18">
              {{ scope.row.publishTime | timeStampToHms }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="更新时间"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <div class="color-606266 line-18">
              {{ scope.row.updateTime | timeStampToYmd }}
            </div>
            <div class="color-606266 line-18">
              {{ scope.row.updateTime | timeStampToHms }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="默认版本"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.defaultFlag"
              active-text=""
              inactive-text=""
              @change="changeVersion(scope.row, scope.row.defaultFlag)" />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="340">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button
              :disabled="(scope.row.status == 2 && scope.row.updateAfterPublish != 1) || scope.row.status == 4"
              type="text"
              @click="handlePublish(scope.$index, scope.row)">
              发布
            </el-button>
            <el-button
              type="text"
              @click="handleSync(scope.$index, scope.row)">
              同步
            </el-button>
            <el-button
              type="text"
              @click="handleShow(scope.$index, scope.row)">
              查看
            </el-button>
            <el-button
              v-if="scope.row.status == 5 || scope.row.status < 4"
              :disabled="scope.row.status != 2 && scope.row.updateAfterPublish != 1"
              type="text"
              @click="handleDown(scope.$index, scope.row)">
              下线
            </el-button>
            <el-button
              v-if="scope.row.status == 4"
              type="text"
              @click="handleUp(scope.$index, scope.row)">
              上线
            </el-button>
            <el-button
              type="text"
              @click="handleRecord(scope.$index, scope.row)">
              发布记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div
        v-if="!!totalCount"
        class="pagination text-right m-t-14">
        <dm-pagination
          small
          :page-size="pageSize"
          :current-page="currentPage"
          layout="prev, pager, next"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <sync-set
      :edit-row="editRow"
      :sync-show="syncShow"
      @hideSyncDialog="hideSyncDialog" />
    <publish-set
      :edit-row="editRow"
      :publish-show="publishShow"
      @hidePublishDialog="hidePublishDialog" />
    <record-list
      :edit-row="editRow"
      :record-show="recordShow"
      @hideRecordDialog="hideRecordDialog" />
  </div>
</template>
<script>
import publishSet from '@/components/api/publish-set.vue';
import syncSet from '@/components/api/sync-set.vue';
import recordList from '@/components/api/record-list.vue';
import { getRequest } from '@/api/api';
import { _debounce } from '@/assets/js/public';
import showMsg from '@/assets/js/showmsg';
import errMsg from '@/assets/js/error';
export default {
  name: 'EnvSetList',
  components: {
    publishSet,
    syncSet,
    recordList
  },
  data() {
    return {
      searchValue: '',
      status: '',
      statusOptions: [
        {
          label: '所有发布状态',
          value: ''
        },
        {
          label: '待发布',
          value: '1'
        },
        {
          label: '发布',
          value: '2'
        },
        {
          label: '下线',
          value: '4'
        },
        {
          label: '上线',
          value: '5'
        }
      ],
      sceneCode: '',
      envOptions: [
        // {
        //   sceneCode: '1',
        //   sceneName: '测试'
        // },
        // {
        //   sceneCode: '2',
        //   sceneName: '正式'
        // }
      ],
      loading: true,
      tableData: [
        /* {
          interfaceVersionId: '1',
          version: '测试',
          status: '1', // 0 删除 1更新修改 2发布 3 历史发布版本
          description: '234',
          proxyType: '0',
          defaultFlag: false,
          createTime: 1564455643252,
          updateTime: 1564455643252,
          publishTime: 1564455643252
        } */
      ],
      pageSize: 20,
      currentPage: 1,
      totalCount: 0,
      // 同步
      syncShow: false,
      editRow: {},
      // 发布
      publishShow: false,
      // 发布记录
      recordShow: false
    };
  },
  mounted() {
    const that = this;
    that.getEnvData();
  },
  methods: {
    /**
     * @description: 搜索
     * @author: 无尘
     */
    searchData: _debounce(function() {
      const that = this;
      that.currentPage == 1;
      that.getData();
    }, 500),

    /**
     * @description: 搜索清除
     * @author: 无尘
     */
    clearInput() {
      this.currentPage = 1;
      this.getData();
    },
    changeStatus() {
      this.currentPage = 1;
      this.getData();
    },
    /**
     * @description: 切换 http dubbo
     * @author: 无尘
     */
    changeType() {
      const that = this;
      that.currentPage = 1;
      that.getData();
    },
    /**
     * @description: 分页
     * @param {Number} val
     * @author: 无尘
     */
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getData();
    },
    /**
     * @description: 改变默认版本
     * @param {Object} row
     * @param {Boolean} val
     * @author: 无尘
     */
    changeVersion(row, val) {
      const that = this;
      that.postChangeVersion(row, val);
    },
    postChangeVersion(row, val) {
      const that = this;
      let para = {
        defaultFlag: val ? '1' : '0',
        interfaceVersionId: row.interfaceVersionId
      };
      getRequest('/gateway-manage/set-default-version-api', para)
        .then(res => {
          let resData = res.data;
          if (resData.code == '0000') {
            showMsg.showmsg('设置成功', 'success');
            that.currentPage = 1;
            that.getData();
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * @description: 发布
     * @param {Boolean} index
     * @param {Object} row
     * @author: 无尘
     */
    handlePublish(index, row) {
      const that = this;
      that.publishShow = true;
      that.editRow = row;
    },
    hidePublishDialog() {
      const that = this;
      that.getData();
      that.publishShow = false;
      that.editRow = {};
    },
    /**
     * @description: 同步
     * @param {Boolean} index
     * @param {Object} row
     * @author: 无尘
     */
    handleSync(index, row) {
      const that = this;
      that.syncShow = true;
      that.editRow = row;
    },
    hideSyncDialog() {
      const that = this;
      that.syncShow = false;
      that.editRow = {};
    },
    /**
     * @description: 发布记录
     * @param {Boolean} index
     * @param {Object} row
     * @author: 无尘
     */
    handleRecord(index, row) {
      const that = this;
      that.recordShow = true;
      that.editRow = row;
    },
    hideRecordDialog() {
      const that = this;
      that.recordShow = false;
      that.editRow = {};
    },
    /**
     * @description: 查看
     * @param {Boolean} index
     * @param {Object} row
     * @author: 无尘
     */
    handleShow(index, row) {
      const that = this;
      that.$router.push(`/apiListManageShow?editFlag=1&interfaceId=${that.$route.query.interfaceId}&interfaceName=${that.$route.query.interfaceName}&projectId=${row.projectId}&projectName=${that.$route.query.projectName}&interfaceGroupId=${row.interfaceGroupId}&interfaceGroupName=${that.$route.query.interfaceGroupName}&interfaceVersionId=${row.interfaceVersionId}`);
    },
    /**
     * @description: 编辑
     * @param {Boolean} index
     * @param {Object} row
     * @author: 无尘
     */
    handleEdit(index, row) {
      const that = this;
      that.$router.push(`/createApi?projectId=${row.projectId}&projectName=${that.$route.query.projectName}&interfaceGroupId=${row.interfaceGroupId}&interfaceGroupName=${that.$route.query.interfaceGroupName}&interfaceId=${that.$route.query.interfaceId}&interfaceName=${that.$route.query.interfaceName}&interfaceVersionId=${row.interfaceVersionId}`);
    },
    /**
     * @description: 下线
     * @param {Boolean} index
     * @param {Object} row
     * @author: 无尘
     */
    handleDown(index, row) {
      const that = this;
      that
        .$confirm(`确认将【${row.version}】版本的【${that.$route.query.interfaceName}】API下线吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.postDownData(index, row);
        })
        .catch(() => {});
    },
    postDownData(index, row) {
      const that = this;
      let para = {
        interfaceVersionId: row.interfaceVersionId
      };
      getRequest('/gateway-manage/offline-api', para)
        .then(res => {
          let resData = res.data;
          if (resData.code == '0000') {
            showMsg.showmsg('下线成功', 'success');
            that.getData();
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    handleUp(index, row) {
      const that = this;
      that
        .$confirm(`确认将【${row.version}】版本的【${that.$route.query.interfaceName}】API上线吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.postUpData(index, row);
        })
        .catch(() => {});
    },
    postUpData(index, row) {
      const that = this;
      let para = {
        interfaceVersionId: row.interfaceVersionId
      };
      getRequest('/gateway-manage/online-api', para)
        .then(res => {
          let resData = res.data;
          if (resData.code == '0000') {
            showMsg.showmsg('上线成功', 'success');
            that.getData();
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * @description: 获取环境列表
     * @author: 无尘
     */
    getEnvData() {
      const that = this;
      getRequest('/gateway-manage/list-all-scene', {})
        .then(res => {
          let resData = res.data;
          if (resData.code == '0000') {
            that.envOptions = resData.result || [];
            if (resData.result.length) {
              resData.result.forEach(ele => {
                if (ele.defaultFlag == 1) {
                  that.sceneCode = ele.sceneCode;
                }
              });
              that.$nextTick(() => {
                that.getData();
              });
            }
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * @description: 获取数据
     * @author: 无尘
     */
    getData() {
      const that = this;
      that.loading = true;
      let para = {
        search: that.searchValue,
        pageNum: that.currentPage,
        pageSize: that.pageSize,
        sceneCode: that.sceneCode,
        status: that.status,
        interfaceId: that.$route.query.interfaceId
      };
      getRequest('/gateway-manage/page-api-version-record', para)
        .then(res => {
          let resData = res.data;
          that.loading = false;
          if (resData.code == '0000') {
            that.tableData = resData.result.result || [];
            if (resData.result.result.length) {
              resData.result.result.forEach(ele => {
                ele.defaultFlag = ele.defaultFlag == 1 ? true : false;
              });
            }
            that.totalCount = resData.result.totalCount;
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loading = false;
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  }
};
</script>
<style lang="less" scoped>
.w-320 {
  width: 320px;
}
.w-137 {
  width: 137px;
}
.m-t-14 {
  margin-top: 14px;
}
</style>
