<template>
  <div class="ls-vertical">
    <navbar icon="cooperation" title="工作报告" :buttons="btns" @clickbutton="clickbtn"></navbar>
    <search ref="searchRef" @query="querySearch" @callback="querySearch"></search>
    <div class="ls-container">
      <el-button @click="handleAdd" type="primary" size="mini" icon="el-icon-plus">写报告</el-button>
      <div style="flex: 1;overflow: hidden;display: flex;flex-direction: column;">
        <el-tabs v-model="activeTab" @tab-click="tabChange" style="overflow: hidden;">
          <el-tab-pane v-for="(items, index) in tabTable" :key="index" :label="items.label" :name="items.name">
            <el-table :data="tableData" ref="multipleRef" size="mini" height="100%" stripe border :cell-style="cellStyle" @row-dblclick="show" style="cursor: pointer;">
              <el-table-column type="index" label="序号" width="60" show-overflow-tooltip></el-table-column>
              <el-table-column
                v-for="(item, index) in colunms"
                :key="index"
                :prop="item.prop"
                :label="item.label"
                :fixed="item.fixed"
                :class-name="item.prop == 'status' ? 'c3383DA' : ''"
                :min-width="item.width"
                :show-overflow-tooltip="item.tooltip"
              >
                <template v-if="item.prop == 'createDateFormat'" slot="header">
                  <span>提交时间</span>
                  <span class="caret-wrapper">
                 <i @click="handleAscending($event, 'ascending', item.prop)" class="sort-caret ascending"></i>
                 <i @click="handleAscending($event, 'descending', item.prop)" class="sort-caret descending"></i>
                </span>
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="120">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.reviewStatus != 'draft'" @click="handleDetail(scope.row)" type="text">详情</el-button>
                  <el-button v-if="scope.row.reviewStatus == 'draft'" @click="editDetail(scope.row)" type="text">编辑</el-button>
                  <el-button v-if="scope.row.reviewStatus == 'draft'" @click="deleteWork(scope.row)" type="text">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- 分页-->
      <el-pagination
        @size-change="pagerHandleSizeChange"
        @current-change="pagerHandleCurrentChange"
        :current-page="pager.currPage"
        :page-sizes="pager.pageOptions"
        :page-size="pager.pageSize"
        :total="pager.totalRow"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import search from './components/work-list-search.vue';
import commonSelectList from '../../../common/commonSelectList.js';
export default {
  name: 'workList',
  components: {
    search,
    commonSelectList
  },
  beforeDestroy() {
    localStorage.removeItem('taskStatus');
  },

  mounted() {
    let _this = this;
    this.activeTab = localStorage.getItem('activeTab') || 'all';
    localStorage.removeItem('activeTab');
  },
  // 这里调用刷新接口
  activated() {
    this.doQuery();
  },
  methods: {
    handleAscending(e, sort, prop){
      let ct = e.currentTarget;
      document.querySelectorAll('.sort-caret.ascending').forEach(item=>{
        item.style.borderBottomColor = '#C0C4CC';
      })
      document.querySelectorAll('.sort-caret.descending').forEach(item=>{
        item.style.borderTopColor = '#C0C4CC';
      })

      if(ct.classList[1] == 'ascending'){
        ct.style.borderBottomColor = '#409eff';
      } else {
        ct.style.borderTopColor = '#409eff';
      }
      if(sort == 'ascending'){
        this.sort = 'ASC';
      }else {
        this.sort = 'DESC';
      }
      if(prop == 'createDateFormat'){
        this.sortField = 'W.CREATE_TIME';
      }
      this.doQuery();
    },
    //双击点击查看详情
    show(row) {
      this.EditdialogFormVisible = true;
      this.showform = row;
      this.handleDetail(row);
    },
    /**
     * 控制表格的颜色
     * row为某一行的除操作外的全部数据，column为某一列的属性，
     * rowIndex为某一行（从0开始数起），columnIndex为某一列（从0开始数起）
     */
    cellStyle({ row, column, rowIndex, columnIndex }) {
      let cellStyle;
      if (column.label === '报告标题') {
          cellStyle = 'text-align:left;';
      }
      if (column.label === '批阅状态') {
        switch (row.reviewStatus) {
          case 'draft':
            cellStyle = 'color: #909399;';
            break;
          case 'readed':
            cellStyle = 'color: #67C23A;';
            break;
          default:
            cellStyle = 'color: #409EFF;';
        }
      }
      return cellStyle;
    },

    //搜索框调用
    querySearch() {
      this.queryParam = this.$refs.searchRef.queryParam;
      this.pager.currPage = 1;
      this.pagerHandleCurrentChange(this.pager.currPage);
    },

    // 查询数据
    doQuery(current = {}) {
      this.queryParam = JSON.stringify(current) !== '{}' ? current : this.queryParam;
      var keycount = 0;
      for (var item in current) {
        keycount++;
      }
      if (keycount > 0) {
        this.queryParam = current;
      }
      this.queryParam.submitType = this.tabTableTab;
      this.queryParam.sortField = this.sortField;
      this.queryParam.sort = this.sort;
      let param = {
        currPage: this.pager.curPage,
        pageSize: this.pager.pageSize,
        queryParam: this.queryParam
      };
      this.$ajax.post({
        domain: 'crmUrl',
        url: 'work.listWorkPage',
        data: JSON.stringify(param),
        success: function(res) {
          if (res.errorCode == 200) {
            this.tableData = res.data.records || [];
            this.pager.totalRow = res.data.total || 0;
            this.pager.currPage = res.data.current;
            this.pager.pageSize = res.data.size;
          } else {
            this.$message.error(res.msg);
          }
        }.bind(this),
        error: function(res) {
          this.$message.error(res.msg);
        }.bind(this)
      });
    },
    //编辑
    editDetail(row) {
      this.$router.push({
        path: 'addWork',
        query: {
          rowData: row
        }
      });
    },
    //删除
    deleteWork(row) {
      let rowData = {
        id: row.id
      };
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      })
        .then(() => {
          this.$ajax.post({
            domain: 'crmUrl',
            url: 'work.deleteDraftWork',
            data: JSON.stringify(rowData),
            success: function(res) {
              console.log(res);
              if (res.errorCode === 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.doQuery();
              } else {
                this.$message.error(res.msg);
              }
            }.bind(this),
            error: function(res) {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {});
    },
    //tab 改变
    tabChange(tab, event, index) {
      this.activeTab = index;
      this.activeTab = tab.name;
      switch (tab.name) {
        case 'all':
          this.tabTableTab = 'all';
          break;
        case 'submit_me':
          this.tabTableTab = 'submit_me';
          break;
        case 'my_submit':
          this.tabTableTab = 'my_submit';
          break;
        case 'subordinate':
          this.tabTableTab = 'subordinate';
          break;
         case 'notifyMe':
           this.tabTableTab = 'notifyMe';
          break;
        default:
      }
      this.doQuery();
    },
    //详情
    handleDetail(row) {
      let pathInfo = 'detailswork'
      if(row.reviewStatus==='draft'){
         pathInfo = 'addwork'
      }
      this.$router.push({
        path: pathInfo,
        query: {
          rowData: row
        }
      });
    },
    //编辑
    taskEdit(row) {
      console.log(row);
      this.rowList = row;
      this.$refs.digTaskListRef.visible = true;
      this.$refs.digTaskListRef.openTitle = '编辑';
      this.$refs.digTaskListRef.paramForm = JSON.parse(JSON.stringify(row)); //解决get，set监听问题
    },
    //添加工作报告
    handleAdd() {
      this.$router.push({
        path: 'addwork',

      });
    },

    //分页
    // 变更页面显示数量
    pagerHandleSizeChange(val) {
      this.pager.pageSize = val;
      this.doQuery();
    },
    // 变更当前页面
    pagerHandleCurrentChange(val) {
      this.pager.curPage = val;
      this.doQuery();
    },
    // 导航栏按钮操作
    clickbtn(type) {
      switch (type) {
        case 'refresh':
          //这是上面刷新按钮事件
          this.pager.curPage = 1;
          this.pager.pageSize = 10;
          this.queryParam = {};
          this.doQuery();
          this.$refs.searchRef.reSet();
          break;
      }
    }
  },
  beforeRouteLeave(to, from, next) {
    console.log(this);
    sessionStorage.setItem('activeTab', this.activeTab);
    sessionStorage.setItem('tabTableTab', this.tabTableTab);
    next();
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      const tabTableTab = sessionStorage.getItem('tabTableTab');
      if (tabTableTab) {
        vm.tabTableTab = tabTableTab;
      }
    });
  },
  data() {
    return {
      btns: [
        {
          title: '',
          btnEvent: 'refresh',
          size: '',
          circle: 'circle',
          type: 'refresh',
          show: true,
          icon: ''
        }
      ],
      rowList: {},
      stutasData: [],
      queryParam: {
        createrId: '',
        deptId: '',
        endTime: '',
        reviewStatus: '',
        starTime: '',
        workType: '',
        submitType: 0,
        reportBigType: 'workReport',
        sort: '',
        sortField: ''
      },
      activeTab: 'all',
      sortField: '',
      sort: '',
      workStatus: [],
      tabTableTab: 'all',
      //分页参数
      pager: {
        curPage: 1,
        pageSize: 20,
        pageOptions: [20, 30, 50],
        totalRow: 0
      },
      tabTable: [
        {
          label: '全部报告',
          name: 'all'
        },
        {
          label: '我提交的',
          name: 'my_submit'
        },
        {
          label: '提交给我的',
          name: 'submit_me'
        },
        {
          label: '下属提交的',
          name: 'subordinate'
        },
        {
          label: '知会我的',
          name: 'notifyMe'
        },
      ],
      tableData: [],
      users: [], //v-mdoel aws-org users
      colunms: [
        //表格列
        {
          prop: 'workTitle',
          label: '报告标题',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'deptName',
          label: '提交部门',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'creater',
          label: '提交人员',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'workTypeKey',
          label: '报告类型',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'reviewStatusKey',
          label: '批阅状态',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'createDateFormat',
          label: '提交时间',
          width: 100,
          fixed: false,
          tooltip: true
        }
      ]
    };
  }
};
</script>

<style scoped lang="scss">
.ls-container {
  overflow: hidden;
  padding: 8px 15px 0;
  position: relative;


  > .el-button {
    position: absolute;
    right: 10px;
    top: 8px;
    z-index: 9;
  }

}

.el-table__body-wrapper is-scrolling-none {
  // height: 469px !important;
}
</style>
