<template>
  <a-layout :class="$style.page">
    <a-layout-header :class="$style.header">
      <div :class="$style.headerTitle" :title="jfName" v-if="ifRouterView">{{ jfName }} </div>
    </a-layout-header>
    <a-layout style="padding: 20px 20px 20px 0">
      <a-layout-sider
        theme="light"
        width="200"
        :class="[
          fold ? $style.leftSiderHidden : null,
          $style.leftSider,
          { [$style.leftOver]: !fold },
        ]"
        style="padding: 0; background: #fff"
      >
        <div :class="$style.siderContent">
          <div :class="[$style.siderTitleDivFirst, { checked: checkedId === 'regist' }]">
            <div :class="$style.siderTitle" @click="setChecked('regist', djurl, 'regist')">
              <a-icon
                type="profile"
                :class="[checkedId === 'regist' ? 'checkedpro' : 'nocheckedpro']"
              />
              纠纷登记
            </div>
          </div>
        </div>
        <div :class="$style.siderContent">
          <div :class="[$style.siderTitleDiv, { checkedpro: projectStage === 'progress' }]">
            <div :class="$style.siderTitle">
              <a-icon
                type="profile"
                :class="[projectStage === 'progress' ? 'checkedpro' : 'nocheckedpro']"
              />
              纠纷进展
              <a-icon
                :type="'plus-circle'"
                @click="addProgress('')"
                :class="[
                  $style.changeStatus,
                  { checkedpro: projectStage === 'progress' },
                  { nocheckedpro: projectStage !== 'progress' },
                ]"
                v-if="(projectStage === 'progress' && djuserflag) || deleteflagprogress"
              />
            </div>
          </div>
          <a-spin :spinning="spinning">
            <a-timeline :class="[spinning ? $style.timeline : '']">
              <div
                v-for="node in ProgressNodes"
                :key="node.id"
                :class="[$style.siderUlDiv, { checked: checkedId === node.id }]"
                @click="setChecked(node.id, node.nodeUrl, 'progress')"
              >
                <table style="border: none; width: 100%; border-bottom: 2px solid #e8e8e8">
                  <tr>
                    <td width="70%"
                      ><a-timeline-item :class="$style.siderLi">{{
                        node.nodeName
                      }}</a-timeline-item></td
                    >
                    <td width="30%" style="text-align: right; padding-right: 15px">
                      <a-icon
                        type="delete"
                        @click="deleteProgress(node)"
                        :class="[$style.deletePro]"
                        v-show="node.nodeUrl.indexOf('/draft/') > -1"
                    /></td>
                  </tr>
                  <tr>
                    <td colspan="2">
                      <span :class="$style.siderLi">{{ node.creationTime }}</span>
                    </td>
                  </tr>
                </table>
              </div>
            </a-timeline>
          </a-spin>
        </div>
        <div :class="$style.siderContent" v-show="jaurl !== ''">
          <div :class="[$style.siderTitleDiv, { checked: checkedId === 'finish' }]">
            <div :class="$style.siderTitle" @click="setChecked('finish', jaurl, 'finish')">
              <a-icon type="profile" />
              纠纷结案
            </div>
          </div>
        </div>
      </a-layout-sider>
      <a-layout-sider width="20" style="background: #f0f2f5">
        <a-button type="primary" :class="$style.fold" @click="foldClick">
          <a-icon :type="fold ? 'right' : 'left'" />
        </a-button>
      </a-layout-sider>
      <a-layout
        style="padding: 0px; background: #fff"
        :class="['sd-has-table', $style.lawprogress]"
      >
        <iframe
          v-show="ifRouterView"
          :src="frameSrc"
          frameborder="0"
          style="height: 100%"
          name="sdEasyflowIframe"
          :key="key"
        ></iframe>
      </a-layout>
    </a-layout>
    <a-modal
      :title="'纠纷进展阶段'"
      :mask-closable="false"
      :visible="visible"
      :width="800"
      :confirm-loading="confirmLoading"
      destroy-on-close
      cancel-text="取消"
      ok-text="确定"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model :model="interForm" :label-col="{ span: 7 }" :wrapper-col="{ span: 15 }">
        <a-form-model-item label="阶段名称" required>
          <a-select v-model="interForm.stageField">
            <a-select-option v-for="item in stage" :key="item.code" :value="item.code">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-layout>
</template>

<script>
import { message, Modal } from 'ant-design-vue'
import moment from 'moment'
import LawService from '../law-service'
import components from './_import-components/law-progress-page-import'
import FlowcenterService from '@/flowcenter/flowcenter-service'
import { getUserInfo } from '@/common/store-mixin'

export default {
  name: 'LawProgressPage',
  metaInfo: {
    title: '纠纷作业',
  },
  components: {
    ...components,
  },
  mixins: [],
  provide() {
    return {
      reload: this.reload,
    }
  },
  data() {
    return {
      key: 0,
      djuserflag: false,
      visible: false,
      confirmLoading: false,
      stage: [],
      interForm: {
        stageField: '',
      },
      ifRouterView: true,
      fold: false,
      spinning: true, // 左侧节点加载状态
      jfId: '', // 纠纷Id
      overProjectId: '', // 结案Id
      projectStatus: '',
      checkedId: '', // 默认选中节点id
      // 案件进展
      ProgressNodes: [],
      projectStage: 'regist', // 纠纷登记1 进展2 结案3
      jfName: '', // 纠纷名称,
      currentUserType: [], // 当前登录人所在分案角色
      type: '',
      todoId: '',
      moduleId: '',
      formListId: '',
      Expressions: [],
      // id: '',
      flag: true,
      frameSrc: '',
      jfinfo: [],
      djurl: '',
      jaurl: '',
      refreshflag: true,
      jfjzid: '',
      deleteflagprogress: false,
    }
  },
  mounted() {
    this.projectStage = this.$route.query.zt
    this.jfId = this.$route.query.id
    const path = this.$route.fullPath.replace('/law-progress-page', '/sd-webflow')
    this.frameSrc = '#' + path
    LawService.getAlljfStage().then((res) => {
      const stage = []
      res.data.data.forEach((d) => {
        stage.push({
          name: d.STAGE_NAME,
          code: d.STAGE_CODE,
          businessTypeId: d.text0,
        })
      })
      this.stage = [...stage]
      this.initData(this.jfId)
      // djuserflag 当前人是否是案件登记人？
      const currentUser = getUserInfo().account
      LawService.getBeanByFormId(this.jfId, 'onl:5713a67680d34e73bd593844929e707a').then((res) => {
        const user = res.data.pageFormData.pageFieldInfos.find((o) => o.name === 'REGISTER_USER')
        if (user) {
          const userobj = JSON.parse(user.value)
          if (userobj[0].code === currentUser) {
            this.djuserflag = true
          }
        }
      })
    })
    // $(window).unbind('beforeunload')
    window.onbeforeunload = null
  },
  destroyed() {
    window.removeEventListener('hasLeaderAuthority', this.hasLeaderAuthority)
    // window.removeEventListener('unload', this.onPageUnload)
  },
  methods: {
    fnclose() {
      // href="javascript:window.opener=null;window.open('','_self');window.close();"
      window.opener = null
      window.open('', '_self')
      window.close()
    },
    onPageUnload(res) {
      if (res.data.url !== undefined) {
        const fullPath = res.data.url
        let zt = '2'
        if (res.data.type === 'jfFinish') {
          zt = '3'
        }
        // if (res.data.type.indexOf('close') > -1) {
        LawService.getProgressData(this.jfId).then((res1) => {
          const progress = []
          if (res1.data.length > 1) {
            if (res1.data[1].children && res1.data[1].children.length > 0) {
              res1.data[1].children.forEach((p) => {
                const timeStamp = p.props.creationTime
                const date = new Date(timeStamp * 1)
                progress.push({
                  id: p.id,
                  nodeUrl: p.props.detailUrl + '/' + p.props.detailInstid,
                  nodeName: p.props.stepName,
                  stepStatus: p.props.stepStatus,
                  creationTime: moment(date).format('YYYY-MM-DD'),
                  instId: p.props.detailInstid,
                })
              })
            }
            this.jfjzid = res1.data[1].id
            this.ProgressNodes = [...progress]
            if (res1.data.length > 1 && res1.data.at(-1).props.stepType === 'finish') {
              this.jaurl =
                res1.data.at(-1).props.detailUrl + '/' + res1.data.at(-1).props.detailInstid
            }
            let url = ''
            if (res.data.type.indexOf('jfFinish') > -1) {
              this.projectStage = 'finish'
              this.checkedId = 'finish'
              url = this.jaurl
            } else {
              this.projectStage = 'progress'
              this.checkedId = progress[progress.length - 1].id
              url = progress[progress.length - 1].nodeUrl
            }
            if (url.indexOf('&id') === -1) {
              url = url + '?zt=' + this.projectStage + '&id=' + this.jfId
            }
            this.frameSrc = url + '&t=' + Math.random()
            url = url.replace('/sd-webflow', '/law-progress-page')
            window.location.href = url + '&t=' + Math.random()
            this.key = this.key + 1
            this.reload()
          }
        })
        // } else {
        //   let url = fullPath.replace('/sd-webflow', '/law-progress-page')
        //   if (url.indexOf('&id') === -1) {
        //     url = url + '?zt=' + zt + '&id=' + this.jfId
        //   }
        //   fullPath = url
        //   window.location.href = fullPath // 改为新窗口打开之后，直接本窗口跳转，防止系统内打开多余页签
        //   if (zt === 'progress') {
        //     const obj = this.ProgressNodes.find((i) => i.id === '0')
        //     obj.nodeUrl = res.data.url
        //     const urls = res.data.url.split('/')
        //     obj.instId = urls[urls.length - 1]
        //     obj.id = obj.instId
        //     this.checkedId = obj.id
        //   } else if (zt === 'finish') {
        //     this.jaurl = res.data.url
        //   }
        // }
      }
    },
    deleteProgress(node) {
      if (node.instId === '0') {
        // Modal.warning({
        //   title: '提示',
        //   content: '当前页面还未存在后端，无需删除',
        // })
        this.ProgressNodes.pop()
        let url = ''
        if (this.ProgressNodes.length > 0) {
          this.frameSrc = this.ProgressNodes[this.ProgressNodes.length - 1].nodeUrl
          this.projectStage = 'progress'
          this.checkedId = this.ProgressNodes[this.ProgressNodes.length - 1].id
          url = this.ProgressNodes[this.ProgressNodes.length - 1].nodeUrl
        } else {
          this.frameSrc = this.djurl
          this.projectStage = 'progress'
          url = this.djurl
          this.deleteflagprogress = true
        }
        url =
          url.replace('sd-webflow', 'law-progress-page') +
          '?zt=' +
          this.projectStage +
          '&id=' +
          this.jfId
        window.location.href = url
      } else {
        const instIds = []
        instIds.push(node.instId)
        Modal.confirm({
          title: '你确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            // this.loading = true
            const params = {
              flowCallbackBeanName: 'formBeanCleanerCallBack',
              processInstanceIds: instIds.join(','),
            }
            FlowcenterService.fnDarftsDelete(params)
              .then((res) => {
                if (res.status === 200) {
                  message.success('删除成功')
                  this.ProgressNodes.pop()
                  let url = ''
                  if (this.ProgressNodes.length > 0) {
                    this.frameSrc = this.ProgressNodes[this.ProgressNodes.length - 1].nodeUrl
                    this.projectStage = 'progress'
                    this.checkedId = this.ProgressNodes[this.ProgressNodes.length - 1].id
                    url = this.ProgressNodes[this.ProgressNodes.length - 1].nodeUrl
                  } else {
                    this.frameSrc = this.djurl
                    this.projectStage = 'regist'
                    this.checkedId = 'regist'
                    url = this.djurl
                    this.deleteflagprogress = true
                  }
                  url =
                    url.replace('sd-webflow', 'law-progress-page') +
                    '?zt=' +
                    this.projectStage +
                    '&id=' +
                    this.jfId
                  window.location.href = url
                  // window.location.reload()
                } else {
                  message.error('删除失败，请联系管理员')
                }
              })
              .catch((e) => {
                message.error('删除失败，请联系管理员')
              })
          },
        })
      }
    },
    addProgress() {
      // 判断当前纠纷ID下无正在流转的纠纷进展详情
      const obj = this.ProgressNodes.find((i) => i.stepStatus === '0')
      if (obj) {
        Modal.warning({
          title: '提示',
          content: '当前还存在未流程办结的纠纷进展，请流程办结后再新建',
        })
        return false
      } else {
        this.interForm.stageField = ''
        this.visible = true
      }
    },
    handleOk() {
      if (this.interForm.stageField === '') {
        Modal.warning({
          title: '提示',
          content: '请选择阶段名称',
        })
      } else {
        this.visible = false
        this.projectStage = 'progress'
        const obj = this.stage.find((o) => o.code === this.interForm.stageField)
        let businessTypeId = obj.businessTypeId.toString()
        LawService.getTypeBusId(businessTypeId).then((res) => {
          businessTypeId = res.data[0].id
          this.frameSrc =
            '#/sd-webflow/pages/draft/0?businessTypeId=' +
            businessTypeId +
            '&extParams=%7B%22moduleId%22%3A%22271792223254282240%22%7D&zt=2&id=' +
            this.jfId +
            '&stage=' +
            this.interForm.stageField +
            '&parentid=' +
            this.jfjzid
          const stage = this.interForm.stageField
          const sobj = this.stage.find((i) => i.code === stage)
          this.ProgressNodes.push({
            id: '0',
            nodeUrl: this.frameSrc,
            nodeName: sobj.name,
            stepStatus: '0',
            creationTime: moment().format('YYYY-MM-DD'),
            instId: '0',
          })
          this.reload()
        })

        this.checkedId = '0'
      }
    },
    handleCancel() {
      this.visible = false
    },
    // 初始化项目信息
    initData(jfId) {
      if (jfId) {
        // 获取项目信息
        LawService.getProgressData(jfId).then((res) => {
          this.jfName = res.data[0].text
          this.jfinfo = res.data
          const progress = []
          this.djurl = res.data[0].props.detailUrl + '/' + res.data[0].props.detailInstid
          if (res.data.length > 1) {
            if (res.data[1].children && res.data[1].children.length > 0) {
              res.data[1].children.forEach((p) => {
                const timeStamp = p.props.creationTime
                const date = new Date(timeStamp * 1)

                progress.push({
                  id: p.id,
                  nodeUrl: p.props.detailUrl + '/' + p.props.detailInstid,
                  nodeName: p.props.stepName,
                  stepStatus: p.props.stepStatus,
                  creationTime: moment(date).format('YYYY-MM-DD'),
                  instId: p.props.detailInstid,
                })
              })
            }
            this.jfjzid = res.data[1].id
            this.ProgressNodes = [...progress]
            if (res.data.length > 1 && res.data.at(-1).props.stepType === 'finish') {
              this.jaurl =
                res.data.at(-1).props.detailUrl + '/' + res.data.at(-1).props.detailInstid
            }
          }
          this.checkedId = this.projectStage
          if (this.projectStage === 'progress') {
            let obj = null
            if (progress.length > 0) {
              obj = progress.find((i) => this.frameSrc.indexOf(i.nodeUrl) > -1)
            }
            if (obj) {
              this.checkedId = obj.id
            } else {
              if (this.$route.params) {
                if (this.$route.params.id && this.$route.params.id === '0') {
                  // 如果打开新建页面则在对象中增加新节点
                  const stage = this.$route.query.stage
                  const sobj = this.stage.find((i) => i.code === stage)
                  this.ProgressNodes.push({
                    id: '0',
                    nodeUrl: this.frameSrc,
                    nodeName: sobj.name,
                    stepStatus: '0',
                    creationTime: moment().format('YYYY-MM-DD'),
                    instId: '0',
                  })
                  this.checkedId = '0'
                }
              }
            }
          } else if (this.projectStage === 'finish') {
            if (this.$route.params) {
              if (this.$route.params.id && this.$route.params.id === '0') {
                // 如果打开新建页面则在对象中增加新节点
                this.jaurl = this.frameSrc
              }
            }
          }
          this.spinning = !this.spinning
          window.addEventListener('message', this.onPageUnload)
        })
      }
    },
    reload() {
      this.ifRouterView = false
      this.$nextTick(() => {
        this.ifRouterView = true
      })
    },
    foldClick() {
      this.fold = !this.fold
    },
    setChecked(val, url, projectStage) {
      this.checkedId = val
      if (url.indexOf('?') > -1) {
        if (url.indexOf('&id') === -1) {
          this.frameSrc = url + '&zt=' + projectStage + '&id=' + this.jfId
        } else {
          this.frameSrc = url
        }
      } else {
        this.frameSrc = url + '?zt=' + projectStage + '&id=' + this.jfId
      }
      this.reload()
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;

.fold {
  position: absolute;
  top: calc(50% - 30px);
  right: 5px;
  z-index: 2;
  width: 15px;
  height: 75px;
  padding: 0;
  border-radius: 0 10px 10px 0;
}

.audit-table {
  :global(.sd-readonly) {
    margin-bottom: 24px;
  }
}

.close-btn {
  font-size: 15px;
  color: #ffffff;
  position: absolute;
  right: 15px;
  top: 25px;
  cursor: pointer;
}

$link-icon-size: 22px;
$line-height-theme: 66px;
$theme-check: #fff;
$icon-size: 15px;

.page {
  // 表格样式
  :global(div.sd-has-table) {
    :global(.ant-table-wrapper) {
      margin-top: -8px;
    }

    :global(.ant-card-body) {
      padding: 0;

      :global(.ant-table-wrapper) {
        margin-top: -8px;
      }
    }
  }

  :global(.sd-has-table) {
    :global(.ant-table-wrapper) {
      margin-top: -8px;
    }
  }

  height: 100%;

  .left-sider {
    overflow: hidden;
    white-space: nowrap;

    :global(.ant-layout-sider-children) {
      overflow: auto;
    }
  }

  .left-sider-hidden {
    flex: 0 0 0 !important;
    max-width: 0 !important;
    min-width: 0 !important;
    width: 0 !important;
    padding: 0px;
    background: rgb(255, 255, 255);

    :global(.ant-layout-sider-children) {
      overflow: hidden;
    }
  }
  .left-over {
    margin-left: 20px;
  }

  .trigger {
    display: inline-block;
    padding: 0 15px;
    vertical-align: top;
    cursor: pointer;
    transition: color 0.3s;

    &:hover {
      color: $text-color-inverse;
    }
  }

  aside {
    overflow: auto;
  }

  :global(.sd-frame-main) {
    height: 100%;
    padding: $padding-lg;
    overflow: auto;
  }

  :global(sd-readonly) {
    margin-bottom: 24px;
  }
}

.title {
  display: inline-block;
  margin-left: -35px;
  font-weight: 600;
  line-height: inherit;
  text-align: center;
  vertical-align: top;

  > i {
    // 固定大小的logo
    /* stylelint-disable-next-line */
    font-size: 20px;
    transform: scale(10);
  }
}

// 主内容区的Card白色背景要占满
:global .sd-frame-main > .ant-card {
  min-height: 100%;
}

.header {
  background: linear-gradient(to right, #3f9bff, #0e7df6);
  height: 48px;
  line-height: 48px;
  padding: 0 20px 0 20px;

  :global .ant-menu {
    float: right;
  }

  :global(.ant-menu-item-selected) {
    color: #ffffff;
    background: #1366c1;
    border-bottom: 0 !important;
    top: 0;
  }

  :global(.ant-menu-item) {
    border-bottom: 2px solid #ffffff;
    border-bottom: 0 !important;
    top: 0;
  }

  :global(.ant-menu-item-active) {
    color: #ffffff !important;
    background: #1366c1 !important;
    border-bottom: 0 !important;
    top: 0;
  }

  .header-title {
    color: #ffffff;
    font-size: 25px;
    font-weight: 400;
    display: inline-block;
    width: 40%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.header > div:last-child {
  width: calc(100% - 200px);
}

.links {
  display: flex;
  align-items: center;
  margin: 0 $link-icon-size / 2;

  li:global(.ant-menu-item) {
    padding: 0;
  }

  i:global(.anticon) {
    padding: 0 $link-icon-size / 2;
    margin: 0;
    font-size: $link-icon-size;
    line-height: $layout-header-height;
    vertical-align: middle;

    &:hover {
      // 悬浮的颜色，与主题无关
      /* stylelint-disable-next-line */
      background-color: rgba(0, 0, 0, 0.2);
    }
  }
}

.tools {
  display: flex;
  float: right;
}

.headerbadge {
  bottom: $line-height-theme / 6;
  left: -$link-icon-size / 2 - 5;
}

.sider-content {
  padding: 0 0;

  .sider-title {
    position: relative;
    margin-left: 23px;

    i {
      color: #1890ff;
      position: absolute;
      font-size: 18px;
      left: -27px;
      top: 3px;
    }

    font-weight: bold;
  }

  .sider-li {
    :global(.ant-timeline-item-content) {
      margin: 0 0 0 15px;
    }

    :global(.ant-timeline-item-head-blue) {
      color: #9f9f9f;
      border-color: #9f9f9f;
      background-color: #9f9f9f;
      top: 4px;
      left: 3px;
      width: 3px;
      height: 3px;
    }

    :global(.ant-timeline-item-tail) {
      height: calc(100% - -18px);
      border-left: 2px solid #f5f5f5;
      display: none;
    }
  }

  .sider-title-div-first {
    padding: 10px 0 10px 20px;
    // margin-bottom: 10px;
    // border-bottom: 2px solid #e8e8e8;
  }

  .sider-title-div {
    padding: 10px 0 10px 20px;
    margin-bottom: 10px;
    border-top: 2px solid #e8e8e8;
    border-bottom: 2px solid #e8e8e8;
  }

  ul {
    margin-left: 0;
    padding-bottom: 5px;
  }

  .sider-ul-div {
    padding: 13px 0px 0px 12px;
    width: 100%;
    margin: 3px auto;
    border-radius: 0px;
    cursor: pointer;

    :global(.ant-timeline-item) {
      padding: 0;
      margin-left: 3px;
    }
  }

  .node-readonly {
    cursor: normal;
    color: #b6b6b6;
  }

  :global(.checked) {
    background: linear-gradient(to right, #13c2c2, #2db7f5);
    color: #fff;

    :global(.ant-timeline-item-head-blue) {
      background-color: #ffffff;
      border-color: #ffffff !important;
      top: 4px;
      left: 3px;
      width: 3px;
      height: 3px;
    }
  }

  :global(.checkedpro) {
    color: #2db7f5;
  }

  :global(.nocheckdpro) {
    color: #7c7c7c;
  }

  :global(.ant-timeline-item-last .ant-timeline-item-tail) {
    display: none;
  }

  .timeline {
    min-height: 150px;
  }
}

:global(.ant-tabs) {
  overflow-y: auto;
}

.rightfrm {
  height: 100%;
  width: 100%;
}

.change-status {
  margin-left: 150px;
  font-size: 20px !important;
  color: #28baeb !important;
  cursor: pointer;
}
.lawprogress {
  :global(.skeleton-box_sd-webflow-panel_webflow) {
    width: auto;
    height: auto;
  }
  :global(.panel_sd-webflow-panel_webflow .skeleton-box_sd-webflow-panel_webflow) {
    height: 90%;
    width: 80%;
  }
}

.deletePro {
  color: #1890ff;
  font-size: 20px;
}
.lawprogress {
  position: relative;
  // :global .ant-layout > .ant-layout-header {
  //   :global .titlepoint_sd-header_common {
  //     display: none;
  //   }
  // }
  :global(.webflow_sd-webflow_webflow > .ant-layout-header) {
    :global .titlepoint_sd-header_common {
      display: none;
    }
  }
  :global(.panel_sd-webflow-panel_webflow > .ant-layout-header) {
    position: absolute;
    :global .titlepoint_sd-header_common {
      position: absolute !important;
    }
  }
  // :global(.titlepoint_sd-header_common) {
  //   position: absolute !important;
  // }
}
</style>
