<template>
  <div class="app-container" style="padding-top:0">
    <div class="recordLayout">
      <div style="border-left:5px solid #1890ff;padding-left:5px">工单详情</div>

      <div class="convenienceInfo">
        <div class="convenienceTitle">
          <i class="icon_list" />
          <div style="flex:1">
            <div class="eventType">
              <span v-if="!isEventTypeChange">{{
                convenience && convenience.eventType.eventName
              }}</span>

              <!-- <el-cascader
                ref="cascader"
                v-else
                v-model="convenience.eventType.id"
                :options="typeOptions"
                :show-all-levels="false"
                :props="{ emitPath: false }"
                placeholder="编辑"
                @change="handleEventTypeChange"
              /> -->
              <el-select
                ref="eventTypeRef"
                v-model="convenience.eventType.id"
                placeholder="请选择"
                @change="handleEventTypeChange"
                v-else
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.id"
                  :label="item.eventName"
                  :value="item.id"
                >
                </el-option>
              </el-select>

              <el-button
                v-if="
                  convenience &&
                    convenience.isSelf &&
                    convenience.statusList[0] &&
                    convenience.phase !== 'FINISH' &&
                    convenience.statusList[0].status !== 'WAIT_APPLY' &&
                    convenience.statusList[0].status !== 'SUBMIT_APPLY' &&
                    convenience.statusList[0].status !== 'FORWARDED_APPLY' &&
                    convenience.statusList[0].status !== 'FORWARDED'
                "
                type="text"
                style="font-size:16px"
                @click="cascader"
                ><i class="icon_edit" />{{
                  isEventTypeChange ? "取消" : "编辑"
                }}</el-button
              >
            </div>
            <div style="color:#787878;font-size:14px;">
              {{ convenience && convenience.sponsor | sponsorFilter }}创建于{{
                convenience &&
                  convenience.createDate | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
              }}
              <el-tag type="danger" style="color:#ff5f40;background:#ffe0da">{{
                convenience && convenience.phase | phaseFilter
              }}</el-tag>
            </div>
          </div>
          <div>
            <el-button
              v-if="
                convenience &&
                  convenience.isSelf &&
                  convenience.phase === 'PENDING_ORDER'
              "
              style="margin-right:16px"
              type="primary"
              @click="handleUpdate(5)"
              ><i class="icon_jd" />接单</el-button
            >
            <el-button
              v-if="
                convenience &&
                  convenience.isSelf &&
                  convenience.statusList[0] &&
                  convenience.statusList[0].status !== 'SUBMIT_APPLY' &&
                  convenience.phase === 'PREREQUISITES' &&
                  convenience.statusList[0].status !== 'FORWARDED_APPLY' &&
                  convenience.statusList[0].status !== 'FORWARDED'
              "
              style="margin-right:16px"
              type="primary"
              @click="handleUpdate(6)"
              ><i class="icon_yj" />要件齐备，开始办理</el-button
            >
            <el-button
              v-if="
                convenience &&convenience.isSelf &&
                  convenience.phase !== 'FINISH' &&
                  convenience.phase === 'PROCESSING' &&
                  convenience.statusList[0].status !== 'SUBMIT_APPLY' &&
                  convenience.statusList[0].status !== 'FORWARDED_APPLY' &&
                  convenience.statusList[0].status !== 'WAIT_APPLY' &&
                  convenience.statusList[0].status !== 'FORWARDED'
              "
              style="margin-right:16px;"
              type="primary"
              @click="handleUpdate(7)"
            >
              <i class="icon_bj" />
              办结
            </el-button>

            <el-button
              v-if="
                convenience &&convenience.isSelf &&
                  convenience.statusList[0] &&
                  convenience.phase !== 'FINISH' &&
                  convenience.statusList[0].status !== 'WAIT_APPLY' &&
                  convenience.statusList[0].status !== 'SUBMIT_APPLY' &&
                  convenience.statusList[0].status !== 'FORWARDED_APPLY' &&
                  convenience.statusList[0].status !== 'FORWARDED'
              "
              style="margin-right:16px;"
              type="primary"
              @click="handleApprovalReminder(11)"
              ><i class="icon_sh" />发起审批</el-button
            >

            <el-button
              v-if="
                convenience &&convenience.isSelf &&
                  convenience.statusList[0] &&
                  convenience.phase !== 'FINISH' &&
                  convenience.statusList[0].status !== 'SUBMIT_APPLY' &&
                  convenience.statusList[0].status !== 'FORWARDED_APPLY' &&
                  convenience.statusList[0].status !== 'FORWARDED' &&
                  convenience.statusList[0].status !== 'WAIT_APPLY'
              "
              type="primary"
              @click="handleUpdate(14)"
              ><i class="icon_zj" />转交任务</el-button
            >
          </div>
        </div>
        <div class="hr" />
        <el-row :gutter="20" style="color:#787878;margin-bottom:30px">
          <el-col :span="6">
            <div>流水号：{{ convenience && convenience.serialNumber }}</div>
          </el-col>

          <el-col :span="6"
            ><div>
              申办人：{{ convenience && convenience.residentInformation.name }}
            </div></el-col
          >
          <el-col :span="6"
            ><div>
              受理人：{{
                convenience && convenience.firstResponsiblePerson.name
              }}
            </div></el-col
          >
          <el-col :span="6" style="text-align:right">
            总办理时长：<i class="icon_timer" /><span class="text_timer">
              {{
                `${
                  this.totalTime.hour > 9
                    ? this.totalTime.hour
                    : this.totalTime.hour
                }:${
                  this.totalTime.minute > 9
                    ? this.totalTime.minute
                    : this.totalTime.minute
                }:${
                  this.totalTime.second > 9
                    ? this.totalTime.second
                    : this.totalTime.second
                }`
              }}
            </span>
          </el-col>
        </el-row>
        <el-row
          :gutter="20"
          style="color:#787878;display: flex;align-items: center;"
        >
          <el-col
            :span="6"
            style="display: flex;align-items: center;flex-direction:column"
          >
            <div
              v-if="convenience && convenience.isSelf && convenience.statusList[0] "
              style="width:100%;display: flex;align-items: center;"
              class="status_btn"
            >
              任务状态：<span style="color:#ff5a00">{{
                convenience && convenience.statusList[0].status | statusFilter
              }}</span>
              <el-popover
                placement="top"
                width="160"
                v-model="cxPop"
                v-if="
                  convenience &&
                    convenience.phase !== 'FINISH' &&
                    convenience.statusList[0].status === 'SUBMIT_APPLY'
                "
              >
                <p>确定撤销审批吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="cxPop = false"
                    >取消</el-button
                  >
                  <el-button
                    type="primary"
                    size="mini"
                    @click="handleUpdate(12)"
                    >确定</el-button
                  >
                </div>
                <el-button
                  slot="reference"
                  type="primary"
                  style="margin-left:10px"
                  >撤回</el-button
                >
              </el-popover>

              <el-button
                v-if="
                  convenience && convenience.isSelf &&
                    convenience.phase !== 'FINISH' &&
                    convenience.statusList[0].status === 'FORWARDED_APPLY' &&
                    convenience &&
                    convenience.applyType === 'FORWARDED'
                "
                style="margin-left:10px"
                type="primary"
                @click="handleUpdate(9)"
                >撤销转交审批</el-button
              >

              <div
                v-if="
                  convenience && convenience.isSelf &&
                    convenience.statusList[0].status === 'WAIT_APPLY'
                "
                style="margin-left:10px"
              >
                <el-button type="success" @click="handleApprove(true)"
                  >通过</el-button
                ><el-button type="danger" @click="handleApprove(false)"
                  >驳回</el-button
                >
              </div>
            </div>
          </el-col>
          <el-col
            :span="6"
            style="display:flex"
            class="appeal"
            v-if="convenience && convenience.isSelf && convenience.evaluation"
          >
            <div>
              办事评价：
              {{ convenience && convenience.evaluation | evaluationFilter }}
            </div>
            <el-button
              type="primary"
              style="position: relative;top: -10px;left: 20px;"
              @click="handleUpdate(16)"
              >申诉</el-button
            ></el-col
          >
        </el-row>
        <el-row>
          <el-col
            :span="24"
            style="display: flex;align-items: center;flex-direction:column"
          >
            <ul v-if="convenience" class="approveUl">
              <li v-for="(item, index) in convenience.applyVoList" :key="index">
                <el-tag type="info" style="display: flex;align-items: center;"
                  ><i
                    :class="{
                      icon_approve: true,
                      approve_pass: item.approve,
                      approve_null: item.approve === null,
                      approve_no: !item.approve
                    }"
                  />{{
                    `${item.residentInformation.name}${
                      item.approve
                        ? "已同意"
                        : item.approve === null
                        ? "审批中"
                        : "已驳回"
                    }`
                  }}</el-tag
                >
              </li>
            </ul>
          </el-col>
        </el-row>

        <el-row class="text-center acceptanceOptionsLayout">
          <el-col :span="8">
            <i class="a_times icon_acceptance" />
            <p>受理</p>
            <div class="timerDiv">
              <div class="text_left">承诺时长 24小时内</div>
              <div>
                实际时长
                <span class="duration">{{
                  `${
                    this.acceptanceTime.hour > 9
                      ? this.acceptanceTime.hour
                      : this.acceptanceTime.hour
                  }:${
                    this.acceptanceTime.minute > 9
                      ? this.acceptanceTime.minute
                      : this.acceptanceTime.minute
                  }:${
                    this.acceptanceTime.second > 9
                      ? this.acceptanceTime.second
                      : this.acceptanceTime.second
                  }`
                }}</span
                ><span
                  v-if="acceptanceMsec > 57600 && acceptanceMsec < 86400"
                  class="timeout"
                  ><i class="icon_timeout" />即将超时</span
                >
                <span v-if="acceptanceMsec > 86400" class="timeout"
                  ><i class="icon_timeout" />已超时</span
                >
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="line_left" />
            <div class="line_right" />
            <i class="a_times icon_prepare" />
            <p>要件准备</p>
            <div class="timerDiv">
              <div>承诺时长 尽快</div>
              <div>
                实际时长
                <span class="duration">{{
                  `${
                    this.prerequisitesTime.hour > 9
                      ? this.prerequisitesTime.hour
                      : this.prerequisitesTime.hour
                  }:${
                    this.prerequisitesTime.minute > 9
                      ? this.prerequisitesTime.minute
                      : this.prerequisitesTime.minute
                  }:${
                    this.prerequisitesTime.second > 9
                      ? this.prerequisitesTime.second
                      : this.prerequisitesTime.second
                  }`
                }}</span>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <i class="a_times icon_finish" />
            <p>办结</p>
            <div class="timerDiv">
              <div class="text_left">
                法定时长
                {{ convenience && convenience.eventType.legalTimeLimit }}小时内
              </div>
              <div class="text_left">
                承诺时长
                {{
                  convenience && convenience.eventType.commitmentTimeLimit
                }}小时内
              </div>
              <div class="text_left">
                实际时长
                <span class="duration">
                  {{
                    `${
                      this.finishTime.hour > 9
                        ? this.finishTime.hour
                        : this.finishTime.hour
                    }:${
                      this.finishTime.minute > 9
                        ? this.finishTime.minute
                        : this.finishTime.minute
                    }:${
                      this.finishTime.second > 9
                        ? this.finishTime.second
                        : this.finishTime.second
                    }`
                  }}
                </span>
                <span
                  v-if="
                    finishMsec >=
                      (convenience &&
                        convenience.eventType.commitmentTimeLimit * 3600)
                  "
                  class="timeout"
                  ><i class="icon_timeout" />已超时</span
                >
                <span
                  v-else-if="
                    finishMsec >=
                      (convenience &&
                        convenience.eventType.timeoutReminder * 3600)
                  "
                  class="timeout"
                  ><i class="icon_timeout" />即将超时</span
                >
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <div class="recordLayout">
      <div style="border-left:5px solid #1890ff;padding-left:5px;float: left;">
        任务处理流程
      </div>
      <div style="float: right">
        <el-button
          v-if="
            convenience && convenience.isSelf && convenience.phase !== 'FINISH'
          "
          type="primary"
          style="margin-right:73px;"
          @click="handleContact"
          >发起沟通</el-button
        >
      </div>

      <div class="timeLine">
        <el-timeline v-if="convenience">
          <el-timeline-item
            v-for="(item, index) in convenience.records"
            :key="index"
            :timestamp="item.createDate | parseTime('{y}-{m}-{d} {h}:{i}:{s}')"
            placement="top"
            ><i
              v-if="convenience.residentInformation.id === item.from.id"
              class="timeLine_self"
            ></i
            ><i v-else class="timeLine_staff"></i>
            <i
              class="timeline_avatar"
              :style="{
                background: 'url(' + item.from.avatar + ')'
              }"
            />

            <el-card
              shadow="never"
              :class="{
                contact_staff:
                  convenience.residentInformation.id !== item.from.id,
                contact_self:
                  convenience.residentInformation.id === item.from.id
              }"
            >
              <h3>{{ item.content }}</h3>

              <p v-if="item.type === 11">审批人：{{ getNames(item.to) }}</p>

              <p v-for="(file, index) in item.attachmentList" :key="index">
                <i
                  v-if="convenience.residentInformation.id === item.from.id"
                  class="icon_fujian_self"
                /><i v-else class="icon_fujian" />

                <!-- file -->

                <span
                  v-if="
                    isAssetTypeAnAudio(file.substr(file.lastIndexOf('.') + 1))
                  "
                  @click="handleSetAudio(file)"
                  >{{ file }}</span
                >
                <span
                  v-if="
                    isAssetTypeAnImage(file.substr(file.lastIndexOf('.') + 1))
                  "
                  @click="handleSetPreviewImg(file)"
                  >{{ file }}</span
                >

                <el-link v-else :href="file" :underline="false" target="_blank">
                  {{ file.substring(file.lastIndexOf("/") + 1) }}
                </el-link>
                <!-- <span
                  v-if="
                    isAssetTypeAnImage(
                      attachment.substr(attachment.lastIndexOf('.') + 1)
                    )
                  "
                  style="cursor: pointer"
                  @click="handleSetPreviewImg(attachment)"
                >
                  <i
                    v-if="convenience.residentInformation.id === item.from.id"
                    class="icon_fujian_self"
                  /><i v-else class="icon_fujian" />
                  {{ attachment.substring(attachment.lastIndexOf("/") + 1) }}
                </span>

                <span
                  v-else-if="
                    isAssetTypeAnAudio(
                      attachment.substr(attachment.lastIndexOf('.') + 1)
                    )
                  "
                  @click="handleSetAudio(attachment)"
                >
                </span>
                
                <el-link
                  v-else
                  :href="attachment"
                  :underline="false"
                  target="_blank"
                >
                  <i
                    v-if="convenience.residentInformation.id === item.from.id"
                    class="icon_fujian_self"
                  /><i v-else class="icon_fujian" />
                  {{ attachment.substring(attachment.lastIndexOf("/") + 1) }}
                </el-link> -->
              </p>
              <p v-if="item.type === 13 || item.type === 10">
                审批结果：{{ item.approve ? "通过" : "驳回" }}
              </p>
              <p v-if="item.frequency">
                已转交次数：{{ item.frequency }}
                <span
                  v-if="item.type === 14 || item.type === 8"
                  style="margin-left:164px"
                  >被转交人：{{
                    item.type === 14
                      ? item.to[0].name
                      : item.type === 8
                      ? item.to[1].name
                      : item.to[0].name
                  }}</span
                >
              </p>
              <p v-if="item.type === 8">
                转交超限审批人：{{ item.to[0].name }}
              </p>
              <p v-if="item.type === 1">
                办事项目：{{ convenience && convenience.eventType.eventName }}
              </p>
              <p v-if="item.remark && item.type !== 4">
                {{
                  item.type === 11
                    ? "审批备注："
                    : item.type === 14
                    ? "转交备注："
                    : item.type === 1
                    ? "文字说明："
                    : "备注："
                }}{{ item.remark }}
              </p>
              <p
                style="line-height:25px"
                v-if="item.type === 4"
                v-html="item.remark.replace(/\n/g, '<br/>')"
              ></p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>

    <el-dialog
      :visible.sync="dialogPreviewImg"
      width="500px"
      title="预览"
      :destroy-on-clos="true"
    >
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>

    <el-dialog
      :visible.sync="dialogAudio"
      width="500px"
      title="预览"
      :destroy-on-clos="true"
      @close="handleClose"
    >
      <video
        id="myVideo"
        :src="dialogAudioSrc"
        controls
        autoplay
        width="100%"
      />
    </el-dialog>

    <el-dialog
      class="dialog"
      center
      width="434px"
      append-to-body
      :visible.sync="contactDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div slot="title" class="dialog-title">
        <span class="title-text">发起沟通</span>
      </div>
      <div class="preview-container">
        <el-form
          ref="contractForm"
          style="width:100%"
          :rules="rules"
          :model="payload"
        >
          <!-- <el-form-item label="选择被沟通人" prop="ids">
            <el-select
              v-model="payload.ids"
              multiple
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in communicationOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="请输入沟通内容" prop="remark">
            <el-input
              v-model="payload.remark"
              type="textarea"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item prop="attachmentList">
            <AliOss v-model="payload.attachmentList" multiple />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="default" @click="contactDialog = false"
          >取消</el-button
        >
        <el-button type="primary" @click="createContact">提交</el-button>
      </span>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="confirmDialog" width="434px" center>
      <div style="text-align: center;line-height: 25px;">
        转交次数已经超限，继续转交会提交转交超限审批，
      </div>
      <div style="text-align: center;line-height: 25px;">是否要继续转交？</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="confirmDialog = false">取消</el-button>
        <el-button type="primary" @click="handleContinue">继续转交</el-button>
      </span>
    </el-dialog>

    <el-dialog
      class="dialog"
      :title="updateType | typeFilter"
      append-to-body
      center
      width="434px"
      :visible.sync="applyDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="preview-container">
        <el-form ref="updateForm" style="width:100%" :rules="rules">
          <el-form-item label="选择行政区域" v-if="updateType !== 6&&updateType!==7">
            <el-cascader
              class="filter-item"
              v-model="regionSearchVal"
              style="width:100%"
              :options="regions"
              :show-all-levels="false"
              @change="handleRegionChange"
              placeholder="行政区域"
              clearable
            />
          </el-form-item>

          <el-form-item
            v-if="updateType === 8 || updateType === 11"
            label="选择审批人"
          >
            <span
              v-if="!staffOptions.length > 0"
              style="font-size:12px;color:red"
              >该行政区域下无工作人员</span
            >
            <el-select
              v-model="spr"
              placeholder="请选择"
              style="width:100%"
              :multiple="updateType !== 8"
              @change="handleChange"
            >
              <el-option
                v-for="item in staffOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            v-if="updateType === 8 || updateType === 14"
            label="选择被转交人"
          >
            <span
              v-if="!staffOptions.length > 0"
              style="font-size:12px;color:red"
              >该行政区域下无工作人员</span
            >
            <el-select v-model="bzjr" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in staffOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <!-- <el-form-item v-if="updateType === 13">
            <el-radio-group v-model="payload.approve">
              <el-radio :label="true">通过</el-radio>
              <el-radio :label="false">拒绝</el-radio>
            </el-radio-group>
          </el-form-item> -->

          <el-form-item
            :label="
              `${
                convenience &&
                convenience.statusList[0] &&
                convenience.statusList[0].status === 'WAIT_APPLY'
                  ? '请输入不通过理由'
                  : updateType === 16
                  ? '申诉理由'
                  : '备注'
              }`
            "
          >
            <el-input
              v-model="payload.remark"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 4 }"
              placeholder="请输入"
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="default" @click="applyDialog = false">取消</el-button>
        <el-button type="primary" @click="apply">提交</el-button>
        <!-- <el-button
          type="primary"
          :disabled="JSON.stringify(spr) === '[]'"
          @click="apply"
          >提交</el-button
        > -->
      </span>
    </el-dialog>

    <el-dialog
      title="提示"
      :visible.sync="dialogApprovalReminder"
      width="30%"
      center
    >
      <div class="text-center">
        {{ convenience && convenience.eventType.approvalReminder }}
      </div>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="centerDialogVisible = false">取 消</el-button> -->
        <el-button type="primary" @click="handleConfirmApprovalReminder"
          >发起审批</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  add,
  info,
  communicationList,
  update,
  typeList
} from "@/api/convenience";
import { parseTime } from "@/utils";
import { staffList } from "@/api/staff";
import AliOss from "@/components/AliOSS/index.vue";
import { getRegions } from "@/api/region";
import { mapGetters } from "vuex";

export default {
  filters: {
    sponsorFilter(status) {
      const statusMap = {
        SELF: "群众",
        STAFF: "工作人员"
      };
      return statusMap[status];
    },
    phaseFilter(status) {
      const statusMap = {
        PENDING_ORDER: "待接单",
        PREREQUISITES: "要件准备中",
        PROCESSING: "办理中",
        FINISH: "办结"
      };
      return statusMap[status];
    },
    statusFilter(status) {
      const statusMap = {
        MINE: "我处理",
        FORWARDED: "已转交",
        FORWARDED_APPLY: "转交超限审批中",
        SUBMIT_APPLY: "已提交审批",
        WAIT_APPLY: "待审核"
      };
      return statusMap[status];
    },
    typeFilter(status) {
      const statusMap = {
        1: "建立工单",
        2: "撤销工单",
        3: "沟通",
        4: "调整工单类别",
        5: "接单",
        6: "要件齐备",
        7: "办结",
        8: "转交超限审批提交",
        9: "转交超限审批撤销",
        10: "转交超限审批",
        11: "发起审批",
        12: "撤销审批",
        13: "审批操作",
        14: "转交",
        16: "提示"
      };
      return statusMap[status];
    },
    evaluationFilter(status) {
      const statusMap = {
        1: "不满意",
        2: "满意",
        3: "非常满意"
      };
      return statusMap[status];
    }
  },
  computed: {
    ...mapGetters(["regionIds"])
  },
  components: {
    AliOss
  },
  data() {
    return {
      id: this.$route.query.id,
      convenience: undefined,
      contactDialog: false,
      remark: undefined,
      fileList: [],
      payload: {
        id: this.id,
        version: undefined,
        ids: [],
        remark: undefined,
        attachmentList: undefined,
        approve: undefined,
        evaluation: undefined
      },
      rules: {
        ids: [{ required: true, message: "请选择操作对象", trigger: "change" }]
      },
      updateType: undefined,
      communicationOptions: [],
      staffOptions: [],
      confirmDialog: false,
      applyDialog: false,
      spr: [],
      bzjr: undefined,
      prerequisitesInterval: undefined,
      preMsec: 0,
      prerequisitesTime: {
        hour: "--",
        minute: "--",
        second: "--"
      },
      finishTimeInterval: undefined,
      finishMsec: 0,
      finishTime: {
        hour: "--",
        minute: "--",
        second: "--"
      },
      acceptanceInterval: undefined,
      acceptanceMsec: 0,
      acceptanceTime: {
        hour: "--",
        minute: "--",
        second: "--"
      },
      totalTimeInterval: undefined,
      totalMsec: 0,
      totalTime: {
        hour: "--",
        minute: "--",
        second: "--"
      },
      dialogPreviewImg: false,
      dialogImageUrl: undefined,
      dialogAudio: false,
      dialogAudioSrc: undefined,
      dialogApprovalReminder: false,
      dialogEventType: false,
      typeOptions: [],
      eventTypeId: undefined,
      applyDetail: false,
      isEventTypeChange: false,
      cxPop: false,
      audioSources: ["http://storage.myntv.cn/files20210415_142012.m4a"],
      regionSearchVal: [],
      regions: [],
      staffQuery: {
        regionIds: "",
        isAll: false,
        category: "CONVENIENCE"
      }
    };
  },
  created() {
    this.getInfo();
    this.getStaffList();
    // this.getCommunicationList();
    this.getTypeList();
    this.getRegionList();
  },
  methods: {
    getInfo() {
      info({ id: this.id }).then(res => {
        this.convenience = res.d;
        const tempData = Object.assign({}, this.convenience);
        const now = Date.parse(new Date()).toString() / 1000;
        clearInterval(this.acceptanceInterval);
        clearInterval(this.prerequisitesInterval);
        clearInterval(this.finishTimeInterval);
        clearInterval(this.totalTimeInterval);
        switch (tempData.phase) {
          // 待接单
          case "PENDING_ORDER":
            if (tempData.acceptanceTime === null) {
              this.acceptanceMsec = now - this.convenience.createDate;
              this.countdown(tempData.phase);
            }
            break;
          // 要件准备
          case "PREREQUISITES":
            if (tempData.prerequisitesTime === null) {
              this.preMsec =
                now - tempData.createDate - tempData.acceptanceTime;
              this.acceptanceMsec = tempData.acceptanceTime;
              this.timeFormat("acceptanceTime", this.acceptanceMsec);
              this.countdown(tempData.phase);
            }
            break;
          // 办理中
          case "PROCESSING":
            if (tempData.finishTime === null) {
              this.finishMsec =
                now -
                tempData.createDate -
                tempData.acceptanceTime -
                tempData.prerequisitesTime;
              this.acceptanceMsec = tempData.acceptanceTime;
              this.preMsec = tempData.prerequisitesTime;
              this.timeFormat("acceptanceTime", this.acceptanceMsec);
              this.timeFormat("prerequisitesTime", this.preMsec);
              this.countdown(tempData.phase);
            }
            break;
          // 办结
          case "FINISH":
            if (tempData.finishTime !== null) {
              this.finishMsec = tempData.finishTime;
              this.acceptanceMsec = tempData.acceptanceTime;
              this.preMsec = tempData.prerequisitesTime;
              this.timeFormat("acceptanceTime", this.acceptanceMsec);
              this.timeFormat("prerequisitesTime", this.preMsec);
              this.timeFormat("finishTime", this.finishMsec);

              this.countdown(tempData.phase);
            }
            break;
        }
      });
    },
    getTypeList() {
      typeList().then(res => {
        this.typeOptions = res.d;
        // this.typeOptions = [];
        // res.d.map(i => {
        //   const children = [];

        //   i.eventTypesList.map(c => {
        //     const level2 = {
        //       label: c.eventName,
        //       value: c.id
        //     };
        //     children.push(level2);
        //   });
        //   const level1 = {
        //     label: i.eventName,
        //     children
        //   };
        //   this.typeOptions.push(level1);
        // });
      });
    },
    countdown(phase) {
      if (phase === "PENDING_ORDER") {
        this.acceptanceInterval = setInterval(() => {
          this.timeFormat("acceptanceTime", this.acceptanceMsec);
          this.acceptanceMsec++;
        }, 1000);
        // 当前阶段的时间加上
        this.totalMsec = this.acceptanceMsec;
        this.totalTimeInterval = setInterval(() => {
          this.timeFormat("totalTime", this.totalMsec);
          this.totalMsec++;
        }, 1000);
      } else if (phase === "PREREQUISITES") {
        this.prerequisitesInterval = setInterval(() => {
          this.timeFormat("prerequisitesTime", this.preMsec);
          this.preMsec++;
        }, 1000);
        this.totalMsec = this.convenience.acceptanceTime + this.preMsec;
        this.totalTimeInterval = setInterval(() => {
          this.timeFormat("totalTime", this.totalMsec);
          this.totalMsec++;
        }, 1000);
      } else if (phase === "PROCESSING") {
        this.finishTimeInterval = setInterval(() => {
          this.timeFormat("finishTime", this.finishMsec);
          this.finishMsec++;
        }, 1000);
        this.totalMsec =
          this.convenience.acceptanceTime +
          this.convenience.prerequisitesTime +
          this.finishMsec;
        console.log(this.totalMsec);
        this.totalTimeInterval = setInterval(() => {
          this.timeFormat("totalTime", this.totalMsec);
          this.totalMsec++;
        }, 1000);
      } else if (phase === "FINISH") {
        this.finishMsec;
        this.totalMsec =
          this.convenience.acceptanceTime +
          this.convenience.prerequisitesTime +
          this.convenience.finishTime;
        this.timeFormat("totalTime", this.totalMsec);
      }
    },
    timeFormat(obj, timeStamp) {
      this[obj].hour =
        Math.floor(timeStamp / 3600) < 9
          ? "0" + Math.floor(timeStamp / 3600)
          : Math.floor(timeStamp / 3600);
      this[obj].minute =
        Math.floor(((timeStamp % 86400) % 3600) / 60) < 9
          ? "0" + Math.floor(((timeStamp % 86400) % 3600) / 60)
          : Math.floor(((timeStamp % 86400) % 3600) / 60);
      this[obj].second =
        Math.floor(((timeStamp % 86400) % 3600) % 60) < 9
          ? "0" + Math.floor(((timeStamp % 86400) % 3600) % 60)
          : Math.floor(((timeStamp % 86400) % 3600) % 60);
    },
    getCommunicationList() {
      communicationList({ id: this.id }).then(res => {
        res.d.map(item => {
          const obj = {
            label: item.name,
            value: item.id
          };
          this.communicationOptions.push(obj);
        });
      });
    },
    getStaffList() {
      let payload = Object.assign({}, this.staffQuery);
      let arr = payload.regionIds.split(",");
      arr.map((item, index) => {
        if (item === "false") {
          arr.splice(index, 1);
        }
      });
      payload.regionIds = arr.join(",");
      // console.log(payload);
      staffList(payload).then(res => {
        this.staffOptions = [];
        // staffList().then(res => {
        res.d.records.map(item => {
          const obj = {
            label: item.name,
            value: item.id
          };
          this.staffOptions.push(obj);
          console.log(this.staffOptions);
        });
      });
    },
    resetPayload() {
      this.payload = {
        id: undefined,
        version: undefined,
        ids: [],
        remark: undefined,
        attachmentList: undefined,
        approve: undefined,
        evaluation: undefined
      };
      this.spr = [];
      this.bzjr = undefined;
    },
    handleRevoke() {
      const payload = {
        id: this.id,
        version: this.convenience.version,
        type: 2
      };
      update(payload).then(res => {
        // console.log(res);
        this.$notify.success("撤销成功");
      });
    },
    handleContact() {
      this.resetPayload();
      this.$nextTick(() => {
        this.$refs.contractForm.clearValidate();
      });
      this.contactDialog = true;
      this.payload.type = 3;
      this.payload.id = this.id;
      this.payload.version = this.convenience.version;
    },
    getNames(arr) {
      const temp = [];
      arr.map(item => {
        temp.push(item.name);
      });
      return temp.join(",");
    },
    handlePreview() {},
    handleRemove() {},
    beforeRemove() {},
    handleExceed() {},
    createContact() {
      // this.resetPayload()
      // const payload = {
      //   id: this.id,
      //   version: this.convenience.version,
      //   type: 3,
      //   remark: this.remark
      //   // ids:
      // };
      // console.log(payload);
      this.$refs.contractForm.validate(valid => {
        if (valid) {
          update(this.payload).then(res => {
            // console.log(res);
            if (res.c === 200) {
              this.$notify.success("提交成功");
            }else{
              this.$notify.error(res.m)
            }
            this.getInfo();
            this.contactDialog = false;
          });
        }
      });
    },
    handleApprove(approve) {
      const applyType = this.convenience.applyType;
      this.updateType = applyType === "FORWARDED" ? 10 : 13;
      this.payload.id = this.convenience.id;
      this.payload.version = this.convenience.version;
      this.payload.type = this.updateType;
      this.payload.approve = approve;

      if (approve) {
        // console.log(this.payload);
        this.updateData();
      } else {
        this.applyDialog = true;
      }
      // id: this.id,
      //   version: undefined,
      //   ids: undefined,
      //   remark: undefined,
      //   attachmentList: undefined,
      //   approve: undefined,
      //   evaluation: undefined
    },
    setDefaultRegionSelectVal() {
      // console.log('swich');

      const tempLen = this.regionIds.split(",").length;
      this.regionSearchVal = [];
      this.staffQuery.regionIds = this.regionIds;
      switch (tempLen) {
        case 1:
          console.log(1);
          this.regionSearchVal.push(this.regionIds, false);

          console.log(this.regionSearchVal);
          break;
        case 2:
          console.log(2);
          this.regionSearchVal.push(this.regionIds, false);
          // console.log(this.regionSearchVal);
          break;
        case 3:
          console.log(3);
          this.regionSearchVal.push(this.regionIds);
          break;
        default:
          this.regionSearchVal = [];
          break;
      }
      this.getStaffList();
    },
    handleApprovalReminder() {
      // this.regionSearchVal = [];

      this.dialogApprovalReminder = true;
      // console.log(this.regionIds);
      this.setDefaultRegionSelectVal();
      // this.dialogApprovalReminder = true;
    },
    handleConfirmApprovalReminder() {
      this.dialogApprovalReminder = false;
      this.handleUpdate(11);
    },
    handleUpdate(type) {
      // console.log(type);
      this.resetPayload();
      this.updateType = type;
      this.payload.id = this.convenience.id;
      this.payload.version = this.convenience.version;
      this.payload.type = type;
      switch (type) {
        case 6:
          // 要件齐备
          this.applyDialog = true;
          break;
        case 7:
          // 办结
          this.applyDialog = true;
          break;
        case 10:
          // 转交超限审批
          // this.approve;
          break;
        case 11:
          // 发起审批
          this.applyDialog = true;
          break;

        // case 12:
        //   // 撤销审批
        //   break;

        case 13:
          // 审批操作
          this.applyDialog = true;
          break;
        case 14:
          // console.log("handle14");
          // 转交
          const frequencys = this.convenience.records.filter(
            m => m.frequency !== null
          );
          if (
            frequencys.filter(
              item =>
                item.frequency >=
                this.convenience.eventType.referralRestrictions
            ).length > 0
          ) {
            this.updateType = 8;
            this.confirmDialog = true;
          } else {
            this.updateType = 14;
            this.applyDialog = true;
          }
          this.setDefaultRegionSelectVal();
          break;
        case 16:
          // 评价申诉
          // this.applyDialog = true;
          this.$notify.warning("功能尚未开发完成，敬请期待");
          break;
        default:
          this.updateData();
          break;
      }
    },
    handleEventTypeChange(val) {
      this.payload = {
        id: this.id,
        type: 4,
        version: this.convenience.version,
        remark: val
      };
      this.updateType = 4;
      this.updateData();
    },
    handleChange(val) {
      // console.log(val1);
    },
    apply() {
      // this.$refs.updateForm.validate(valid=>{
      //   console.log(valid);
      // })
      // console.log(this.payload);
      // console.log(this.payload.type);
      this.updateData();
      this.applyDialog = false;
    },
    handleContinue() {
      setTimeout(() => {
        this.confirmDialog = false;
      }, 100);
      this.applyDialog = true;
    },
    updateData() {
      // console.log(this.updateType);
      switch (this.updateType) {
        case 6:
          break;
        case 8:
          this.payload.ids.push(this.spr);
          this.payload.ids.push(this.bzjr);
          this.payload.type = 8;
          break;
        case 11:
          this.payload.id = this.convenience.id;
          this.payload.version = this.convenience.version;
          this.payload.ids = this.spr;
          break;
        case 14:
          this.payload.type = 14;
          this.payload.ids.push(this.bzjr);
          break;
      }
      // this.$refs.updateForm.validate(valid => {
      //   console.log(valid);
      // });
      update(this.payload).then(res => {
        if (res.c === 200) {
          this.$notify.success("操作成功");
          if (this.updateType === 13) {
            this.$router.push("/convenience/list");
            return;
          }
          if (this.updateType === 4) {
            this.isEventTypeChange = false;
          }
          if (this.updateType === 12) {
            this.cxPop = false;
          }
          // if (this.updateType===12){
          //   this.$notify.success('撤销成功')
          // }
          // if(this.updateType===10||this.updateType===13){
          //   if(this.payload.approve){
          //     this.$notify.success('审批通过')
          //   }
          // }
          this.getInfo();
        }else{
              this.$notify.error(res.m)
            }
      });
    },
    isAssetTypeAnImage(ext) {
      return (
        ["png", "jpg", "jpeg", "bmp", "gif"].indexOf(ext.toLowerCase()) !== -1
      );
    },
    handleSetPreviewImg(imgurl) {
      this.dialogImageUrl = imgurl;
      this.dialogPreviewImg = true;
    },
    isAssetTypeAnAudio(ext) {
      // console.log(e);
      return ["m4a", "mp4", "mp3", "mov"].indexOf(ext.toLowerCase()) !== -1;
    },
    handleSetAudio(src) {
      this.dialogAudio = true;
      this.dialogAudioSrc = src;
    },
    handleClose() {
      // console.log('close');
      document.getElementById("myVideo").pause();
    },
    handleChangeEventType() {
      this.dialogEventType = true;
    },
    eventTypeUpdate() {
      this.payload = {
        id: this.id,
        type: 4,
        version: this.convenience.version,
        remark: this.eventTypeId
      };
      this.updateType = 4;
      this.updateData();
      this.dialogEventType = false;
    },
    cascader() {
      this.isEventTypeChange = !this.isEventTypeChange;

      this.$nextTick(() => {
        const tempRef = this.$refs.eventTypeRef;
        if (tempRef) tempRef.toggleMenu();
        // tempRef.$el.style.display = "inline-block";
        // this.$refs.eventTypeRef.focusFirstNode();
      }, 100);
    },
    getRegionList() {
      getRegions().then(res => {
        const tempData = res.d;
        const countyArr = []; // 县,1
        tempData.map(county => {
          const countyObj = {
            value: county.root.id,
            label: county.root.name,
            disabled: !county.root.check,
            // children: [{value:true,label:'全县'},{value:false,label:'本县'}],
            children: [
              {
                value: false,
                label: county.root.name,
                disabled: false
                // children: []
              }
            ]
          };
          countyArr.push(countyObj);
          county.node.map(town => {
            const townObj = {
              value: town.root.id,
              label: town.root.name,
              disabled: !town.root.check,
              // children: [{value:true,label:'全镇'},{value:false,label:'本镇'}],
              children: [
                {
                  value: false,
                  label: town.root.name,
                  disabled: false
                  // children: []
                }
              ]
            };
            countyObj.children.push(townObj);
            town.node.map(country => {
              townObj.children.push({
                value: country.root.id,
                label: country.root.name,
                disabled: !country.root.check
              });
            });
          });
        });
        this.regions = countyArr;
      });
    },
    handleRegionChange(val) {
      this.staffQuery.regionIds = val.join(",");
      this.getStaffList();
    }
  },
  beforeRouteLeave(to, from, next) {
    clearInterval(this.acceptanceInterval);
    clearInterval(this.prerequisitesInterval);
    clearInterval(this.finishTimeInterval);
    next();
  }
};
</script>

<style scope>
.convenienceInfo {
  padding: 40px 50px;
  margin-bottom: 10px;
}
.convenienceTitle {
  display: flex;
}
.icon_list {
  background: url("./img/icon_list.png") no-repeat;
  background-size: cover;
  display: inline-block;
  width: 52px;
  height: 51px;
  margin-right: 20px;
}
.icon_timer {
  background: url("./img/icon_timer.png") no-repeat;
  background-size: cover;
  display: inline-block;
  width: 18px;
  height: 18px;
  margin-right: 4px;
  vertical-align: baseline;
  margin-left: 24px;
}
.a_times {
  background-size: cover !important;
  width: 69px;
  height: 69px;
  display: inline-block;
}
.acceptanceOptionsLayout {
  display: flex;
  text-align: center;
  background-image: linear-gradient(#f9f9f9, #f9f9f9),
    linear-gradient(#f7f7f7, #f7f7f7);
  background-blend-mode: normal, normal;
  padding: 50px 132px;
  margin-top: 40px;
  color: #878787;
  position: relative;
}
.line_left {
  border-top: 4px solid #f2f2f2;
  position: absolute;
  left: 30%;
  width: 15%;
  top: 28%;
}
.line_right {
  border-top: 4px solid #f2f2f2;
  position: absolute;
  right: 30%;
  width: 15%;
  top: 28%;
}
.acceptanceOptionsLayout div p:nth-child(2) {
  color: #000000;
}
.icon_acceptance {
  background: url("./img/icon_acceptance.png") no-repeat;
}
.icon_finish {
  background: url("./img/icon_finish.png") no-repeat;
}
.icon_prepare {
  background: url("./img/icon_prepare.png") no-repeat;
}
.timeout {
  color: #ff3000;
  position: absolute;
}
.icon_timeout {
  width: 12px;
  height: 11px;
  display: inline-block;
  background: url("./img/icon_timeout.png") no-repeat;
  background-size: cover;
  margin-right: 5px;
  margin-left: 10px;
}
.eventType {
  font-size: 18px;
  color: #000000;
}
.text_timer {
  color: #ff6918;
  font-size: 20px;
}
.el-tag {
  font-size: 14px;
  margin-top: 3px;
}
.duration {
  color: #000000;
}
.hr {
  height: 3px;
  background-image: linear-gradient(#f9f9f9, #f9f9f9),
    linear-gradient(#c8c8c8, #c8c8c8);
  background-blend-mode: normal, normal;
  border-radius: 1px;
  margin-top: 25px;
  margin-bottom: 25px;
}
.timeline {
  background: #fff;
}
.el-icon-mores {
  background: url("./img/icon_acceptance.png") no-repeat;
}
.icon_fujian {
  background: url("./img/icon_fujian.png") no-repeat;
  background-size: cover;
  width: 32px;
  height: 32px;
  display: inline-block;
  vertical-align: top;
  margin-right: 12px;
}
.icon_fujian_self {
  background: url("./img/icon_fujian_self.png") no-repeat;
  background-size: cover;
  width: 32px;
  height: 32px;
  display: inline-block;
  vertical-align: top;
  margin-right: 12px;
}
.timeline_avatar {
  width: 73px;
  height: 74px;
  display: inline-block;
  border-radius: 73px;
  position: absolute;
  left: -32px;
  top: -28px;
  background-size: cover !important;
}
.el-timeline-item__wrapper {
  padding-left: 60px;
}
.contact_staff {
  background: #f7fafd;
}
.contact_self {
  background: #fff5f4;
}
.recordLayout {
  padding-top: 26px;
  background: #fff;
  /* margin-top: 25px; */
}
.timeLine {
  padding: 130px 73px;
}
.el-dialog__header {
  background: #f9fafc;
  border-radius: 4px;
}
.text_left {
  text-align: left;
}
.timerDiv {
  width: 137px;
  text-align: left;
  margin: 0 auto;
  line-height: 25px;
  margin-top: 25px;
}
.approveUl {
  list-style: none;
  padding-left: 0;
  display: inline-block;
  line-height: 30px;
  width: 100%;
  padding: 0 80px;
}
.approveUl > li {
  /* width: 50%; */
  margin-right: 10px;
  float: left;
}
.icon_approve {
  width: 19px;
  height: 19px;
  display: inline-block;
  vertical-align: middle;
  margin-right: 5px;
}
.approve_pass {
  background: url("./img/approve_pass.png") no-repeat;
  background-size: cover;
}
.approve_no {
  background: url("./img/approve_no.png") no-repeat;
  background-size: cover;
}
.approve_null {
  background: url("./img/approve_null.png") no-repeat;
  background-size: cover;
}
/* .timeLine > .el-card {
  border-radius: 0;
  border: none;
}
.timeLine > .el-card__body {
  padding: 5px 48px;
} */
.contact_staff {
  border: none;
  color: #787878;
}
.contact_self {
  border: none;
  color: #787878;
}
.contact_staff > .el-card__body {
  padding: 20px 48px 15px 48px;
}
h3 {
  color: #000000;
}
.el-timeline-item__content {
  margin-bottom: 63px;
}
.el-timeline-item__timestamp.is-top {
  margin-bottom: 22px;
}
/* .el */
.el-timeline-item__timestamp {
  color: #787878;
  padding-left: 25px;
}
.approveUl > li > .el-tag.el-tag--info {
  background-color: #f9f9f9;
  border: 0;
  color: #787878;
  height: 42px;
  border-radius: 10px;
}
.icon_zj {
  background: url("./img/icon_zj.png") no-repeat;
  width: 21px;
  height: 19px;
  display: inline-block;
  background-size: cover;
  margin-right: 6px;
  vertical-align: top;
}
.icon_edit {
  background: url("./img/icon_edit.png") no-repeat;
  width: 16px;
  height: 16px;
  display: inline-block;
  background-size: cover;
  margin-right: 3px;
  vertical-align: top;
}
.icon_sh {
  background: url("./img/icon_sh.png") no-repeat;
  width: 19px;
  height: 20px;
  display: inline-block;
  background-size: cover;
  margin-right: 6px;
  vertical-align: top;
}
.icon_bj {
  background: url("./img/icon_bj.png") no-repeat;
  width: 20px;
  height: 14px;
  display: inline-block;
  background-size: cover;
  margin-right: 4px;
  /* vertical-align: top; */
}
.timeLine_staff {
  background: url("./img/timeLine_staff.png") no-repeat;
  background-size: cover;
  display: inline-block;
  width: 16px;
  height: 16px;
  position: absolute;
  top: 2px;
}
.timeLine_self {
  background: url("./img/timeLine_self.png") no-repeat;
  background-size: cover;
  display: inline-block;
  width: 16px;
  height: 16px;
  position: absolute;
  top: 2px;
}
.icon_jd {
  background: url("./img/icon_jd.png") no-repeat;
  width: 20px;
  height: 19px;
  display: inline-block;
  background-size: cover;
  margin-right: 4px;
  vertical-align: top;
}
.icon_yj {
  background: url("./img/icon_yj.png") no-repeat;
  width: 17px;
  height: 19px;
  display: inline-block;
  background-size: cover;
  margin-right: 7px;
  vertical-align: top;
}
/* .el-cascader-panel{
  display: -webkit-inline-box;
} */
</style>
