<template>
  <div class="detail">
    <div class="side-layout">
      <div class="info">
        <div class="title">
          <p>工单</p>
          <h3>
            {{ detail.name }}
            <span v-if="detail.orderStatus == '30'">
              <span>
                <el-button
                  v-if="
                    detail.orderTypeName == '产品试用申请（硬件）' || detail.orderTypeName == '产品试用申请（软件）'
                  "
                  v-permissions="['work:workOrder:try:changeTime']"
                  @click="handleChangeTime()">
                  改期
                </el-button>
                <el-button
                  v-if="detail.orderTypeName == '技术文件支持'"
                  v-permissions="['work:workOrder:support:changeTime']"
                  @click="handleChangeTime()">
                  改期
                </el-button>
                <el-button
                  v-if="detail.orderTypeName == '售前讲解支持'"
                  v-permissions="['work:workOrder:sale:changeTime']"
                  @click="handleChangeTime()">
                  改期
                </el-button>
              </span>
              <!--支持人员反馈(总结)-->
              <span>
                <el-button
                  v-if="
                    !detail.feedbackSupportBy &&
                    (detail.orderTypeName == '技术文件支持' || detail.orderTypeName == '售前讲解支持')
                  "
                  v-permissions="['work:workOrder:feedback:support']"
                  @click="openFeedBack('support')">
                  支持人员总结
                </el-button>
              </span>
              <!--销售反馈-->
              <span>
                <el-button
                  v-if="
                    detail.feedbackSupportBy &&
                    !detail.feedbackSaleBy &&
                    (detail.orderTypeName == '技术文件支持' || detail.orderTypeName == '售前讲解支持')
                  "
                  v-permissions="['work:workOrder:feedback:sale']"
                  @click="openFeedBack('sale')">
                  销售反馈
                </el-button>
              </span>
              <span
                v-if="detail.orderTypeName == '产品试用申请（硬件）' || detail.orderTypeName == '产品试用申请（软件）'">
                <!--试用启动反馈-->
                <el-button
                  v-if="!detail.feedbackTrail"
                  v-permissions="['work:workOrder:feedback:start']"
                  @click="openFeedBack('start')">
                  试用启动反馈
                </el-button>
                <!--试用过程反馈-->
                <el-button
                  v-if="detail.feedbackTrail && !detail.feedbackTrail.find((item) => item.feedbackTrialType == 30)"
                  v-permissions="['work:workOrder:feedback:process']"
                  @click="openFeedBack('process')">
                  试用过程反馈
                </el-button>
                <!--试用总结反馈-->
                <el-button
                  v-if="
                    detail.feedbackTrail &&
                    detail.feedbackTrail.length > 1 &&
                    !detail.feedbackTrail.find((item) => item.feedbackTrialType == 30)
                  "
                  v-permissions="['work:workOrder:feedback:summarize']"
                  @click="openFeedBack('summarize')">
                  试用总结反馈
                </el-button>
              </span>
            </span>
          </h3>
        </div>
        <header>
          <el-descriptions :colon="false" :column="6" direction="vertical" style="padding-top: 15px">
            <el-descriptions-item content-class-name="my-content" label="名称" label-class-name="my-label">
              {{ detail.name }}
            </el-descriptions-item>
            <el-descriptions-item content-class-name="my-content" label="工单类型" label-class-name="my-label">
              {{ detail.orderTypeName }}
            </el-descriptions-item>
            <el-descriptions-item content-class-name="my-content" label="工单状态" label-class-name="my-label">
              {{ selectDictLabel(orderStatusOptions, detail.orderStatus) }}
            </el-descriptions-item>
            <el-descriptions-item content-class-name="my-content" label="分派人员" label-class-name="my-label">
              {{ detail.assignUserName }}
            </el-descriptions-item>
            <el-descriptions-item content-class-name="my-content" label="创建人" label-class-name="my-label">
              {{ detail.createdName }}
            </el-descriptions-item>
            <el-descriptions-item content-class-name="my-content" label="创建时间" label-class-name="my-label">
              {{ parseTime(detail.createdTime, '{y}-{m}-{d}') }}
            </el-descriptions-item>
          </el-descriptions>
        </header>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="详细信息" name="detail">
            <el-descriptions
              border
              :column="2"
              :content-style="{ width: '35%', 'word-break': 'break-all' }"
              :label-style="{ width: '15%' }"
              size="small">
              <el-descriptions-item
                v-for="(item, index) in dingFormData"
                v-show="item.componentName !== 'TableField'"
                :key="index"
                :label="item.name">
                <span v-if="item.name == '试用开始时间'">
                  {{ parseTime(detail.trialTimeStart, '{y}-{m}-{d} {h}:{i}') }}
                </span>
                <span v-else-if="item.name == '试用结束时间'">
                  {{ parseTime(detail.trialTimeEnd, '{y}-{m}-{d} {h}:{i}') }}
                </span>
                <span v-else-if="item.name == '期望完成时间'">
                  {{ parseTime(detail.expectTime, '{y}-{m}-{d} {h}:{i}') }}
                </span>
                <span v-else-if="item.name == '支持时间'">
                  {{ parseTime(detail.supportTime, '{y}-{m}-{d} {h}:{i}') }}
                </span>
                <span v-else-if="item.componentName === 'DDDateRangeField'">{{ item.value.join(' 至 ') }}</span>
                <span v-else-if="item.componentName === 'DDAttachment'">
                  {{ item && item.length > 0 ? item[0].fileName : '' }}
                </span>
                <span v-else>{{ item.value }}</span>
              </el-descriptions-item>
            </el-descriptions>
            <div v-if="dingFormTableData.length">
              <h3 style="margin-top: 10px; margin-bottom: 10px">{{ dingFormTableName }}</h3>
              <el-table border :data="dingFormTableData">
                <el-table-column
                  v-for="(col, index) in dingFormTableHeader"
                  :key="index"
                  align="center"
                  :label="col.name"
                  :prop="col.id"
                  show-overflow-tooltip />
              </el-table>
            </div>
            <div v-if="detail.finishRemark">
              <h3 style="margin-top: 10px; margin-bottom: 10px">完成信息</h3>
              <el-row>
                <el-col :span="24" style="margin-bottom: 10px">
                  <div>{{ detail.finishByName }}于 {{ detail.finishTime }} 完成</div>
                </el-col>
                <el-col :span="24">
                  <div>
                    {{ detail.finishRemark }}
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
          <!-- <el-tab-pane label="反馈记录" name="feedback">
            <feedback-record :detail="detail" />
          </el-tab-pane> -->
          <el-tab-pane
            v-if="detail.orderTypeName == '技术文件支持' || detail.orderTypeName == '售前讲解支持'"
            label="支持人员总结"
            name="supportFB">
            <feedback-record :detail="detail" type="support" />
          </el-tab-pane>
          <el-tab-pane
            v-if="detail.orderTypeName == '技术文件支持' || detail.orderTypeName == '售前讲解支持'"
            label="销售反馈"
            name="saleFB">
            <feedback-record :detail="detail" type="sale" />
          </el-tab-pane>
          <el-tab-pane
            v-if="detail.orderTypeName == '产品试用申请（硬件）' || detail.orderTypeName == '产品试用申请（软件）'"
            label="试用反馈"
            name="try">
            <feedback-record :detail="detail" type="try" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="info-side">
        <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>
                  <div class="feedback-content">{{ JSON.parse(item.opnContent).content }}</div>
                  <p>{{ item.opnDate }}</p>
                </div>
              </li>
            </ul>
          </li>
        </ul>
        <el-input
          v-model="feedBackContent"
          maxlength="30"
          placeholder="请输入反馈内容"
          show-word-limit
          style="margin-bottom: 7px"
          type="textarea" />
        <el-row>
          <el-col style="text-align: right">
            <el-button type="primary" @click="handleSubFeedBack">提交反馈</el-button>
          </el-col>
        </el-row>
      </div>
    </div>
    <support-feedback ref="supportFB" @update-detail="getDetail" />
    <sale-feedback ref="saleFB" @update-detail="getDetail" />
    <try-feedback ref="tryFB" @update-detail="getDetail" />
    <change-time ref="changeTime" @update-detail="getDetail" />
  </div>
</template>

<script>
  import to from 'await-to-js'
  import api from '@/api/work/index'
  import SaleFeedback from '@/views/work/order/components/SaleFeedback'
  import SupportFeedback from '@/views/work/order/components/SupportFeedback'
  import TryFeedback from '@/views/work/order/components/TryFeedback'
  import FeedbackRecord from './components/FeedbackRecord'
  import ChangeTime from './components/ChangeTime'
  export default {
    name: 'WorkOrderDetail',
    components: { FeedbackRecord, SaleFeedback, SupportFeedback, TryFeedback, ChangeTime },
    data() {
      return {
        feedBackContent: '',
        id: undefined,
        activeName: 'detail',
        detail: {},
        dingFormData: {},
        dingFormTableName: [],
        dingFormTableHeader: [],
        dingFormTableData: [],
        orderStatusOptions: [],
        records: [],
      }
    },
    mounted() {
      this.id = parseInt(this.$route.query.id)
      this.getOptions()
      this.getDynamics()
      this.getDetail()
    },
    methods: {
      handleChangeTime() {
        this.$refs.changeTime.open(this.detail)
      },
      // 打开不同的反馈组件
      openFeedBack(type = null) {
        if (type == 'support') {
          this.$refs.supportFB.open(this.detail)
        } else if (type == 'sale') {
          this.$refs.saleFB.open(this.detail)
        } else {
          this.$refs.tryFB.open(this.detail, type)
        }
      },
      async getDynamics() {
        const [err, res] = await to(api.dynamicsList({ orderId: this.id }))
        if (err) return
        if (res.data.list) {
          let obj = res.data.list
          const keys = Object.keys(obj).reverse()
          let records = {}
          for (const item of keys) {
            records[item] = obj[item]
          }
          this.records = records
        }
      },
      async handleSubFeedBack() {
        let params = {
          content: this.feedBackContent,
          orderId: this.id,
        }
        const [err, res] = await to(api.addDynamics({ ...params }))
        if (err) return
        console.log(res)
        if (res.code == 200) {
          this.feedBackContent = ''
          this.$message({
            type: 'success',
            message: '提交成功!',
          })
          this.getDynamics()
        }
      },
      getOptions() {
        Promise.all([this.getDicts('work_order_status')])
          .then(([workOrderStatus]) => {
            this.orderStatusOptions = workOrderStatus.data.values || []
          })
          .catch((err) => console.log(err))
      },
      async getDetail() {
        const [err, res] = await to(api.getDetail({ id: this.id }))
        if (err) return
        if (res.code == 200) {
          this.detail = res.data
          this.dingFormData = JSON.parse(this.detail.formData)
          this.checkDingFormType()
        }
      },
      checkDingFormType() {
        for (let item of this.dingFormData) {
          if (item.componentName === 'TableField') {
            this.dingFormTableName = item.name
            if (item.value.length === 0) {
              continue
            }
            this.dingFormTableHeader = item.value[0]
            this.dingFormTableData = []
            let tableData = []
            for (let row of item.value) {
              let obj = {}
              for (let col of row) {
                obj[col.id] = col.value
              }
              tableData.push(obj)
            }
            this.dingFormTableData = tableData
          }
        }
        this.dingFormData = this.dingFormData.filter((item) => item.componentName !== 'TableField')
      },
      async handleClick(tab) {
        if (tab.name === 'feedback') {
          // await this.$refs.feedback.fetchData()
        } else if (tab.name === 'worksheet') {
          return
        } else {
          return
        }
      },
    },
  }
</script>

<style lang="scss" scoped>
  $base: '.detail';

  #{$base} {
    height: calc(100vh - 60px - 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;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

    .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% - 90px);
      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;
          }
        }
      }
    }
    .feedback-content {
      margin: 10px 0;
      color: #000;
    }
  }
</style>
