<!--
 * @Author: wanglj 471442253@qq.com
 * @Date: 2022-12-26 16:34:37
 * @LastEditors: wanglj
 * @LastEditTime: 2023-01-05 13:39:44
 * @Description: file content
 * @FilePath: \opms_frontend\src\views\customer\list.vue
-->
<template>
  <div class="list-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="全部客户" name="first" />
      <el-tab-pane label="我的客户" name="second" />
      <el-tab-pane label="下属的客户" name="third" />
    </el-tabs>
    <el-row :gutter="10" style="margin-bottom: 10px">
      <el-col :span="4">
        <el-input v-model="queryForm.custCode" placeholder="客户编码" />
      </el-col>
      <el-col :span="4">
        <el-input v-model="queryForm.custName" placeholder="客户名称" />
      </el-col>
      <el-col :span="4">
        <el-select v-model="queryForm.custIndustry" placeholder="客户行业" style="width: 100%">
          <el-option v-for="item in industryOptions" :key="item.value" :label="item.value" :value="item.value" />
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-select v-model="queryForm.custLevel" placeholder="客户级别" style="width: 100%">
          <el-option v-for="item in levelOptions" :key="item.value" :label="item.value" :value="item.value" />
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-date-picker
          v-model="queryForm.followUpDate"
          placeholder="最后跟进时间"
          style="width: 100%"
          type="date"
          value-format="yyyy-MM-dd" />
      </el-col>
      <el-col :span="4">
        <el-button icon="el-icon-plus" type="primary" @click="fetchData">查询</el-button>
        <el-button icon="el-icon-refresh-right" @click="reset">重置</el-button>
      </el-col>
    </el-row>
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <el-button icon="el-icon-plus" size="mini" type="primary" @click="$refs.edit.init()">新建</el-button>
        <el-button icon="el-icon-plus" size="mini" type="primary" @click="handleShift">转移客户</el-button>
        <el-button icon="el-icon-plus" size="mini" type="primary" @click="handleToOpen">移入公海</el-button>
        <el-button icon="el-icon-plus" size="mini" type="primary" @click="handleMerge">合并客户</el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <el-button icon="el-icon-download" />
        <table-tool :check-list.sync="checkList" :columns="columns" />
      </vab-query-form-right-panel>
    </vab-query-form>
    <el-table
      v-loading="listLoading"
      border
      :data="list"
      height="calc(100vh - 394px)"
      @selection-change="setSelectRows">
      <el-table-column align="center" show-overflow-tooltip type="selection" />

      <el-table-column align="center" label="客户编码" prop="custCode" />
      <el-table-column align="center" label="客户名称" prop="custName" />
      <el-table-column align="center" label="助记名" prop="abbrName" />
      <el-table-column align="center" label="所在地区" prop="custLocation" />

      <el-table-column align="center" label="客户行业" prop="custIndustry" />

      <el-table-column align="center" label="客户级别" prop="custLevel" />
      <el-table-column align="center" label="客户状态" prop="custStatus">
        <template slot-scope="scope">
          {{ scope.row.custStatus == 10 ? '正常' : '异常' }}
        </template>
      </el-table-column>

      <el-table-column
        v-for="(item, index) in finallyColumns"
        :key="index"
        align="center"
        :label="item.label"
        :min-width="item.width"
        :prop="item.prop"
        show-overflow-tooltip
        :sortable="item.sortable">
        <template #default="{ row }">
          <el-button v-if="item.prop === 'custName'" class="link-button" type="text" @click="handleDetail(row)">
            {{ row.custName }}
          </el-button>
          <span v-else-if="item.prop === 'custStatus'">
            {{ row.custStatus == 10 ? '正常' : '异常' }}
          </span>
          <span v-else>{{ row[item.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange" />
    <!-- 新增编辑客户弹窗 -->
    <Edit ref="edit" @createContact="createContact" @customerSave="fetchData" />
    <!-- 新建联系人弹窗 -->
    <Contact ref="contact" />
    <!-- 转移客户 -->
    <Shift ref="shift" @refresh="fetchData" />
    <!-- 移入公海 -->
    <ToOpen ref="toOpen" @refresh="fetchData" />
    <!-- 合并客户 -->
    <Merge ref="merge" @refresh="fetchData" />
  </div>
</template>

<script>
  import to from 'await-to-js'
  import api from '@/api/customer'
  import Edit from './components/Edit'
  import Contact from './components/Contact'
  import Shift from './components/Shift'
  import ToOpen from './components/ToOpen'
  import Merge from './components/Merge'
  import TableTool from '@/components/table/TableTool'

  export default {
    components: {
      Edit,
      Contact,
      Shift,
      ToOpen,
      Merge,
      TableTool,
    },
    data() {
      return {
        activeName: 'first',
        layout: 'total, sizes, prev, pager, next, jumper',
        queryForm: {
          custCode: '',
          custName: '',
          indusTry: '',
          pageNum: 1,
          pageSize: 10,
        },
        total: 0,
        listLoading: false,
        list: [],
        selectRows: [],
        industryOptions: [], //客户行业
        levelOptions: [], //客户级别
        // 自定义列表
        checkList: [],
        columns: [
          {
            label: '客户编码',
            width: '120px',
            prop: 'custCode',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '客户名称',
            width: '120px',
            prop: 'custName',
            sortable: false,
            disableCheck: true,
          },
          {
            label: '助记名',
            width: 'auto',
            prop: 'abbrName',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '所在地区',
            width: 'auto',
            prop: 'custLocation',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '客户行业',
            width: 'auto',
            prop: 'custIndustry',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '客户级别',
            width: 'auto',
            prop: 'custLevel',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '客户状态',
            width: 'auto',
            prop: 'custStatus',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '最后跟进时间',
            width: '140px',
            prop: 'followUpDate',
            sortable: false,
            disableCheck: false,
          },
          {
            label: '创建时间',
            width: '140px',
            prop: 'createdTime',
            sortable: false,
            disableCheck: false,
          },
        ],
      }
    },
    computed: {
      finallyColumns() {
        return this.columns.filter((item) => this.checkList.includes(item.label))
      },
    },
    mounted() {
      this.getOptions()
      this.fetchData()
    },
    methods: {
      getOptions() {
        Promise.all([this.getDicts('CustomerLevel'), this.getDicts('CustomerIndustry')])
          .then(([level, industry]) => {
            this.levelOptions = level.data.values || []
            this.industryOptions = industry.data.values || []
          })
          .catch((err) => console.log(err))
      },
      handleClick(tab) {
        console.log(tab, 'tab')
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const params = { ...this.queryForm }
        const [err, res] = await to(api.getList(params))
        if (err) return (this.listLoading = false)
        this.list = res.data.list || []
        this.total = res.data.total
        this.listLoading = false
      },
      reset() {
        this.queryForm = {
          pageNum: 1,
          pageSize: 10,
          custCode: '', // 客户编码
          custName: '', //客户名称
          indusTry: '', // 客户行业  ()
        }
        this.fetchData()
      },
      // 客户编辑
      handleEdit(row) {
        this.$refs.edit.init([row.id])
      },
      // 联系人弹窗
      async createContact(res) {
        this.$refs.contact.contactForm.custId = res.id
        this.$refs.contact.contactForm.custName = res.name
        this.$refs.contact.contactVisible = true
      },
      // 客户详情
      handleDetail(row) {
        this.$router.push({
          path: '/customer/detail',
          query: {
            id: row.id,
            privateCus: 1,
          },
        })
      },
      // 客户删除
      handleDelete(row) {
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            const [err, res] = await to(api.deleteCustomer({ Id: row.id }))
            if (err) return
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功!',
              })
            }
          })
          .catch(() => {})
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      // 转移客户
      handleShift() {
        if (!this.selectRows.length) return this.$message.warning('请选择需要转移的客户')
        this.$refs.shift.form.Ids = this.selectRows.map((item) => item.id)
        this.$refs.shift.visible = true
      },
      // 移入公海
      handleToOpen() {
        if (!this.selectRows.length) return this.$message.warning('请选择要移入公海的客户')
        this.$refs.toOpen.form.ids = this.selectRows.map((item) => item.id)
        this.$refs.toOpen.visible = true
      },
      async handleMerge() {
        if (this.selectRows.length < 2) return this.$message.warning('请选择两个以上客户进行合并')
        const ids = this.selectRows.map((item) => item.id)
        const [err, res] = await to(api.getDetail({ ids }))
        if (err) return
        this.$refs.merge.init(res, ids)
      },
    },
  }
</script>

<style lang="scss" scoped>
  $base: '.list';
  .link-button {
    font-size: 14px;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
