<template>
  <div id="goods">
    <el-row>
      <el-col :span="24" class="main">
        <el-col :span="8" class="left" v-loading="loadings" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
          <left-1 :roomList="roomList" @toView="toView"></left-1>
        </el-col>
        <el-col :span="16" class="non" v-if="show == '0'">
          <el-col :span="24"> <i class="el-icon-chat-line-round"></i></el-col>
        </el-col>
        <el-col :span="16" class="right" v-else>
          <right-1
            :chatRecordList="chatRecordList"
            :customer="customer"
            :shop="shop"
            @toUp="toUp"
            @onSubmit="onSubmit"
            :form="form"
            :srcList="srcList"
          ></right-1>
        </el-col>
      </el-col>
    </el-row>
    <e-dialog :dialog="dialog" @toClose="toClose">
      <template v-slot:info>
        <el-col :span="24" class="dia_one">
          <c-upload :url="url" v-model="file" :limit="1"></c-upload>
          <p>一次最多发送一张图片</p>
        </el-col>
        <el-col :span="24" class="dia_one">
          <el-button type="success" size="mini" @click="onSubmit('file')">发送</el-button>
        </el-col>
      </template>
    </e-dialog>
  </div>
</template>

<script>
const _ = require('lodash');
const moment = require('moment');
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: room } = createNamespacedHelpers('room');
const { mapActions: users } = createNamespacedHelpers('users');
const { mapActions: address } = createNamespacedHelpers('address');
const { mapActions: chatRecord } = createNamespacedHelpers('chatRecord');

export default {
  name: 'index',
  props: {},
  components: {
    cUpload: () => import('@/components/usual/c-upload.vue'),
    left1: () => import('./parts/left-1.vue'),
    right1: () => import('./parts/right-1.vue'),
  },
  data: function () {
    return {
      loadings: false,
      searchName: '',
      searchInfo: {},
      // 聊天房间列表
      roomList: [],
      // 聊天记录
      chatRecordList: [],
      // 用户信息
      customer: {},
      // 店铺信息
      shop: {},
      // 收货地址
      address: {},
      // 弹框
      dialog: { title: '信息管理', show: false, type: '1' },
      url: '/files/point/message/upload',
      file: [],
      // 大图预览列表
      srcList: [],
      form: {},
      // 判断显示聊天记录
      show: '0',
      // 判断显示地址
      add: '0',
    };
  },
  created() {
    this.searchOthers();
    this.search();
    if (this.customer_id) this.searchDetail();
  },
  methods: {
    ...users({ userFetch: 'fetch' }),
    ...address({ addFetch: 'fetch' }),
    ...room({ roomQuery: 'query', roomFetch: 'fetch', roomDelete: 'delete' }),
    ...chatRecord(['query', 'delete', 'fetch', 'update', 'create', 'read']),
    // 查询
    async search() {
      const res = await this.roomQuery({ shop: this.user.shop._id });
      if (this.$checkRes(res)) this.$set(this, `roomList`, res.data);
      this.loadings = false;
    },
    // 订单和售后跳转页面，联系买家
    async searchDetail() {
      let res = await this.roomQuery({ customer: this.customer_id, shop: this.user.shop._id });
      if (this.$checkRes(res)) {
        if (res.total > 0) this.toView(res.data[0]);
        else {
          let aee = await this.userFetch(this.customer_id);
          if (this.$checkRes(aee)) {
            let data = { customer: aee.data, shop: this.user.shop };
            this.toView(data);
          }
        }
      }
    },
    // 查看
    async toView(data) {
      if (this.customer._id != data.customer._id) this.$set(this, `customer`, data.customer);
      if (data._id) {
        this.$set(this, `form`, { room: data._id });
        // 处理已读
        let list = [];
        let res = await this.query({ room: data._id });
        if (this.$checkRes(res)) {
          // 聊天记录列表
          let arr1 = res.data.reverse();
          this.$set(this, `chatRecordList`, arr1);
          // 处理已读
          for (const p1 of res.data) {
            if (p1.speaker != this.user.shop._id && p1.is_read == '0') list.push(p1._id);
          }
          // 处理聊天图片，大图预览
          let arr = [];
          for (const p1 of this.chatRecordList) {
            if (p1.msg_type == '1') arr.push(p1.content);
          }
          this.$set(this, `srcList`, arr);
        }
        // 处理已读
        if (list.length != 0) {
          let form = { ids: list };
          res = await this.read(form);
          if (this.$checkRes(res)) this.search();
        }
      }
      this.show = '1';
    },
    // 发送图片
    toUp() {
      this.dialog = { title: '信息管理', show: true, type: '1' };
    },
    // 提交
    async onSubmit(value) {
      var form = { speaker: this.user.shop._id, time: moment().format('YYYY-MM-DD HH:mm:ss') };
      if (this.form.room) form.room = this.form.room;
      else form.customer = this.customer_id;
      if (value == 'content') {
        // 文字消息
        form.msg_type = '0';
        if (this.form.content) form.content = this.form.content;
        else this.$message({ type: `warning`, message: `请输入要发送的消息` });
      } else {
        // 图片消息
        form.msg_type = '1';
        if (this.file.length == 0) this.$message({ type: `warning`, message: `请选择要发送的图片` });
        else form.content = this.file[0].url;
      }
      let res = await this.create(form);
      if (this.$checkRes(res, '操作成功', '操作失败')) {
        let data = { _id: res.data.room, customer: this.customer, shop: this.shop };
        this.toClose();
        this.search();
        if (this.customer_id) this.searchDetail();
        if (!this.customer_id) this.toView(data);
      }
    },
    // 关闭
    toClose() {
      this.file = [];
      this.dialog = { title: '信息管理', show: false, type: '1' };
    },
    // 查询其他信息
    async searchOthers() {
      this.$set(this, `shop`, this.user.shop);
    },
  },
  computed: {
    ...mapState(['user']),
    customer_id() {
      return this.$route.query.customer_id;
    },
  },
};
</script>

<style lang="less" scoped>
.main {
  height: 81vh;
  overflow-y: auto;
  .left {
    background: rgb(240, 240, 240);
    padding: 0 5px;
    height: 80vh;
    overflow-y: auto;
  }
  .non {
    text-align: center;
    font-size: 300px;
    color: #ccc;
    padding: 10% 0;
    height: 80vh;
    overflow-y: auto;
  }
  .right {
    height: 80vh;
    background: rgb(219, 240, 188);
    overflow-y: auto;
  }
}
.dia_one {
  text-align: center;
  margin: 10px 0 0 0;
}
</style>
