<!--
 * @Descripttion: sql列表
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-11-09 11:16:12
 * @LastEditors: 无尘
 * @LastEditTime: 2020-11-19 16:46:05
-->
<!--  -->
<template>
  <div class="common-right">
    <div class="m-b-20">
      <el-input placeholder="请输入 SQL"  maxlength="250" v-model="searchInput" class="w-180" @keyup.native="value => toInput(value, searchInput)" clearable @clear="clearInput"></el-input>
      <el-date-picker class="m-l-10 w-249" :editable="false" v-model="createDate" prefix-icon="el-icon-time" type="daterange" range-separator="~" value-format="yyyy-MM-dd" :default-time="['00:00:00', '23:59:59']" start-placeholder="开始日期" end-placeholder="结束日期" @change="changeDate"></el-date-picker>
      <el-select class="m-l-10 w-130" v-model="sqlCheckIndexType" placeholder="请选择" @change="changeCondition">
        <el-option
          v-for="item in perfectOption"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-select class="m-l-10 w-130" v-model="statusFlag" placeholder="请选择" @change="changeCondition">
        <el-option
          v-for="item in onlineOption"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-select class="m-l-10 w-130" v-model="sqlCheckIndexStatus" placeholder="是否需要完善" @change="changeCondition">
        <el-option
          v-for="item in isPerfectOption"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button class="m-l-10" :loading="loadStatus" type="primary" @click="multStatus(1)">完善上线状态</el-button><el-button class="m-l-10" :loading="loadExport" type="primary" @click="exportSql">导出脚本</el-button>
    </div>
    <!-- <div class="m-b-20">
      <el-button type="primary" @click="multPerfect(1)">批量是否需要完善sql</el-button><el-button type="primary" @click="multStatus(1)">批量完善上线状态</el-button><el-button type="primary" @click="exportSql">导出脚本</el-button>
    </div> -->
    <el-table class="select-table" ref="multipleTable" v-loading="loading" :data="tableData" tooltip-effect="dark" :style="{ width: '100%', minHeight: tableH }" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="项目名称" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.sqlCheckProjectName || '--' }}</template>
      </el-table-column>
      <el-table-column label="表名称" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.sqlCheckTableName || '--' }}</template>
      </el-table-column>
      <el-table-column label="是否需要完善" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.sqlCheckIndexStatus"
            @change="changePerfect($event, scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="SQL" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.sqlCheckSql || '--' }}</template>
      </el-table-column>
      <el-table-column label="完善状态" show-overflow-tooltip>
        <template slot-scope="scope"><span :class="['span-dot', scope.row.sqlCheckIndexType == 1 ? 'bg-52c41a ' : 'bg-d9d9d9']"></span><span class="p-l-8">{{ scope.row.sqlCheckIndexType== 1? '已完善' : '未完善' }}</span></template>
      </el-table-column>
      <el-table-column label="上线状态" show-overflow-tooltip>
        <template slot-scope="scope">
           <el-switch
            v-model="scope.row.statusFlag"
            @change="changeStatus($event, scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="" label="创建时间" show-overflow-tooltip>
        <template slot-scope="scope">
          <div>{{ scope.row.createTime | timeStampToYmd }} {{ !scope.row.createTime ? '--': '' }}</div>
          <div>{{ scope.row.createTime | timeStampToHms }} {{ !scope.row.createTime ? '--': '' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作人" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.commitName || '--' }}</template>
      </el-table-column>
      <el-table-column prop="" label="操作"  width="136">
        <template slot-scope="scope">
          <el-button type="text" @click="toShowIndex(scope.row)">完善索引</el-button><el-button type="text" @click="toShowDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block common-wrap__page text-right m-t-24" v-if="tableData.length != 0">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </div>
    <sql-detail v-if="showDetail" :sql-row="sqlRow" @closeDetail="closeDetail"></sql-detail>
    <index-dialog v-if="showIndex" :sql-check-index="sqlCheckIndex" :sql-check-sql-id="sqlCheckSqlId" @closeText="closeText" @submitText="submitText"></index-dialog>
  </div>
</template>

<script>
import sqlDetail from '@/components/sql/sql-detail.vue';
import indexDialog from '@/components/sql/index-dialog.vue';
import { _debounce } from '@/common/js/public';
import fetch from '@/api/sql';

const { getSqlList, setPerfect, setStatus, exportData } = fetch;
export default {
  name: 'SqlList',
  components: { sqlDetail, indexDialog },
  data() {
    return {
      userInfo: localStorage.getItem('haobanOperate') ? JSON.parse(localStorage.getItem('haobanOperate')) : { id: '', userMobile: '', realName: '', },

      searchInput: '',
      createDate: [],
      sqlCheckIndexType: '',
      perfectOption: [
        {
          value: '',
          label: '全部完善状态'
        },
        {
          value: '1',
          label: '已完善'
        },
        {
          value: '0',
          label: '未完善'
        },
      ],
      statusFlag: '',
      onlineOption: [
        {
          value: '',
          label: '全部上线状态'
        },
        {
          value: '1',
          label: '已上线'
        },
        {
          value: '0',
          label: '未上线'
        },
      ],
      sqlCheckIndexStatus: '',
      isPerfectOption: [
        {
          value: '',
          label: '是否需要完善'
        },
        {
          value: '1',
          label: '是'
        },
        {
          value: '0',
          label: '否'
        },
      ],
      // 分页参数
      currentPage: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      tableData: [],
      multipleSelection: [],
      showDetail: false,
      sqlRow: {},
      showIndex: false,
      sqlCheckSqlId: '',
      sqlCheckIndex: '',
      loadStatus: false,
      loadExport: false
    };
  },
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    const that = this;
    that.getTableData();
  },

  // methods
  methods: {
    /**
     * @description: 批量操作
     * @author: 无尘
     */
    // multPerfect(e) {

    // },
    multStatus(e) {
      const that = this;
      if (!that.multipleSelection.length) {
        that.$message.error('请先选择数据');
        return false;
      }
      that.loadStatus = true;
      that.changeStatus(e);
    },
    /**
     * @description: 导出脚本
     * @author: 无尘
     */
    exportSql() {
      const that = this;
      if (!that.createDate) {
        that.createDate = [];
      }
      that.loadExport = true;
      const param = {
        project: that.$route.query.sqlCheckProjectId,
        table: that.$route.query.sqlCheckTableId,
        sqlCheckIndexType: that.sqlCheckIndexType,
        statusFlag: that.statusFlag,
        sqlCheckIndexStatus: that.sqlCheckIndexStatus,
        startDate: that.createDate[0],
        endDate: that.createDate[1],
      };
      exportData(param, {responseType: 'blob'}).then(res => {
        that.loadExport = false;
        if (res.indexOf('result:null') != -1) {
          that.$message.error('暂无数据');
          return false;
        }
        that.$message.success('导出成功');
        const blob = new Blob([ res ], {
          type: 'application/vnd.ms-excel'
        });
        const fileName = 'sql脚本.csv';
        const elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      })
        .catch(function(error) {
          that.loadExport = false;
        });
    },
    /**
     * @description: 条件
     * @author: 无尘
     */
    changeCondition() {
      const that = this;
      that.currentPage = 1;
      that.getTableData();
    },
    changeDate(e) {
      const that = this;
      if (!e) {
        that.createDate = [];
      }
      that.currentPage = 1;
      that.getTableData();
    },
    /**
     * @description: 完善索引
     * @param {Object} row
     * @author: 无尘
     */
    toShowIndex(row) {
      const that = this;
      that.showIndex = true;
      that.sqlCheckSqlId = row.sqlCheckSqlId;
      that.sqlCheckIndex =  row.sqlCheckIndex;
    },
    closeText() {
      const that = this;
      that.showIndex = false;
      that.sqlCheckSqlId = '';
      that.sqlCheckIndex = '';
    },
    submitText() {
      const that = this;
      that.showIndex = false;
      that.sqlCheckSqlId = '';
      that.sqlCheckIndex = '';
      that.getTableData();
    },
    toShowDetail(row) {
      const that = this;
      that.showDetail = true;
      that.sqlRow = row;
    },
    closeDetail() {
      const that = this;
      that.showDetail = false;
      that.sqlRow = {};
    },
    /**
     * @description: 开关
     * @param {Boolean} e
     * @param {Object} row
     * @author: 无尘
     */
    changePerfect(e, row) {
      const that = this;
      const param = {
        sqlCheckIndexStatus: e ? 1 : 0,
        sqlCheckSqlId: row ? row.sqlCheckSqlId : that.multipleSelection.map(ele=>ele.sqlCheckSqlId).join(','),
        commitId: that.userInfo.id,
        commitName: that.userInfo.realName
      };
      setPerfect(param).then(res => {
        if (res.code == '0000') {
          that.$message.success('设置成功');
          that.getTableData();
        }else{
          if (row) {
            row.sqlCheckIndexStatus = e ? false : true;
          }
          that.$message.error(res.message);
        }
      })
        .catch(function(error) {
          if (row) {
            row.sqlCheckIndexStatus = e ? false : true;
          }
        });
    },
    changeStatus(e, row) {
      const that = this;
      const param = {
        statusFlag: e ? 1 : 0,
        sqlCheckSqlId: row ? row.sqlCheckSqlId : that.multipleSelection.map(ele=>ele.sqlCheckSqlId).join(','),
        commitId: that.userInfo.id,
        commitName: that.userInfo.realName
      };
      setStatus(param).then(res => {
        that.loadStatus =  false;
        if (res.code == '0000') {
          that.$message.success('设置成功');
          that.getTableData();
        }else{
          if (row) {
            row.statusFlag = e ? false : true;
          }
          that.$message.error(res.message);
        }
      })
        .catch(function(error) {
          that.loadStatus =  false;
          if (row) {
            row.statusFlag = e ? false : true;
          }
        });
    },

    /**
     * @description: 输入
     * @param {Object} e
     * @param {String} value
     * @author: 无尘
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      that.currentPage = 1;
      that.getTableData();
    }, 500),
    /**
     * @description: 搜索清除
     * @author: 无尘
     */
    clearInput() {
      const that = this;
      that.currentPage = 1;
      that.getTableData();
    },
    /**
     * @description: 分页---页码变化
     * @param {Number} val
     * @author: 无尘
     */
    handleSizeChange(val) {
      const that = this;
      that.currentPage = 1;
      that.pageSize = val;
      that.getTableData();
    },
    /**
     * @description: 分页---当前页变化
     * @param {Number} val
     * @author: 无尘
     */
    handleCurrentChange(val) {
      const that = this;
      that.currentPage = val;
      that.getTableData();
    },
    /**
     * @description: 勾选
     * @param {Array} val
     * @author: 无尘
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /**
     * @description: 获取表列表
     * @author: 无尘
     */
    getTableData() {
      const that = this;
      that.loading = true;
      if (!that.createDate) {
        that.createDate = [];
      }
      const param = {
        project: that.$route.query.sqlCheckProjectId,
        table: that.$route.query.sqlCheckTableId,
        sqlCheckIndexType: that.sqlCheckIndexType,
        statusFlag: that.statusFlag,
        search: that.searchInput,
        sqlCheckIndexStatus: that.sqlCheckIndexStatus,
        startDate: that.createDate[0],
        endDate: that.createDate[1],
        pageNum: that.currentPage,
        pageSize: that.pageSize
      };
      getSqlList(param).then(res => {
        that.loading = false;
        if (!!res.result.result && !!res.result.result.length) {
          res.result.result.forEach(ele=> {
            ele.sqlCheckIndexStatus = ele.sqlCheckIndexStatus == 1 ? true : false;
            ele.statusFlag = ele.statusFlag == 1 ? true : false;
          });
        }
        that.tableData = res.result.result || [];
        that.total = res.result.totalCount || 0;
      })
        .catch(function(error) {
          that.loading = false;
        });
    },
  },
  watch: {}
};
</script>
<style lang='less' scoped>
  .m-l-10 {
    margin-left: 10px;
  }
  .w-130 {
    width: 130px;
  }
  .w-249 {
    width: 249px;
  }
  .w-180 {
    width: 180px;
  }
  .span-dot {
    display: inline-block;
    vertical-align: middle;
    width: 6px;
    height: 6px;
    margin-right: 6px;
    border-radius: 3px;
    &.bg-52c41a  {
      background: #52c41a ;
    }
    &.bg-d9d9d9 {
      background: #d9d9d9;
    }
  }
</style>
