<!--
 * @Description: In User Settings Edit
 * @Author: Huidong Che
 * @Date: 2020-03-27 16:38:45
 * @LastEditors: chd
 * @LastEditTime: 2020-11-18 09:25:23
-->
<template>
  <div class="wraper">
    <div class="page_left">
      <el-tree
        :data="treeData"
        :props="defaultProps"
        highlight-current
        :node-key="'statusCode'"
        :expand-on-click-node="false"
        current-node-key="PRE_HANDLING"
        default-expand-all
        @node-click="handleNodeClick"
      >
        <span
          class="custom-tree-node"
          slot-scope="{ node, data }"
        >
          <span v-html="node.label"></span>
          <span>({{ data.quantity }})</span>
        </span>
      </el-tree>
    </div>
    <div class="page_right">
      <el-form
        v-show="is_tab == 1"
        :model="searchForm"
        size="mini"
        v-enter-submit="getlist"
        :inline="true"
        ref="form"
        class="search_form"
      >
        <el-form-item label="创建时间">
          <choose-time-period
            v-model="periodTime"
          ></choose-time-period>
        </el-form-item>
        <el-form-item label="工单编号">
          <el-input
            style="width: 120px"
            v-model="searchForm.orderNo"
            placeholder="请输入"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="工单类型">
          <el-select
            v-model="searchForm.orderType"
            style="width: 120px"
            value-key=""
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="(type, index) in orderTypes"
              :key="index"
              :label="type.value"
              :value="type.key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单标题">
          <el-input
            style="width: 120px"
            v-model="searchForm.title"
            placeholder="请输入"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="负责人">
          <el-select
            style="width: 120px"
            placeholder="请选择"
            clearable
            v-model="searchForm.leader"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.realName"
              :value="user.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label>
          <el-button
            @click="getlist()"
            type="primary"
            size="mini"
          >
            查询
          </el-button>
        </el-form-item>
      </el-form>
      <div class="table-wrap" v-loading="loading">
        <table-view
          :tableColumns="tableColumns"
          :sourceData="sourceData"
          selection
          @selectionChange="selectionChange"
        ></table-view>
      </div>
      <div class="pagination">
        <el-pagination
          layout="sizes, total, prev, pager, next, jumper"
          background
          :total="centerPageOptions.total"
          :page-size="centerPageOptions.pageSize"
          :current-page="centerPageOptions.currentPage"
          @size-change="sizeChange"
          @current-change="onCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 详情 -->
    <el-dialog
      title="详情"
      :close-on-click-modal="false"
      :visible.sync="detailVisible"
      width="900px"
    >
      <div class="step-bar">
        <!-- step-pass 已经完成,step-active当前步骤 -->
        <div
          class="step step-after"
          :class="{
            'step-pass':
              detail.orderStatus === 'TO_BE_ASSIGN' ||
              detail.orderStatus === 'TO_BE_CONFIRMED' ||
              detail.orderStatus === 'IN_PROGRESS' ||
              detail.orderStatus === 'CLOSED' ||
              detail.orderStatus === 'ARCHIVE',
            'step-active':
              detail.orderStatus === 'PRE_HANDLING',
          }"
        >
          <span>待受理</span>
        </div>
        <div
          class="step step-after step-before"
          :class="{
            'step-pass':
              detail.orderStatus === 'CLOSED' ||
              detail.orderStatus === 'ARCHIVE',
            'step-active':
              detail.orderStatus === 'IN_PROGRESS' ||
              detail.orderStatus === 'TO_BE_ASSIGN' ||
              detail.orderStatus === 'TO_BE_CONFIRMED',
          }"
        >
          <span>处理中</span>
        </div>
        <div
          class="step step-after step-before"
          :class="{
            'step-pass': detail.orderStatus === 'ARCHIVE',
            'step-active': detail.orderStatus === 'CLOSED',
          }"
        >
          <span>已关闭</span>
        </div>
        <div
          class="step step-before"
          :class="{
            'step-pass': detail.orderStatus === 'ARCHIVE',
            'step-active': detail.orderStatus === 'ARCHIVE',
          }"
        >
          <span>已归档</span>
        </div>
      </div>
      <div class="content">
        <div class="detail_list">
          <div class="item_wrap">
            <p class="item" style="width: 100%">
              <span class="label">工单标题</span>
              <span class="value" style="width: 732px">{{
                detail.title
              }}</span>
            </p>
            <p class="item">
              <span class="label">工单编码</span>
              <span class="value">{{
                detail.orderNo
              }}</span>
            </p>
            <p class="item">
              <span class="label">工单类型</span>
              <span class="value">
                {{ detail.orderTypeTxt }}
              </span>
            </p>

            <p class="item">
              <span class="label">工单状态</span>
              <span class="value">
                {{ detail.orderStatusTxt }}
              </span>
            </p>
            <p
              class="item"
              style="width: 100%; display: flex"
            >
              <span class="label">工单内容</span>
              <span
                style="flex: 1; display: inline-block"
                class="value"
                v-html="detail.content"
              ></span>
            </p>
          </div>
          <div
            style="padding: 5px; overflow: auto"
            v-html="detail.taskContent"
            @click="fullScreenDisplay"
          ></div>
        </div>
        <div class="record">
          <div class="title">沟通记录</div>
          <ul
            class="chat_content"
            v-if="chatRecord.length > 0"
          >
            <li
              v-for="(item, index) in chatRecord"
              :key="index"
              class="chat_item"
              :class="{ chat_right: item.type === 2 }"
            >
              <div class="chat_warp" v-if="item.type === 2">
                <div class="chat_user">
                  <div class="chat_user_time">
                    {{
                      item.createTime
                    }}&nbsp;&nbsp;&nbsp;&nbsp;客服
                  </div>
                  <div class="chat_text">
                    {{ item.msg }}
                  </div>
                </div>
                <div class="chat_icon">
                  <img
                    width="100%"
                    src="http://img.alicdn.com/tfs/TB14feR0AL0gK0jSZFAXXcA9pXa-64-64.png"
                    alt=""
                  />
                </div>
              </div>
              <div v-else class="chat_warp">
                <div class="chat_icon">
                  <img
                    width="100%"
                    src="http://img.alicdn.com/tfs/TB14feR0AL0gK0jSZFAXXcA9pXa-64-64.png"
                    alt=""
                  />
                </div>
                <div class="chat_user">
                  <div class="chat_user_time">
                    {{
                      item.sendUserName
                    }}:&nbsp;&nbsp;&nbsp;&nbsp;{{
                      item.createTime
                    }}
                  </div>

                  <div class="chat_text">
                    {{ item.msg }}
                  </div>
                </div>
              </div>
            </li>
          </ul>
          <div class="empty-data" v-else>暂无数据</div>
        </div>
      </div>

      <div style="margin-top: 10px">
        <div>
          <el-input
            type="textarea"
            :rows="4"
            maxlength="1000"
            placeholder="请输入内容"
            v-model="textarea"
          >
          </el-input>
        </div>
        <div style="margin-top: 10px; text-align: right">
          <el-button
            size="mini"
            type="success"
            @click="confirm"
            >受理</el-button
          >
          <el-button
            size="mini"
            type="primary"
            @click="reply"
            >回复</el-button
          >
        </div>
      </div>
    </el-dialog>

    <!-- 指派 -->
    <el-dialog
      title="指派给"
      :close-on-click-modal="false"
      :visible.sync="assignVisible"
      width="300px"
    >
      <el-select
        style="width: 100%"
        size="small"
        v-model="user"
      >
        <el-option
          v-for="user in userList"
          :key="user.id"
          :label="user.realName"
          :value="user.id"
        ></el-option>
      </el-select>
      <span slot="footer">
        <el-button
          size="mini"
          @click="assignVisible = false"
          >取消</el-button
        >
        <el-button
          size="mini"
          type="primary"
          @click="submitAssign"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import tableView from '@/common/components/base/tableView.vue'
import ChooseTimePeriod from '../../components/base/chooseTimePeriod.vue'
import pagination from '../../mixins/pagination'
import axios from '../../common/api/axios'
import {
  getOrderTree,
  workConfirmed,
  workAssigned,
  startWorder,
  archiveWorkOrder,
  replyTocustomer,
  getOrderType,
} from '@/common/api/order'
import { getSystemUserList } from '@/common/api/system'
import { mapState } from 'vuex'
// import confirmWork from '@/assets/work/confirm.png'
import assignWork from '@/assets/work/assign.png'
import startWork from '@/assets/work/start.png'
import archiveWork from '@/assets/work/archive.png'

export default {
  name: 'task_center',
  mixins: [pagination],
  components: {
    ChooseTimePeriod,
    tableView,
  },
  data() {
    const userInfo = localStorage.getItem('userinfo')
    let employeeId
    if (userInfo) {
      employeeId = JSON.parse(userInfo).employeeId
    }

    return {
      loading: false,
      user: '',
      textarea: '',
      centerPageOptions: {
        pageSize: 100,
        currentPage: 1,
        total: 0,
      },
      taskLeader: '',
      assignVisible: false,
      periodTime: [],
      selections: [],
      is_tab: '1',
      statusCode: 'PRE_HANDLING',
      searchForm: { timeProp: 'create_time' },
      isEdit: false,
      sourceData: [],
      currentRowId: '',
      editForm: {},
      commentsVisible: false,
      detail: {},
      detailVisible: false,
      employeeId,
      taskTypes: [],
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'statusName',
      },
      userList: [],
      orderTypes: [],
      chatRecord: [],
    }
  },
  mounted() {
    this.getOrderTree()
    this.getlist()
    this.getSystemUserList()
    this.getOrderTypes()
  },
  computed: {
    ...mapState(['deptStaff']),
    tableColumns() {
      // const employeeId = this.employeeId
      return [
        { label: '工单编号', key: 'orderNo', width: 110 },
        {
          label: '工单类型',
          key: 'orderTypeTxt',
          width: 80,
        },
        {
          label: '工单标题',
          key: 'title',
          minWidth: 120,
          align: 'left',
        },
        {
          label: '负责人',
          key: 'leaderName',
          width: 80,
        },
        {
          label: '创建人',
          key: 'fromBusiness',
          width: 80,
        },

        {
          label: '工单状态',
          key: 'orderStatusTxt',
          width: 80,
        },

        {
          label: '创建时间',
          key: 'createTime',
          width: 130,
        },
        {
          label: '操作',
          fixed: 'right',
          width: 80,
          align: 'center',
          render: (item) => (
            <span>
              {(item.orderStatus === 'PRE_HANDLING' ||
                item.orderStatus === 'IN_PROGRESS') && (
                <span
                  title="详情"
                  class="icon-view icon-tools-view"
                >
                  <i
                    class="el-icon-tickets"
                    onClick={() => this.showDetail(item)}
                  ></i>
                </span>
              )}
              {item.orderStatus === 'TO_BE_ASSIGN' && (
                <span title="指派给" class="icon-view">
                  <img
                    width="24"
                    height="24"
                    src={assignWork}
                    onClick={() => this.showAssign(item)}
                  />
                </span>
              )}
              {item.orderStatus === 'TO_BE_CONFIRMED' && (
                <span title="开始" class="icon-view">
                  <img
                    width="24"
                    height="24"
                    src={startWork}
                    onClick={() =>
                      this.startWorkOrder(item)
                    }
                  />
                </span>
              )}
              {item.orderStatus === 'CLOSED' && (
                <span title="归档" class="icon-view">
                  <img
                    width="24"
                    height="24"
                    src={archiveWork}
                    onClick={() => this.archive(item)}
                  />
                </span>
              )}
            </span>
          ),
        },
      ]
    },
  },
  methods: {
    async getOrderTypes() {
      try {
        const res = await getOrderType()
        this.orderTypes = res.data
      } catch (e) {
        console.error(e)
      }
    },
    sizeChange(pageSize) {
      this.centerPageOptions.pageSize = pageSize
      this.getlist()
    },
    onCurrentChange(currentPage) {
      this.centerPageOptions.currentPage = currentPage
      this.getlist()
    },
    operation() {},
    async getSystemUserList() {
      try {
        const res = await getSystemUserList()
        this.userList = res.data
      } catch (e) {
        console.error(e)
      }
    },
    // 确认
    async confirm() {
      try {
        await this.$confirm('确定执行吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
      } catch {
        return
      }
      try {
        const res = await workConfirmed(this.currentRowId)
        if (res.code === 200) {
          this.getlist()
          this.getOrderTree()
          this.detailVisible = false
          this.$message.success('操作成功')
        }
      } catch (e) {
        console.error(e)
      }
    },
    async getOrderTree() {
      try {
        const res = await getOrderTree()
        if (res.code === 200) {
          this.treeData = [res.data]
        }
      } catch (e) {
        console.error(e)
      }
    },
    handleClick(v) {
      this.is_tab = v
      this.getlist()
    },
    fullScreenDisplay(e) {
      if (e.target.nodeName === 'IMG') {
        const uri = e.target.src
        console.log(uri)
        window.open(uri)
      }
    },
    showAssign(item) {
      this.currentRowId = item.id
      this.taskLeader = ''
      this.assignVisible = true
    },
    // 开始工单
    async startWorkOrder(item) {
      try {
        await this.$confirm('确定开始吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
      } catch {
        return
      }
      try {
        const res = await startWorder(item.id)
        if (res.code === 200) {
          this.getlist()
          this.getOrderTree()
        }
      } catch (e) {
        console.error(e)
      }
    },
    // 提交分派
    async submitAssign() {
      if (!this.user) {
        return this.$message.warning('请选择负责人')
      }
      try {
        const res = await workAssigned(
          this.selections[0].id,
          this.user,
        )
        if (res.code === 200) {
          this.assignVisible = false
          this.getlist()
          this.getOrderTree()
        }
      } catch (e) {
        console.error(e)
      }
    },
    handleNodeClick(data) {
      this.statusCode = data.statusCode
      this.getlist()
    },
    async getlist() {
      this.loading = true
      const { pageSize, currentPage } =
        this.centerPageOptions
      axios
        .post('platform/platformWorkOrder/list_page', {
          pageSize,
          currentPage,
          orderStatus: this.statusCode,
          startTime: this.periodTime && this.periodTime[0],
          endTime: this.periodTime && this.periodTime[1],
          ...this.searchForm,
        })
        .then((res) => {
          this.sourceData = res.data.records
          this.centerPageOptions.total = res.data.total
          this.loading = false
        })
    },
    async archive(item) {
      try {
        await this.$confirm('确定归档吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
      } catch {
        return
      }
      try {
        const res = await archiveWorkOrder(item.id)
        if (res.code === 200) {
          this.getlist()
          this.getOrderTree()
        }
      } catch (e) {
        console.error(e)
      }
    },
    selectionChange(selection) {
      this.selections = selection
    },
    async reply() {
      if (!this.textarea) {
        return this.$message.warning('请输入内容')
      }

      try {
        const res = await replyTocustomer(
          this.currentRowId,
          this.textarea,
        )
        if (res.code === 200) {
          this.showDetail(this.detail)
        }
      } catch (e) {
        console.error(e)
      }
    },
    async showDetail(item) {
      this.currentRowId = item.id
      this.detail = item
      axios
        .get(
          `platform/platformWorkOrderChat/getByWorkOrder?workOrderId=${item.id}`,
        )
        .then((res) => {
          if (res.code === 200) {
            this.chatRecord = res.data
          }
        })
      this.detailVisible = true
      this.textarea = ''
    },
  },
}
</script>
<style lang="scss" scoped>
.wraper {
  height: 100%;
  display: flex;
  overflow: hidden;

  &::v-deep {
    .el-tree-node {
      font-size: 14px;
    }
    .el-tree-node__content {
      height: 32px;
      padding: 4px 0px;
      padding-left: 10px !important;
    }
    .el-tree-node__children .el-tree-node.is-current {
      .el-tree-node__content {
        position: relative;
        color: #1565c0;
        font-size: 16px;
      }

      .el-tree-node__content::before {
        position: absolute;
        content: '';
        top: 0;
        bottom: 0;
        left: 0;
        width: 4px;
        display: block;
        background-color: #1565c0;
      }
    }
  }
}
.page_left {
  width: 200px;
  min-width: 200px;
  background: #fff;
  border-radius: 5px;
  margin-right: 10px;
}
.page_right {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 5px;
  overflow: hidden;
}
.search_form {
  margin-top: 5px;
  margin-left: 10px;
}
.search_form >>> .el-form-item {
  margin-bottom: 5px;
}
.content {
  max-height: 68vh;
  overflow: auto;
}
.detail_list {
  padding-top: 10px;
  background-color: #efefef;
}
.detail_list .item {
  display: inline-block;
  width: 30%;
  line-height: 24px;
  margin-bottom: 10px;
}
.detail_list .item .label {
  display: inline-block;
  color: #999;
  width: 100px;
  text-align: right;
  margin-right: 5px;
}
.detail_list .item .value {
  color: #222;
}
.item_wrap {
  background: #efefef;
  padding-top: 10px;
}
.detail_list .item .label {
  display: inline-block;
  color: #999;
  width: 100px;
  text-align: right;
  margin-right: 5px;
}
.detail_list .item .value {
  color: #222;
}
.form_item >>> .el-radio {
  margin-right: 13px;
}
.form_item >>> .el-radio svg {
  vertical-align: text-bottom;
}
.detail_btn {
  display: inline-block;
  font-size: 14px;
  border: 1px solid #ddd;
  border-radius: 5px;
  color: #fff;
  padding: 3px 15px;
  cursor: pointer;
  vertical-align: bottom;
}
.detail_btn + .detail_btn {
  margin-left: 10px;
}
.table-wrap {
  background: #fff;
  flex: 1;
  overflow: hidden;
  width: 100%;
}

.step-bar {
  margin-bottom: 10px;
  display: flex;
}
.step {
  position: relative;
  flex: 1;
  font-size: 14px;
  height: 32px;
  line-height: 32px;
  color: #fff;
  background-color: #cacaca;
  z-index: 1;
  text-align: center;
}

.step,
.step span {
  display: inline-block;
}

.step span {
  width: 90%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.step-before:before {
  left: -16px;
  z-index: 8;
  border-top: 16px solid #cacaca;
  border-left: 16px solid transparent !important;
  border-bottom: 16px solid #cacaca;
}
.step-after:after {
  width: 22px;
  height: 32px;
  right: 0;
  z-index: 9;
  border-top: 16px solid transparent !important;
  border-left: 16px solid #cacaca;
  border-bottom: 16px solid transparent !important;
  background-color: #fff;
}
.step-after:after,
.step-before:before {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  box-sizing: border-box;
}
.step-active {
  background-color: #ff6a00;
}
.step-active:after,
.step-active:before {
  border-color: #ff6a00;
}
.step-pass {
  background-color: rgba(255, 106, 0, 0.5);
}
.step-pass:after,
.step-pass:before {
  border-color: rgba(255, 106, 0, 0.5);
}

.record {
  border: 1px solid #efefef;
  margin-top: 10px;
}
.record .title {
  height: 40px;
  line-height: 40px;
  font-size: 16px;
  padding-left: 10px;
  background: #efefef;
  border-left: 2px solid #ff6a00;
}
.chat_content {
  padding: 10px;
}

.chat_item {
  margin-bottom: 10px;
}
.chat_item.chat_right {
  text-align: right;
}
.chat_warp {
  display: flex;
}
.chat_right .chat_warp {
  justify-content: end;
}
.chat_icon {
  width: 30px;
  height: 30px;
  background: #efefef;
  border-radius: 50%;
  margin-top: 5px;
  margin-right: 5px;
  margin-left: 5px;
}

.empty-data {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
}
.detail_list {
  &::v-deep {
    table {
      border-right: 1px solid #000000;
      border-bottom: 1px solid #000000;
      text-align: center;
      width: 100% !important;
      border-spacing: 0;
    }

    table th {
      border-left: 1px solid #000000;
      border-top: 1px solid #000000;
      padding: 6px;
    }

    table td {
      border-left: 1px solid #000000;
      border-top: 1px solid #000000;
      padding: 6px;
      height: 20px;
    }
  }
}
</style>
