<!--
 * @Author: wanglj 471442253@qq.com
 * @Date: 2022-12-26 09:30:47
 * @LastEditors: wanglj
 * @LastEditTime: 2023-01-05 11:50:51
 * @Description: file content
 * @FilePath: \opms_frontend\src\views\customer\detail.vue
-->
<template>
  <div class="detail">
    <el-row :gutter="10">
      <el-col :span="16">
        <div class="title">
          <p>客户</p>
          <h3>
            {{ detail.custName }}
            <span>
              <template v-if="privateCus == 1">
                <el-button @click="handleShift">转移客户</el-button>
                <el-button @click="handleToOpen">移入公海</el-button>
                <el-button>创建项目</el-button>
              </template>
              <template v-else>
                <el-button @click="handleReceive">领取客户</el-button>
                <el-button @click="handleAllocate">分配客户</el-button>
              </template>
            </span>
          </h3>
        </div>
        <header>
          <el-descriptions :colon="false" :column="6" direction="vertical">
            <el-descriptions-item content-class-name="my-content" label="客户编码" label-class-name="my-label">
              {{ detail.custCode }}
            </el-descriptions-item>
            <el-descriptions-item content-class-name="my-content" label="助记名" label-class-name="my-label">
              {{ detail.abbrName }}
            </el-descriptions-item>
            <el-descriptions-item content-class-name="my-content" label="客户级别" label-class-name="my-label">
              {{ detail.custLevel }}
            </el-descriptions-item>
            <el-descriptions-item content-class-name="my-content" label="客户行业" label-class-name="my-label">
              {{ detail.custIndustry }}
            </el-descriptions-item>
            <el-descriptions-item content-class-name="my-content" label="客户状态" label-class-name="my-label">
              {{ detail.custStatus == 10 ? '正常' : '异常' }}
            </el-descriptions-item>
            <el-descriptions-item content-class-name="my-content" label="最后跟进时间" label-class-name="my-label">
              {{ detail.followUpDate }}
            </el-descriptions-item>
          </el-descriptions>
        </header>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="跟进记录" name="follow">
            <ul v-if="followList.length" class="follow">
              <li v-for="(date, index) in followList" :key="index">
                <div class="date">
                  <h2>{{ date.followDay.split('-')[2] }}</h2>
                  <h3>
                    {{ date.followDay.split('-').splice(0, 2).join('.') }}
                  </h3>
                </div>
                <ul class="content">
                  <li v-for="(item, idx) in date.followupList" :key="idx">
                    <!-- <el-avatar class="user-avatar"
              :src="avatar" />-->
                    <div class="text-container">
                      <vab-icon class="user-avatar" icon="account-circle-fill" />
                      <div class="text">
                        <p class="action">
                          <span>{{ item.contactsName }} 跟进（{{ formatType(item.followType) }}）</span>
                          <span>
                            <vab-icon icon="time-line" />
                            {{ item.followDate }}
                          </span>
                        </p>
                        <p>{{ item.followContent }}</p>
                        <div class="footer">
                          <p>
                            来自客户：
                            <span>{{ item.custName }}</span>
                          </p>
                          <div>
                            <el-button size="mini" @click="showDetail(item)">
                              <vab-icon icon="arrow-right-circle-fill" />
                              详情
                            </el-button>
                            <el-button size="mini" @click="showComment(item)">评论({{ item.commentNumber }})</el-button>
                          </div>
                        </div>
                      </div>
                    </div>
                    <transition name="height">
                      <ul v-if="item.showComment" class="comments">
                        <li v-for="comment in item.comments" :key="comment.id">
                          <vab-icon class="user-avatar" icon="account-circle-fill" />
                          <div class="text">
                            <p>{{ comment.createdName }}</p>
                            <p>{{ comment.content }}</p>
                            <p>{{ comment.createdTime }}</p>
                          </div>
                        </li>
                      </ul>
                    </transition>
                  </li>
                </ul>
              </li>
            </ul>
            <div v-else class="no-follow">暂无跟进记录</div>
          </el-tab-pane>
          <el-tab-pane label="详细信息" name="detail">
            <el-descriptions border :column="2" size="medium">
              <el-descriptions-item label="客户级别">
                {{ detail.custLevel }}
              </el-descriptions-item>
              <el-descriptions-item label="下次联系时间">
                {{ detail.followUpDate }}
              </el-descriptions-item>
              <el-descriptions-item label="所在地区">
                {{ detail.custLocation }}
              </el-descriptions-item>
              <el-descriptions-item label="详细地址">
                {{ detail.custAddress }}
              </el-descriptions-item>
              <el-descriptions-item label="创建人">
                {{ detail.createdName }}
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                {{ detail.createdTime }}
              </el-descriptions-item>
              <el-descriptions-item label="跟进次数">
                {{ abstract.followContent }}
              </el-descriptions-item>
              <el-descriptions-item label="未跟进时长">
                {{ abstract.notFollowDay }}
              </el-descriptions-item>
              <el-descriptions-item label="商机数量">
                {{ abstract.business }}
              </el-descriptions-item>
              <el-descriptions-item label="商机总额">
                {{ formatPrice(abstract.businessTotal) }}
              </el-descriptions-item>
              <el-descriptions-item label="成交次数">
                {{ abstract.dealCotal }}
              </el-descriptions-item>
              <el-descriptions-item label="成交总额">
                {{ formatPrice(abstract.dealTotal) }}
              </el-descriptions-item>
              <el-descriptions-item label="回款总额">
                {{ formatPrice(abstract.paymentTotal) }}
              </el-descriptions-item>
              <el-descriptions-item label="未回款总额">
                {{ formatPrice(abstract.notPaymentTotal) }}
              </el-descriptions-item>
              <el-descriptions-item label="开票总额" :span="24">
                {{ formatPrice(abstract.drawTotal) }}
              </el-descriptions-item>
              <el-descriptions-item label="备注" :span="24">
                {{ detail.remark }}
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="联系人" name="contact">
            <vab-query-form>
              <vab-query-form-left-panel :span="12">
                <el-input placeholder="请输入单据名称/编号" prefix-icon="el-icon-search" style="width: 50%" />
              </vab-query-form-left-panel>
              <vab-query-form-right-panel :span="12">
                <el-button icon="el-icon-plus" @click="addContact">新建联系人</el-button>
              </vab-query-form-right-panel>
            </vab-query-form>
            <el-table
              v-loading="listLoading"
              border
              :data="contactList"
              height="calc(100% - 42px)"
              @selection-change="setSelectRows">
              <el-table-column align="center" type="selection" />
              <el-table-column align="center" label="姓名" prop="cuctName" />
              <el-table-column align="center" label="岗位" prop="postion" />
              <el-table-column align="center" label="电话" prop="telephone" />
              <el-table-column align="center" label="微信" prop="wechat" />
              <el-table-column align="center" label="邮箱" prop="email" />
              <el-table-column align="center" label="是否决策人">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.policy" :active-value="1" disabled :inactive-value="0" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                  <el-button type="text" @click="contactEdit(scope.row)">编辑</el-button>
                  <el-button type="text" @click="contactDel(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="项目记录" name="item">项目记录</el-tab-pane>
          <el-tab-pane label="合同记录" name="contract">合同记录</el-tab-pane>
          <el-tab-pane label="工单记录" name="worksheet">工单记录</el-tab-pane>
          <el-tab-pane label="归属记录" name="belong">
            <el-table v-loading="listLoading" border :data="belongs" height="calc(100% - 42px)">
              <el-table-column align="center" label="归属销售" prop="saleName" />
              <el-table-column align="center" label="原来归属" prop="origSaleName" />
              <el-table-column align="center" label="操作方式" prop="opnType">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.opnType == 10">分配</el-tag>
                  <el-tag v-else-if="scope.row.opnType == 20">转移</el-tag>
                  <el-tag v-else-if="scope.row.opnType == 30">领取</el-tag>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作人" prop="createdName" />
              <el-table-column align="center" label="操作时间" min-width="160px" prop="opnDatetime" />
              <el-table-column align="center" label="备注" prop="remark" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col :span="8">
        <div class="buttons">
          <el-button type="primary" @click="handleEdit">编辑</el-button>
          <el-button @click="handleDelete">删除</el-button>
        </div>
        <ul class="records">
          <li v-for="(value, key) in records" :key="key">
            <div class="date">
              <h2>{{ key.split('-')[2] }}</h2>
              <h3>{{ key.split('-').splice(0, 2).join('.') }}</h3>
            </div>
            <ul class="content">
              <li v-for="(item, index) in records[key]" :key="index">
                <!-- <el-avatar class="user-avatar"
                           :src="avatar" /> -->
                <vab-icon class="user-avatar" icon="account-circle-fill" />
                <div class="text">
                  <p class="action">{{ item.opnPeople }} {{ item.opnType }}</p>
                  <p>{{ item.opnDate }}</p>
                  <p v-if="item.opnContent.custName">
                    客户名称：
                    <span>{{ item.opnContent.custName }}</span>
                  </p>
                  <template v-else-if="item.opnContent.cuctName">
                    <p>
                      联系人名称：
                      <span>{{ item.opnContent.cuctName }}</span>
                    </p>
                    <p>职务：{{ item.opnContent.postion }}</p>
                    <p>手机：{{ item.opnContent.telephone }}</p>
                  </template>
                </div>
              </li>
            </ul>
          </li>
        </ul>
      </el-col>
    </el-row>
    <Contact ref="contact" @contactSave="contactSave" />
    <Edit ref="edit" @customerSave="customerSave" />
    <!-- 分配客户 -->
    <Allocate ref="allocate" @refresh="back" />
    <!-- 转移客户 -->
    <Shift ref="shift" @refresh="back" />
    <!-- 移入公海 -->
    <ToOpen ref="toOpen" @refresh="backToOpen" />
    <!-- 跟进详情 -->
    <FollowDetail ref="followDetail" />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import api from '@/api/customer'
  import follow from '@/api/customer/follow'
  import to from 'await-to-js'
  import Contact from './components/Contact'
  import Edit from './components/Edit'
  import Allocate from './components/Allocate'
  import Shift from './components/Shift'
  import ToOpen from './components/ToOpen'
  import FollowDetail from './components/FollowDetail.vue'
  export default {
    name: 'CustomerDetail',
    components: {
      Edit,
      Contact,
      Allocate,
      Shift,
      ToOpen,
      FollowDetail,
    },
    data() {
      return {
        id: '',
        privateCus: '',
        detail: {
          custCode: '', //客户编码
          abbrName: '', //助记名
          level: '', //客户级别
          indusTry: '', //客户行业
          custStatus: '', //客户状态
          followUpDate: '', //最后跟进时间
        },
        abstract: {
          followContent: '', //跟进次数
          notFollowDay: '', //未跟进天数
          business: '', //商机数量
          businessTotal: '', //商机总额
          dealCotal: '', //成交次数
          dealTotal: '', //成交总额
          paymentTotal: '', //回款总额
          notPaymentTotal: '', //未回款总额
          drawTotal: '', //开票总额
        },
        activeName: 'follow',
        listLoading: false,
        contactList: [],
        selectRows: [],
        records: [], //操作记录
        followList: [], //跟进记录
        belongs: [],
      }
    },
    computed: {
      ...mapGetters({
        avatar: 'user/avatar',
        username: 'user/username',
      }),
    },
    mounted() {
      this.id = this.$route.query.id
      this.privateCus = this.$route.query.privateCus
      this.init()
      this.getDynamics()
      this.handleClick({ name: 'follow' })
    },
    methods: {
      async init() {
        Promise.all([api.getDetail({ ids: [parseInt(this.id)] }), api.getAbstract({ id: parseInt(this.id) })]).then(
          ([detail, abstract]) => {
            if (detail.data.list[0]) this.detail = detail.data.list[0]
            if (abstract.data.list) this.abstract = abstract.data.list
          }
        )
      },
      async getDynamics() {
        const [err, res] = await to(api.dynamicsList({ custId: parseInt(this.id) }))
        if (err) return
        if (res.data.list[0]) {
          let obj = res.data.list[0]
          const keys = Object.keys(obj).reverse()
          let records = {}
          for (const item of keys) {
            records[item] = obj[item]
          }
          this.records = records
        }
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      async handleClick(tab) {
        let err, res
        if (tab.name == 'contact') {
          ;[err, res] = await to(api.getContact({ custId: parseInt(this.id) }))
          if (err) return
          this.contactList = res.data.list || []
        } else if (tab.name == 'follow') {
          let params = {
            custId: this.id,
            DaysBeforeToday: 9999,
          }
          ;[err, res] = await to(follow.getListByDay(params))
          if (err) return
          this.followList = res.data.list || []
        } else if (tab.name == 'belong' && this.belongs.length == 0) {
          ;[err, res] = await to(api.getBelongs({ custId: parseInt(this.id) }))
          if (err) return
          this.belongs = res.data.list || []
        }
      },
      // 添加联系人
      addContact() {
        this.$refs.contact.contactForm.custId = this.detail.id
        this.$refs.contact.contactForm.custName = this.detail.custName
        this.$refs.contact.contactVisible = true
      },
      // 保存联系人
      contactSave() {
        this.handleClick({ name: 'contact' })
        this.getDynamics()
      },
      // 编辑客户
      handleEdit() {
        this.$refs.edit.title = '编辑客户'
        this.$refs.edit.editForm = { ...this.detail }
        this.$refs.edit.editVisible = true
        this.$refs.edit.showLocation()
      },
      // 编辑联系人
      contactEdit(row) {
        this.$refs.contact.contactForm = { ...row }
        this.$refs.contact.contactVisible = true
      },
      // 删除联系人
      contactDel(row) {
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            const [err, res] = await to(api.deleteContact({ Id: row.id, custId: parseInt(this.id) }))
            if (err) return
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功!',
              })
              this.contactSave()
            }
          })
          .catch(() => {})
      },
      // 转移客户
      handleShift() {
        this.$refs.shift.form.Ids = [parseInt(this.id)]
        this.$refs.shift.visible = true
      },
      // 移入公海
      handleToOpen() {
        this.$refs.toOpen.form.ids = [parseInt(this.id)]
        this.$refs.toOpen.visible = true
      },
      // 客户删除
      handleDelete() {
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            const [err, res] = await to(api.deleteCustomer({ Id: parseInt(this.id) }))
            if (err) return
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功!',
              })
              this.$router.go(-1)
            }
          })
          .catch(() => {})
      },
      backToOpen() {
        this.$router.push('/customer/openSea')
      },
      back() {
        this.$router.go(-1)
      },
      // 领取
      handleReceive() {
        this.$confirm('确认领取客户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            const [err, res] = await to(
              api.receiveCustomer({
                ids: [parseInt(this.id)],
                salesId: this.$store.state.user.id,
                salesName: this.$store.state.user.username,
                receive: '1',
              })
            )
            if (err) return
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '领取成功!',
              })
              this.$router.push('/customer/list')
            }
          })
          .catch(() => {})
      },
      handleAllocate() {
        this.$refs.allocate.ids = [parseInt(this.id)]
        this.$refs.allocate.visible = true
      },
      customerSave() {
        this.init()
        this.getDynamics()
      },
      formatType(val) {
        let str = ''
        if (val == 10) str = '电话'
        else if (val == 20) str = '邮件'
        else if (val == 30) str = '拜访'
        return str
      },
      // 跟进记录详情
      showDetail(row) {
        this.$refs.followDetail.init({ ...row })
      },
      // 展开评论
      showComment(row) {
        if (!row.comments.length) return this.$message.warning('暂无评论')
        row.showComment = !row.showComment
        this.$forceUpdate()
      },
    },
  }
</script>

<style lang="scss" scoped>
  $base: '.detail';
  #{$base} {
    height: calc(100vh - 60px - 50px - 12px * 2 - 40px);
    display: flex;
    padding: 20px 40px;
    > .el-row {
      flex: 1;
      > .el-col {
        height: 100%;
      }
    }
    .title {
      p,
      h3 {
        margin: 0;
      }
      p {
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
      }
      h3 {
        font-size: 24px;
        font-weight: 500;
        line-height: 36px;
        color: #333;
        display: flex;
        justify-content: space-between;
      }
    }
    header {
      height: 74px;
      background: rgba(196, 196, 196, 0.5);
      border-radius: 4px;
      display: flex;
      align-items: center;
      padding: 0 20px;
      margin-top: 16px;
      ::v-deep .el-descriptions__body {
        background: transparent;
      }
      ::v-deep .my-label {
        font-size: 14px;
        font-weight: 600;
        color: #1d66dc;
      }
      ::v-deep .my-content {
        font-size: 14px;
        font-weight: 600;
        color: #333;
      }
    }
    .el-tabs {
      height: calc(100% - 148px);
      display: flex;
      flex-direction: column;
      ::v-deep .el-tabs__content {
        flex: 1;
        .el-tab-pane {
          height: 100%;
        }
      }
    }
    .buttons {
      padding-top: 28px;
      text-align: right;
    }
    .records {
      margin: 0;
      padding: 10px 20px;
      list-style: none;
      height: calc(100% - 60px);
      overflow-y: auto;
      > li {
        display: flex;
        & + li {
          margin-top: 10px;
        }
      }
      .date {
        width: 100px;
        display: flex;
        flex-direction: column;
        align-items: center;
        h2,
        h3 {
          margin: 0;
        }
        h2 {
          font-size: 26px;
          line-height: 32px;
        }
      }
      .content {
        flex: 1;
        list-style: none;
        li {
          display: flex;
          & + li {
            margin-top: 10px;
          }
        }
        .user-avatar {
          font-size: 40px;
        }
        .text {
          flex: 1;
          padding-left: 20px;
          p {
            font-weight: 500;
            margin: 0;
            line-height: 20px;
            span {
              color: #1d66dc;
            }
          }
          p:nth-child(2) {
            margin-bottom: 10px;
          }
          .action {
            font-weight: bold;
            color: #333;
          }
        }
      }
    }
    .follow {
      height: 100%;
      padding: 10px 20px;
      overflow: auto;
      > li {
        display: flex;
        + li {
          margin-top: 10px;
        }
      }
      .date {
        width: 100px;
        display: flex;
        flex-direction: column;
        align-items: center;
        h2,
        h3 {
          margin: 0;
        }
        h2 {
          font-size: 26px;
          line-height: 32px;
        }
      }
      .content {
        flex: 1;
        list-style: none;
        > li {
          border: 1px solid rgb(215, 232, 244);
          background: rgb(247, 251, 254);
          border-radius: 4px;
          padding: 8px;
          overflow: hidden;

          .text-container {
            display: flex;
          }
          .comments {
            padding-left: 60px;
            margin-top: 10px;
            max-height: 190px;
            overflow: auto;
            li {
              display: flex;
              border-top: 1px solid #e3e5e7;
              .text {
                flex: 1;
                padding: 0 10px;
                p {
                  font-weight: 500;
                  margin: 0;
                  line-height: 32px;
                }
                p:first-child {
                  line-height: 30px;
                  font-weight: bold;
                }
                p:last-child {
                  font-size: 12px;
                  color: #9499a0;
                  text-align: right;
                }
              }
            }
          }
          + li {
            margin-top: 10px;
          }
        }
        .user-avatar {
          font-size: 40px;
        }
        .text {
          flex: 1;
          padding-left: 20px;
          padding-right: 10px;
          p {
            font-weight: 500;
            margin: 0;
            line-height: 32px;
            span {
              color: #1d66dc;
            }
          }
          .action {
            display: flex;
            justify-content: space-between;
            span:first-child {
              font-weight: bold;
              color: #333;
            }
          }
          .footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
          }
        }
      }
    }
    .no-follow {
      height: 100%;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      color: rgba(0, 0, 0, 0.65);
    }
  }
  .height-enter-active,
  .height-leave-active {
    transition: all 0.5s;
  }
  .height-enter-to,
  .height-leave {
    height: 190px;
  }
  .height-enter, .height-leave-to /* .fade-leave-active below version 2.1.8 */ {
    height: 0;
  }
  ::v-deep .el-descriptions__table tbody {
    td,
    th {
      width: 25%;
    }
  }
</style>
