<template>
  <div class="app-container">
    <SearchForm v-show="showSearch" ref="SearchForm" :user-options="userOptions" :source-options="sourceOptions" @search="_getTableList" />
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['zs:clue:add']" icon="el-icon-plus" type="primary" @click="handleAddandUpdate(undefined)">新增</el-button>
        <el-button v-hasPermi="['zs:clue:import']" icon="el-icon-upload" type="warning" @click="handleImport(false)">导入</el-button>
        <el-button v-hasPermi="['zs:clue:import']" icon="el-icon-upload" type="warning" @click="handleImport(true)">一点通导入</el-button>
        <el-button v-hasPermi="['zs:clue:export']" icon="el-icon-download" type="warning" @click="handleExport">导出</el-button>
        <el-button v-hasPermi="['zs:clue:edit']" icon="el-icon-edit" type="primary" :disabled="multiple" @click="handleBatChUpdate()">批量修改</el-button>
        <el-button type="primary" @click="handlePublicClue">公海</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" :columns="columns" @queryTable="_getTableList" />
    </el-row>
    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange" border @row-dblclick="handleRowClick" @cell-click="handleCellClick">
      <el-table-column type="selection" width="50" align="center" />
      <template v-for="item in columns">
        <el-table-column v-if="item.visible && item.prop != 'clueMemo'" :key="item.prop" :label="item.label" align="center" :width="item.width" :prop="item.prop" :show-overflow-tooltip="item.overflow" />
        <el-table-column v-if="item.visible && item.prop == 'clueMemo'" :key="item.prop" :label="item.label" align="center" :width="item.width" :prop="item.prop" :show-overflow-tooltip="item.overflow" />
      </template>
      <el-table-column label="意向状态" prop="intentionState" sortable fixed="right" min-width="100">
        <template slot-scope="{ row }">
          <el-tag effect="dark" style="border: none" :color="tagColorMap[row.intentionState]">{{ row.intentionState }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="left" min-width="200">
        <template slot-scope="scope">
          <el-button v-if="(admin == 'true' || scope.row.followUser2.indexOf(userId) != -1 )" v-hasPermi="['zs:clue:edit']" type="text" style="color: red;" @click.native.stop="handleAddandUpdate(scope.row)">编辑</el-button>
          <el-button v-if="(admin == 'true' || scope.row.followUser2.indexOf(userId) != -1  )" v-hasPermi="['zs:clue:distribute']" type="text" @click.native.stop="handleDistribute(scope.row)">分发</el-button>
          <el-button v-if="(admin == 'true' || scope.row.followUser2.indexOf(userId) != -1  ) && scope.row.state" v-hasPermi="['zs:clue:sign']" type="text" style="color: #26a69a" @click.native.stop="handleSign(scope.row)">已登记</el-button>
          <el-button v-if="(admin == 'true' || scope.row.followUser2.indexOf(userId) != -1  ) && !scope.row.state" v-hasPermi="['zs:clue:sign']" type="text" @click.native.stop="handleSign(scope.row)">未登记</el-button>
          <el-button v-if="(admin == 'true' || scope.row.followUser2.indexOf(userId) != -1  )" v-hasPermi="['zs:clue:remove']" type="text" @click.native.stop="handleDelete(scope.row)">删除</el-button>
          <el-button v-if="(admin == 'true' || scope.row.followUser2.indexOf(userId) != -1  ) && !scope.row.state" v-hasPermi="['zs:clue:discard']" type="text" @click.native.stop="handleDiscard(scope.row)">释放</el-button>
          <el-button v-if="quickSearch == 8" type="text" @click="handleViewZhuangDan(scope.row)"> 撞单信息</el-button>
          <!-- <el-button v-if="searchForm.quickSearch == 8" type="text" > 撞单信息</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" :page.sync="searchForm.pageNum" :limit.sync="searchForm.pageSize" :page-sizes="[10, 20, 30, 50, 100]" @pagination="_getTableList" />
    <!-- 批量修改 -->
    <BatchUpdateDialog ref="batchUpdateDialogForm" :options="options" @refreshDataList="_getTableList" />
    <!-- 公海  -->
    <PublicDialog ref="publicDialogForm" @refreshDataList="_getTableList" />
    <!-- 上传 -->
    <UploadDialog ref="uploadDialogForm" @refreshDataList="_getTableList" />
    <!-- 登记弹框 -->
    <SignFormDialog ref="signDialogForm" :clue-info="clueInfo" />
    <!-- 分发 -->
    <DistributeFormDialog ref="distributeDialogForm" @refreshDataList="_getTableList" />
    <!-- 撞单信息 -->
    <ZhuangDanDialog ref="zhuangDanDialog" />
    <!-- 备注编辑 -->
    <MemoFormDialog ref="memoDialog" @refreshDataList="_getTableList" />

  </div>
</template>

<script>
import SearchForm from './components/SearchForm.vue';
import BatchUpdateDialog from './components/BatchUpdateDialog.vue';
import PublicDialog from './components/PublicDialog.vue';
import UploadDialog from './components/UploadDialog.vue';
import DistributeFormDialog from './components/DistributeFormDialog.vue';
import SignFormDialog from '../sign/components/SignFormDialog.vue';
import ZhuangDanDialog from './components/ZhuangDanDialog.vue';
import MemoFormDialog from './components/MemoFormDialog.vue';

import { defaultColumns } from './columns.js';
import { getClueList, deleteClue, getClueCountBadge, discardClue, getSign, getConsultRecord } from '@/api/zs/clue';
import empApi from '@/api/system/employee';
export default {
  name: 'Clue',
  beforeRouteEnter(to, from, next) {
    if (from.name == 'ClueForm') {
      next(vm => {
        vm._getTableList()
      })
    } else {
      next()
    }
  },
  components: {
    SearchForm, BatchUpdateDialog, PublicDialog, UploadDialog, SignFormDialog, DistributeFormDialog, ZhuangDanDialog, MemoFormDialog
  },
  data() {
    return {
      admin: localStorage.getItem('admin'),
      userId: localStorage.getItem('userId'),
      showSearch: true,
      searchForm: {
        pageNum: 1,
        pageSize: 10
      },
      tableList: [],
      total: 0,
      columns: [],
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      expireCount: 0,
      userOptions: [],
      sourceOptions: [],
      tagColorMap: {
        A高意向: '#ff7043',
        B中意向: '#26a69a',
        C无意向: '#5c6bc0',
        D未知意向: '#ef5350',
        报名成功: '#ffa726',
        报名他校: '#afaeb0',
        无效线索: '#afaeb0'
      },
      options: undefined,
      clueInfo: undefined,
      consultRecord: [],
      quickSearch: 0
    };
  },
  created() {
    const str = localStorage.getItem(`${this.$route.name}-table-columns`);
    this.columns = str ? JSON.parse(str) : defaultColumns;
    this._getClueCountBadge();
    this.getEmployee();
    // 线索来源
    this.getDicts('dm_source').then((response) => {
      this.sourceOptions = response.data;
    });
    // 意向状态
    this.getDicts('dm_intention_state').then((response) => {
      this.intentionOptions = response.data;
    });
    this._getTableList();
  },
  methods: {
    // 分页查询表格数据
    _getTableList() {
      this.loading = true;
      const tempForm = this.$refs.SearchForm?.searchForm || {};
      this.quickSearch = tempForm.quickSearch
      const params = { ...this.searchForm, ...tempForm };
      getClueList(params).then((response) => {
        this.tableList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取已过期线索数
    async _getClueCountBadge() {
      const resp = await getClueCountBadge();
      if (resp.code === 200) {
        this.expireCount = resp.data;
      }
    },
    // 新增或修改
    handleAddandUpdate(info) {
      this.$router.push('/zs/clue-form/index/' + (info ? info.clueId : 0));
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection);
      this.ids = selection.map((item) => item.clueId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 释放线索操作
    handleDiscard(item) {
      this.$confirm('是否确认释放该条线索（“' + item.name + '/' + item.phone + '”）到公海?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then((res) => {
          discardClue(item).then((resp) => {
            if (resp && resp.code === 200) {
              this.$message.success('释放成功');
              this._getTableList();
            }
          });
        })
        .catch(function () { });
    },
    // 删除
    handleDelete(item) {
      this.$confirm('是否确认删除该条线索（“' + item.name + '/' + item.phone + '”）?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then((res) => {
          deleteClue({ clueId: item.clueId }).then((resp) => {
            if (resp.code === 200) {
              this.$message.success('删除成功');
              this._getTableList();
            }
          });
        })
        .catch(function () { });
    },
    // 导入
    handleImport(ydtData) {
      this.$nextTick(() => {
        this.$refs.uploadDialogForm.init(ydtData);
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出所有学员信息项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const tempForm = this.$refs.SearchForm?.searchForm || {};
        this.download('zs/clue/export', tempForm, `线索信息_${new Date().getTime()}.xlsx`);
      });
    },
    // 公海按钮点击时间
    handlePublicClue() {
      this.$nextTick(() => {
        this.$refs.publicDialogForm.init();
      });
    },
    getEmployee() {
      empApi.getEmployee().then((resp) => {
        if (resp.code === 200) {
          this.userOptions = resp.data;
        }
      });
    },
    // 批量修改
    handleBatChUpdate() {
      this.options = {
        userOptions: this.userOptions
      };
      this.$nextTick(() => {
        this.$refs.batchUpdateDialogForm.init({
          clueIds: this.ids
        });
      });
    },
    // 登记成交
    async handleSign(item) {
      // 根据clueId查询登记信息
      let signInfo = {};
      this.clueInfo = item;
      const resp = await getSign({ clueId: item.clueId });
      if (resp.code == 200) {
        signInfo = { ...resp.data };
      }
      this.$nextTick(() => {
        this.$refs.signDialogForm.init(signInfo);
      });
    },
    //分发到场地
    handleDistribute(item) {

      this.$nextTick(() => {
        this.$refs.distributeDialogForm.init(item.clueId);
      });
    },
    //外呼
    handlePhone(item) {

    },
    handleViewZhuangDan(item) {
      this.$nextTick(() => {
        this.$refs.zhuangDanDialog.init(item.clueId);
      });
    },
    handleRowClick(row) {
      if (this.quickSearch != 8) {
        this.handleAddandUpdate(row)
      }
    },
    handleCellClick(row, column, cell, event) {
      //如果点击的是备注的话 开始备注编辑框
      if (column.property == 'clueMemo') {
        console.log(row, column, cell, event)
        this.$nextTick(() => {
          this.$refs.memoDialog.init(row);
        });

      }
    }
  }
};
</script>

<style lang="scss" scoped></style>
