<template>
  <div class="app-container">
    <div class="title-container">
      <breadcrumb id="breadcrumb-container" class="breadcrumb-container" />
    </div>

    <y-page-list-layout :page-list="pageData" :page-para="listQuery" :get-page-list="getList">
      <template slot="left">
        <PermissionButton menu-code="_views_market_customer_add" class-name="filter-item" type="primary" name size="mini"
          :page-jump="true" round style="float: left" />
        <el-input v-model="listQuery.name" placeholder="客户名字" clearable
          style="margin-left: 20px;width: 320px;float: left;">
        </el-input>
        <el-select clearable style="margin-left: 20px;width: 200px;float: left;" v-model="listQuery.level"
          placeholder="客户等级">
          <el-option v-for="(item, index) in AllEnum['客户等级']" :key="index" :label="item" :value="item" />
        </el-select>
        <el-button class="filter-item" style="margin-left: 10px;float: left;" type="primary" @click="searchList" round>搜索
        </el-button>
        <el-button class="filter-item" style="float: left;" round type="warning" @click="resetSearch()">重置
        </el-button>
      </template>
      <template slot="right">
        <PermissionButton menu-code="_views_customer_template" class-name="filter-item" round icon="el-icon-download"
          name="下载模板" @click="handleDownload" />
        <PermissionButton menu-code="_views_customer_import" class-name="filter-item" round type="text" name=""
          style="padding: 0; margin-bottom: 10px">
          <excelImport ref="uploadControl" flag="customer/importExcel" :style-type="1" title="导入" @fath="getList" />
        </PermissionButton>
        <PermissionButton menu-code="_views_customer_export" class-name="filter-item" round type="primary" name="导出"
          @click="customerExport">
        </PermissionButton>
      </template>
      <parentTable v-loading="listLoading" :data="pageData.records" slot="table" style="width: 100%;">
        <el-table-column label="客户名字" align="center" width="120">
          <template slot-scope="{row}">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="市/州" align="center" width="150">
          <template slot-scope="{row}">
            <span>{{ row.firstCity }}</span>
          </template>
        </el-table-column>
        <el-table-column label="区/县" align="center" width="120">
          <template slot-scope="{row}">
            <span>{{ row.secCity }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" width="300">
          <template slot-scope="{row}">
            <span>{{ row.department }}</span>
          </template>
        </el-table-column>
        <el-table-column label="职位" align="center" width="120">
          <template slot-scope="{row}">
            <span>{{ row.position }}</span>
          </template>
        </el-table-column>
        <el-table-column label="科室" align="center" width="120">
          <template slot-scope="{row}">
            <span>{{ row.section }}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系电话" align="center" width="120">
          <template slot-scope="{row}">
            <span>{{ row.mobile }}</span>
          </template>
        </el-table-column>
        <el-table-column label="微信号" align="center" width="120">
          <template slot-scope="{row}">
            <span>{{ row.wechatNo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="QQ号" align="center" width="120">
          <template slot-scope="{row}">
            <span>{{ row.qq }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户等级" align="center" width="120">
          <template slot-scope="{row}">
            <span v-if="row.level === '重点客户'" style="color: red">{{ row.level }}</span>
            <span v-if="row.level === '普通客户'" style="color: sandybrown">{{ row.level }}</span>
            <span v-if="row.level === '一般客户'" style="color: green">{{ row.level }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户地址" align="center" width="200">
          <template slot-scope="{row}">
            <span>{{ row.address }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户经理" align="center" width="120">
          <template slot-scope="{row}">
            <span>{{ row.userName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300" fixed="right">
          <template slot-scope="{row}">
            <PermissionButton menu-code="_views_market_customer_detail" class-name="filter-item" name="" type="primary"
              :page-jump="true" :page-query="{ id: row.id, listQuery: listQuery }" round size="mini" />
            <PermissionButton menu-code="_views_market_customer_remove" class-name="filter-item" name="" type="danger"
              round size="mini" @click="deleteInfo(row.id)" />
            <PermissionButton menu-code="_views_customer_transfer" class-name="filter-item" name="" type="success" round
              size="mini" @click="openTransferDialog(row)" />
          </template>
        </el-table-column>
      </parentTable>
    </y-page-list-layout>
    <el-dialog :visible.sync="dialogFormVisible" :close-on-click-modal="false" custom-class="tansferDialog">
      <div class="detail">
        <el-divider content-position="left">项目信息</el-divider>
        <el-descriptions :column="4" size="lager" border>
          <el-descriptions-item label="客户名字">{{ detail.name }}</el-descriptions-item>
          <el-descriptions-item label="市/州">{{ detail.firstCity }}</el-descriptions-item>
          <el-descriptions-item label="区/县">{{ detail.secCity }}</el-descriptions-item>
          <el-descriptions-item label="单位">{{ detail.department }}</el-descriptions-item>
          <el-descriptions-item label="职位">{{ detail.position }}</el-descriptions-item>
          <el-descriptions-item label="科室">{{ detail.section }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ detail.mobile }}</el-descriptions-item>
          <el-descriptions-item label="微信号">{{ detail.wechatNo }}</el-descriptions-item>
          <el-descriptions-item label="QQ号">{{ detail.qq }}</el-descriptions-item>
          <el-descriptions-item label="客户经理">
            <el-select v-model="detail.userId">
              <el-option v-for="(item, index) in managers" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-tooltip class="item" effect="dark" content="点击转交" placement="bottom-start">
              <el-button type="success" icon="el-icon-check" circle style="margin-left: 20px;" placeholder="转交"
                @click="saveManager"></el-button>
            </el-tooltip>
          </el-descriptions-item>
          <el-descriptions-item label="客户等级">{{ detail.level }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="histroy">
        <el-divider content-position="left">转交记录</el-divider>
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <el-timeline>
              <el-timeline-item v-for="item in historys" :key="item.id" :timestamp="item.created" placement="top">
                <el-card>
                  <el-descriptions :column="3" border>
                    <el-descriptions-item label="前客户经理"><el-tag type="info">{{ item.originalUserName
                    }}</el-tag></el-descriptions-item>
                    <el-descriptions-item label="后客户经理"><el-tag type="success">{{ item.currentUserName
                    }}</el-tag></el-descriptions-item>
                    <el-descriptions-item label="操作人"><el-tag>{{ item.operatorName }}</el-tag></el-descriptions-item>
                  </el-descriptions>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import YPageListLayout from '@/components/YPageListLayout'
import Breadcrumb from '@/components/Breadcrumb'
import PermissionButton from '@/components/PermissionButton/PermissionButton'

export default {
  name: 'ViewsMarketCustomerList',
  components: {
    Breadcrumb,
    YPageListLayout,
    PermissionButton,
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger',
      }
      return statusMap[status]
    },
  },
  data() {
    return {
      isDisable: false,
      tableKey: 0,
      pageData: { records: [] },
      total: 20,
      listLoading: true,
      listQuery: {
        page: 1,
        size: 10,
        descs: 'id',
      },
      listQueryKey: 'keyword',
      importLoading: false,
      name: null,
      city: null,
      county: null,
      AllEnum: [],
      dialogFormVisible: false,
      detail: {},
      activeNames: ['1'],
      historys: [],
      managers: [],
    }
  },
  created() {
    const that = this;
    if (that.$route.query.current && !isNaN(that.$route.query.current)) {
      that.listQuery.current = parseInt(that.$route.query.current);
    }
    if (that.$route.query.name) {
      that.listQuery.name = that.$route.query.name;
    }
    if (that.$route.query.level) {
      that.listQuery.level = that.$route.query.level;
    }
    that.getAllEnum();
    that.getList();
  },
  methods: {
    customerExport() {
      this.$utils.exportUtil(
        "/customer/export", this.listQuery,
        "导出"
      );
    },
    handleDownload() {
      this.$utils.exportUtil('/customer/download/importTemplate', {}, '模板下载')
    },
    getAllEnum() {
      const that = this;
      that.$api.globalConfig.getAllEnum().then(data => {
        if (data.code === 200) {
          that.AllEnum = data.data
        } else {
          this.$message({
            type: 'error',
            message: data.msg
          })
        }
      })
    },
    resetSearch() {
      this.$router.push({ query: {} });
      this.listQuery = {
        current: 1,
        size: 10,
        descs: 'id',
      }
      this.getList()
    },
    removeHandle(row) {
      // console.log(data)
      const that = this
      that
        .$confirm('确认删除当前记录吗?', '警告', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(async () => {
          this.$api.customer.delete(row.id).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功',
              })
              this.getList()
            }
          })
        })
        .catch((err) => {
          console.error(err)
        })
    },
    searchList() {
      // 重置分页
      this.listQuery.page = 1
      this.listQuery.size = 10
      this.getList()
    },
    getList() {
      const that = this
      this.listLoading = true
      // console.log(that.listQuery)
      const key = {}
      key[this.listQueryKey] = this.listQuery.description
      this.$api.customer
        .list(Object.assign({}, that.listQuery, key))
        .then((res) => {
          that.pageData = res.data
          setTimeout(() => {
            that.listLoading = false
          }, 200)
        })
        .catch(() => {
          that.listLoading = false
        })
    },
    deleteInfo(id) {
      const that = this
      that.$confirm('请确认是否删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        that.$api.customer.delete(id).then(data => {
          that.loading = false
          if (data.code === 200) {
            that.getList()
          } else {
            this.$message({
              type: 'error',
              message: data.msg
            })
          }
        })
      }).catch(() => {
      })
    },
    openTransferDialog(row) {
      const originalUserId = row.userId;
      this.dialogFormVisible = true;
      this.detail = row;
      this.detail.originalUserId = originalUserId;
      this.getHistroyList(row.id);
      this.getManagers();
    },
    getManagers() {
      this.$api.user.usersByDepartment("市场部").then(res => {
        this.managers = res.data
      })
    },
    getHistroyList(id) {
      this.$api.resourceTransfer.history({ "resourceType": "CUSTOMER", "resourceId": id }).then(res => {
        if (res.code === 200) {
          this.historys = res.data;
        }
      })
    },
    saveManager() {
      if (this.detail.userId === this.detail.originalUserId){
        this.$message({
            type: 'error',
            message: '抱歉，不能转交给本人。'
          });
          return ;
      }
      this.$api.customer.changeManager(this.detail).then(res => {
        if (res.code === 200 && res.data === true) {
          this.$message({
            type: 'success',
            message: '转交成功'
          });
          this.getHistroyList(this.detail.id);
        }
      }
      );
    },
  },

}
</script>
<style lang="scss" scoped>
.right {
  flex: 1;

  .title {
    font-size: 16px;
    font-weight: 500;
    color: rgba(51, 51, 51, 1);
    line-height: 35px;
    margin-bottom: 8px;
  }

  .menu-2-box {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }

  .menu-2-item {
    display: flex;
    align-items: center;
    color: #656565;
    font-size: 12px;
    width: 230px;
    height: 101px;
    background: rgb(255, 185, 129);
    border-radius: 3px;
    padding-left: 20px;
    margin-right: 10px;
    margin-bottom: 10px;
    cursor: pointer;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);

    .text {
      margin-left: 16px;
    }
  }
}

/deep/ .tansferDialog {
  width: 60%;
  border-radius: 10px;
}

.el-dropdown-link {
  cursor: pointer;
  color: red;
}

.el-icon-arrow-down {
  font-size: 12px;
}
</style>
