<template>
  <div>
    <Navbar :title="'任务详细信息' + (trace == null ? '' : '-' + trace.projectName)" :is-go-back="true" />
    <div v-if="isflag">
      <a-row justify="center" style="margin-bottom: 16px">
        <a-col :span="24" style="text-align: center">
          <div v-if="finished" class="checked" @click="getTimeLineNumber()" />
          <div v-else class="clickFinished" @click="getTimeLineNumber()">
            <div class="clickFinishedText">
              <span>点击完成任务</span>
            </div>
          </div>
        </a-col>
      </a-row>

      <a-space direction="vertical" style="width: 100%">
        <a-row align="middle">
          <a-col :flex="1">
            <a-typography-title :level="3" style="margin-bottom: 0;margin-top: 0px">
              <span>{{ trace.summary }}</span>
              <a-tag class="label" :color="trace.overdue ? '#d9534f' : '#337ab7'">
                责任人:{{ trace.receiveUserName }}, 时间节点:{{
                  formatDate(trace.planFinishedDate)
                }}
              </a-tag>
            </a-typography-title>
          </a-col>
          <a-col>
            <a-space>
              <a-button style="padding: 4px" type="link" @click="edit">编辑</a-button>
              <a-button style="padding: 4px" type="link" @click="deleteTrace">删除</a-button>
              <a-button style="padding: 4px" type="link" @click="copyShaneUrl">复制链接</a-button>
            </a-space>
          </a-col>
        </a-row>
        <a-divider />

        <!-- eslint-disable-next-line -->
        <div id="content-editor-view" v-html="trace.detail" />

        <AudioField :class-name="className" :src-array="srcArray" :is-readonly="'true'" @delete-audio-src="undefined" />
      </a-space>

      <TraceTimeLine ref="traceTimeLine" :trace-id="traceId" :trace="trace" @refresh-trace-log="refreshTraceLog" />

      <div style="margin-top: 20px">
        <span>附件</span>
        <a-divider />
      </div>

      <TraceAttachment :trace-id="traceId" :class-name="attachmentClassName" />

      <div style="margin-top: 20px">
        <span>评论信息</span>
        <a-divider />
      </div>

      <TraceComment :trace-id="traceId" />

      <a-button block style="margin-top: 16px;background: #efefef" @click="openTraceComment">
        <template #icon><edit-outlined /></template>
        评论
      </a-button>

      <div style="margin-top: 20px">
        <TraceLog ref="traceLog" :trace-id="traceId" :trace="trace" :class-name="className" />
      </div>
    </div>
    <Loading v-if="loading" />
  </div>
</template>

<script>
import Common from '../common/Common.js';
import UpladFile from '../widget/UpladFile.js';
import TraceCommon from './TraceCommon.js';
import TraceResource from './TraceResource.js';
import TraceLog from './TraceLog.vue';
import TraceComment from './TraceComment.vue';
import TraceTimeLine from './TraceTimeLine.vue';
import TraceAttachment from './TraceAttachment.vue';
import AudioField from '../widget/AudioField.vue';
import { Notify } from 'pc-component-v3';
import { EditOutlined } from '@ant-design/icons-vue';

export default {
  components: {
    TraceLog,
    TraceComment,
    TraceTimeLine,
    TraceAttachment,
    UpladFile,
    AudioField,
    EditOutlined,
  },
  data: function () {
    this.formatDate = TraceCommon.formatDate;

    return {
      traceId: undefined,
      trace: {},
      finished: undefined,
      count: 0,
      attachmentList: [],
      className: 'com.leanwo.prodog.Trace',
      attachmentClassName: 'com.leanwo.prodog.model.trace.TraceAttachment',
      srcArray: [],
      isflag: true,
      loading: false,
    };
  },

  computed: {
    finishedImageName: function () {
      if (this.finished != true) {
        return '../../static/image/finished.png';
      } else {
        return '../../static/image/finished2.png';
      }
    },
  },

  mounted: function () {
    this.traceId = this.$route.params.traceId;
    this.judgePermission();
  },
  methods: {
    /**
     * 复制链接
     * @author GuoZhiBo 20191024
     */
    copyShaneUrl: function () {
      var input = document.createElement('input'); // 直接构建input
      var url = window.location.href;
      input.value = url; // 设置内容
      document.body.appendChild(input); // 添加临时实例
      input.select(); // 选择实例内容
      document.execCommand('Copy'); // 执行复制
      document.body.removeChild(input); // 删除临时实例
      Notify.success('提示', '复制链接成功');
    },
    back: function () {
      history.back();
    },

    getCount: function () {
      return this.$refs.traceTimeLine.count;
    },

    /**
     * 初始化数据
     * @author GuoZhiBo 20171201
     */
    initData: function () {
      this.loadTraceById();
    },

    /**
     * 根据追踪单Id查询追踪单的数据
     */
    loadTraceById: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('TraceResource/uniqueByTraceId'),
        type: 'get',
        dataType: 'json',
        data: {
          traceId: _self.traceId,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if (data != null) {
            _self.traceId = data.id;
            _self.finished = data.finished;
            _self.trace = data;
            if (data.audioSrcs != null) {
              _self.srcArray = JSON.parse(data.audioSrcs);
            }
            _self.$nextTick(() => {
              Common.downloadByA('#content-editor-view');
            });
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    getUrl: function (item) {
      var _self = this;
      var url =
        Common.getApiURL('file/fileDownload') +
        '?className=' +
        _self.className +
        '&fileName=' +
        item;
      return url;
    },
    /**
     * 修改追踪单的状态
     * @author GuoZhiBo 20171201
     */
    updateTracefinished: function () {
      var _self = this;
      if (_self.count == 0) {
        _self.loading = true;
        TraceResource.updateTraceFinished(_self.trace.id).then(
          successData => {
            _self.loadTraceById();
            _self.loading = false;
            _self.$refs.traceLog.getTraceLog();
          },
          errorData => {
            _self.loading = false;
            Common.processException(errorData);
          },
        );
      } else {
        Notify.error('提示', '还有时间节点没有完成！');
      }
    },

    getTimeLineNumber: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL(
          'TraceTimeLineResource/queryTraceTimeLineNumberFalse',
        ),
        type: 'get',
        dataType: 'json',
        async: false,
        data: {
          traceId: _self.trace.id,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.count = data;
          _self.updateTracefinished();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 打开评论界面进行评论
     * @author GuoZhiBo 20171201
     */
    openTraceComment: function () {
      var _self = this;
      this.$router.push('/trace/traceCommentCreate/' + _self.trace.id);
    },

    /**
     * 获取图片地址
     * @param  {String} item 图片名称
     * @return {String}      图片URL地址
     */
    getImageSrc: function (item) {
      var _self = this;
      if (item != undefined && item != null) {
        return Common.getResourceUrl(
          'image',
          'com.leanwo.prodog.trace.model.TraceComment',
          item,
        );
      } else {
        return '';
      }
    },

    /**
     * 编辑
     */
    edit: function () {
      var _self = this;
      _self.$router.push('/trace/traceUpdate/' + _self.traceId);
    },

    /**
     * 删除
     */
    deleteTrace: function () {
      var _self = this;

      Notify.show({
        title: '删除确认',
        message:
          '您确定要删除任务' +
          _self.trace.summary +
          '吗？如果"是"的话，请点击"确定"按钮，否则点击"取消"按钮',
        buttons: [
          {
            label: '确定',
            cssClass: 'btn-primary',
            action: function (dialogItself) {
              dialogItself.close();
              $.ajax({
                url: Common.getApiURL('TraceResource/deleteTraceById'),
                type: 'get',
                dataType: 'json',
                data: {
                  traceId: _self.traceId,
                },
                beforeSend: function (request) {
                  Common.addTokenToRequest(request);
                },
                success: function (data) {
                  Notify.success('提示', '删除成功！');
                  _self.back();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                  Common.processException(
                    XMLHttpRequest,
                    textStatus,
                    errorThrown,
                  );
                  Notify.error('提示', '删除失败！');
                },
              });
            },
          },
          {
            label: '取消',
            action: function (dialogItself) {
              dialogItself.close();
            },
          },
        ],
      });
    },
    refreshTraceLog: function () {
      this.$refs.traceLog.getTraceLog();
    },
    /**
     * 根据追踪单Id查询追踪单的数据
     */
    judgePermission: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('TraceResource/judgePermission'),
        type: 'get',
        dataType: 'json',
        data: {
          traceId: _self.traceId,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.isflag = data;
          if (_self.isflag) {
            _self.initData();
          } else {
            Notify.error('提示', '你没有访问权限！');
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
  },
};
</script>

<style scoped>
.label {
  display: inline;
  padding: 0.2em 0.6em 0.3em;
  font-size: 64%;
  font-weight: 700;
  line-height: 1;
  color: #fff;
  text-align: center;
  white-space: nowrap;
  vertical-align: baseline;
  border-radius: 0.25em;
  margin-left: 10px;
}

.checked {
  background: #69ba52;
  width: 80px;
  height: 80px;
  border-radius: 16px;
  position: relative;
  cursor: pointer;
  margin: 0 auto;
}

.checked::after {
  content: "";
  background-color: white;
  width: 26px;
  height: 8px;
  position: absolute;
  top: 44px;
  left: 14px;
  border-radius: 8px;
  transform: rotate(34deg);
}

.checked::before {
  content: "";
  background-color: white;
  width: 43px;
  height: 8px;
  position: absolute;
  top: 37px;
  left: 26px;
  transform: rotate(-50deg);
  border-radius: 8px;
}

.clickFinished {
  border: 2px solid #9b9b9b;
  width: 80px;
  height: 80px;
  border-radius: 16px;
  position: relative;
  cursor: pointer;
  user-select: none;
  margin: 0 auto;
}

.clickFinishedText {
  width: 50px;
  height: 50px;
  color: #9b9b9b;
  margin-top: 16px;
  margin-left: 15px;
}

:deep(.ant-divider-horizontal) {
  margin: 10px 0 !important;
}
</style>
