<template>
  <div class="ls-vertical" >
    <navbar title="拜访报告" :buttons="btns" @clickbutton="clickbtn" icon="look"></navbar>
    <search ref="search" @query="chaData"></search>
    <div class="ls-container" style="overflow: auto;">
      <div class="ls-btn-row">
        <div class="left">
          <img src="@/assets/img/public/icon-list.png" />
          <span >列表</span>
        </div>
        <div><el-button @click="addVisit" icon="el-icon-plus" type="primary" size="mini">添加拜访报告</el-button></div>
      </div>
      <div class="ls-table-warp">
        <el-table :data="datas" ref="tableRef"  size="mini" stripe border height="100%" :cell-style="cellStyle" @row-dblclick="show"  highlight-current-row>
          <!--<el-table-column type="selection" width="50"></el-table-column>-->
          <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"
            :min-width="item.width"
            :show-overflow-tooltip="item.tooltip"
            :fixed="item.fixed"
          >
            <template v-if="item.prop == 'visitDateFormat'" 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="200" prop="status">
            <template slot-scope="scope">
              <el-button v-if="scope.row.reviewStatus != 'draft'" type="text"  size="mini" @click="doAddOrUpdate(scope.row)">详情</el-button>
              <el-button v-if="scope.row.reviewStatus == 'draft'" type="text" size="mini"  @click="editVisit(scope.row)">编辑</el-button>
              <el-button v-if="scope.row.reviewStatus == 'draft'" type="text" size="mini"  @click="deletes(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--分页-->
      <el-pagination
        @size-change="pagerHandleSizeChange"
        @current-change="pagerHandleCurrentChange"
        :current-page="pager.currPage"
        :page-size="pager.pageSize"
        :page-sizes="pager.pageOptions"
        :total="pager.totalRow"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
      <visit-dict-add-update @callback="callback" ref="refDictAddUpdate"></visit-dict-add-update>
    </div>
  </div>
</template>

<script>
import search from './components/visitReport-search.vue';
import commonSelect from '../../components/common-select.vue';
import visitDictAddUpdate from './components/visitReport-dict-add-update.vue';
import commonSelectList from '../../common/commonSelectList.js';
export default {
  name: 'visitReport-list',
  components: {
    search,
    visitDictAddUpdate,
    commonSelect
  },
  mounted: function() {

  },
  activated(){
    let _this = this;
    this.$nextTick(function() {
      _this.doQuery();
    });
  },
  updated() {

  },
  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 == 'visitDateFormat'){
        this.sortField = 'V.VISIT_DATE';
      }
      this.doQuery();

    },
    //双击点击查看详情
    show(row) {
      this.EditdialogFormVisible = true;
      this.showform = row;
      this.doAddOrUpdate(row);
    },
    /**
     * 控制表格的颜色
     * row为某一行的除操作外的全部数据，column为某一列的属性，
     * rowIndex为某一行（从0开始数起），columnIndex为某一列（从0开始数起）
     */
    cellStyle({ row, column, rowIndex, columnIndex }) {
      let cellStyle;
      if (column.label === '状态') {
        switch (row.reviewStatus) {
          case 'draft':
            cellStyle = 'color: #909399;';
            break;
          case 'readed':
            cellStyle = 'color: #67C23A;';
            break;
          default:
            cellStyle = 'color: #409EFF;';
        }
      }
      return cellStyle;
    },

    //按钮操作
    btnOperation: function(btnName, row) {
      if (btnName === 'details') {
        return this.doAddOrUpdate('edit', row);
      } else if (btnName === 'delete') {
        return this.deletes(row);
      }
    },

    callback: function() {
      this.doQuery();
    },

    //删除
    deletes: function(row) {
      console.log(row);
      this.$confirm(`此操作将删除该拜访报告, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let param = {
            id: row.id,
            reviewStatus: row.reviewStatus
          };
          this.$ajax.post({
            domain: 'crmUrl',
            url: 'visit.deleteVisitReport',
            data: JSON.stringify(param),
            success: function(res) {
              console.log(res);
              if (res.errorCode == 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                });
                this.doQuery();
              } else {
                this.$message.error(res.body.msg);
              }
            }.bind(this),
            error: function(res) {
              this.$message.error(res.body.msg);
            }.bind(this)
          });
        })
        .catch(() => {});
    },

    editVisit(row) {
      console.log(row);
      this.$router.push({
        path: 'addVisit',
        query: {
          rowData: row
        }
      });
    },

    //新增拜访报告
    addVisit() {
      this.$router.push({
        path: 'addVisit'
      });
    },

    //分页查询
    doQuery() {
      let paramInner = {
        sortField: this.sortField,
        sort: this.sort,
      };

      Object.assign(paramInner, this.$refs.search.queryParam );
      let param = {
        currPage: this.pager.currPage,
        pageSize: this.pager.pageSize,
        queryParam: paramInner
      };
      this.$ajax.post({
        domain: 'crmUrl',
        url: 'visit.visitReportList',
        data: JSON.stringify(param),
        success: function(res) {
          if (res.errorCode == 200) {
            this.datas = 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.body.msg);
          }
        }.bind(this),
        error: function(res) {
          this.$message.error(res.body.msg);
        }.bind(this)
      });
    },
    //跳转
    doAddOrUpdate(row) {
      let pathInfo = 'detailsVisit'
      if(row.reviewStatus==='draft'){
          pathInfo = 'addVisit'
      }
      this.$router.push({
        path: pathInfo,
        query: {
          rowData: row
        }
      });
    },
    //从搜索带过来的查询条件
    chaData(data) {
      if ( typeof data != 'undefined') {
        this.pager.curPage = data;
      }

      this.doQuery();
    },

    // 变更页面显示数量
    pagerHandleSizeChange(val) {
      this.pager.pageSize = val;
      this.doQuery();
    },

    // 变更当前页面
    pagerHandleCurrentChange(val) {
      this.pager.currPage = val;
      this.doQuery();
    },

    // 导航栏按钮操作
    clickbtn: function(type) {
      switch (type) {
        case 'refresh':
          this.pager.currPage = 1;
          this.pager.pageSize = 10;
          this.doQuery();
          break;
      }
    },

    // 日志信息展示
    showLogsInfo: function(msg) {
      this.$refs.logRef.logMsg = msg;
      this.$refs.logRef.visible = true;
    }
  },

  data: function() {
    return {

      visitStatus: [],
      btns: [
        {
          title: '',
          btnEvent: 'refresh',
          size: '',
          circle: 'circle',
          type: 'refresh',
          show: true,
          icon: ''
        }
      ],
      sortField: '',
      sort: '',
      btnList: [
        {
          name: 'details',
          type: 'text',
          size: 'small',
          content: '详情'
        },
        {
          name: 'delete',
          type: 'text',
          size: 'small',
          content: '删除'
        }
      ],
      pager: {
        currPage: 1,
        pageSize: 20,
        pageOptions: [20, 30, 50],
        totalRow: 0
      },
      datas: [],
      queryParam: {},

      //表格列
      colunms: [
        {
          prop: 'visitDateFormat',
          label: '拜访时间',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'customer',
          label: '客户名称',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'agentName',
          label: '代理商',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'salesUserName',
          label: '销售人员',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'visitSubject',
          label: '拜访主题',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'visitPurposeName',
          label: '拜访目的',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'reviewStatusKey',
          label: '状态',
          width: 100,
          fixed: false,
          tooltip: true
        },
        {
          prop: 'visitCode',
          label: '编号',
          width: 100,
          fixed: false,
          tooltip: true
        },
      ]
    };
  }
};
</script>

<style lang="scss">
.project-list.ls-container {

  .sort-caret.descending, .sort-caret.ascending {
    border-top-color: #409eff;
  }

  position: relative;
  > .btns-project {
    position: absolute;
    right: 10px;
    top: 16px;
    z-index: 9;
  }

  .el-tabs {
    overflow: hidden;
    .table-wrap {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: auto;
    }
  }
  .el-table .el-table__empty-block {
    min-height: unset;
  }

}
</style>
