<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col v-show="!showMatterView" style="width: 30%;" :xs="24" class="matter-content">
        <div class="head-container left-search-div">
          <el-input v-model="matterName" placeholder="请输入审查事项名称" clearable size="small"
                    prefix-icon="el-icon-search"/>
          <el-button type="primary" size="small" @click="handleSearchClick">查询</el-button>
        </div>
        <div class="head-container" style="overflow: auto; height: calc(100% - 50px);">
          <el-tree v-show="stepViewFlag" :load="loadDeptNode" :props="defaultProps" :expand-on-click-node="false"
                   ref="tree" node-key="id" lazy accordion highlight-current
                   :default-expanded-keys="defaultExpandedKeys" @node-click="handleNodeClick">
            <template slot-scope="{ node, data }">
              <span class="custom-tree-node" :class="{ 'is-dept': !data.isMatter, 'is-matter': data.isMatter }"
                    :title="data.deptName ? data.deptName : data.itemName">
                <i class="el-icon" :class="data.isMatter ? 'el-icon-tickets' : 'el-icon-office-building'"></i>
                <span>{{ data.deptName ? data.deptName : data.itemName }}</span>
              </span>
            </template>
          </el-tree>
          <el-tree v-show="!stepViewFlag" :data="searchMatterList" :props="defaultProps" :expand-on-click-node="false"
                   ref="searchTree" node-key="id" :lazy="false" accordion default-expand-all highlight-current
                   @node-click="handleNodeClick">
            <template slot-scope="{ node, data }">
              <span class="custom-tree-node" :class="{ 'is-dept': !data.isMatter, 'is-matter': data.isMatter }"
                    :title="data.deptName ? data.deptName : data.itemName">
                <i class="el-icon" :class="data.isMatter ? 'el-icon-tickets' : 'el-icon-office-building'"></i>
                <span>{{ data.deptName ? data.deptName : data.itemName }}</span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-col>
      <el-col class="matter-content" style="margin-left: 5px; margin-right: 5px; width: 30px;">
        <i v-show="showMatterView" class="el-icon-d-arrow-right"
           style="color: #409eff; cursor: pointer; position: absolute; top: 49%; transform: translateX(-20%);"
           @click="changeView(false)"
           title="展开"></i>
        <i v-show="!showMatterView" class="el-icon-d-arrow-left"
           style="color: #409eff; cursor: pointer; position: absolute; top: 49%; transform: translateX(-20%);"
           @click="changeView(true)"
           title="收起"></i>
      </el-col>
      <el-col :xs="24" class="matter-content"
              :style="showMatterView ? 'width: calc(100% - 40px);' : 'width: calc(70% - 40px);'">
        <template v-if="preQuestionPart">
          <div class="matter-title-h" style="font-style: italic; color: #00afff; margin-bottom: -10px;"
               :title="currMatter.itemName">
            <i class="el-icon-collection"></i>&nbsp;&nbsp;{{ currMatter.itemName }}
          </div>
          <el-divider></el-divider>
          <el-alert :title="currMatterQuestion.desc" type="success" class="matter-title" :closable="false">
          </el-alert>
          <el-row class="pre-question-div" style="margin-top: 20px;overflow-y: scroll;height: calc(100% - 120px);">
            <template v-for="option in currMatterQuestion.preQuestionOptionList">
              <el-row style="display: flex; justify-content: center; margin: 10px;">
                <el-button type="primary" plain class="text-wrap-button" style="width: 50%;"
                           @click="handleOptionClick(option, $event)">{{
                    option.desc
                  }}
                </el-button>
              </el-row>
            </template>
          </el-row>
        </template>
        <template v-if="preMaterialPart">
          <el-row>
            <el-button type="primary" @click="handleBtnSaveDealWith(0)">保存</el-button>
            <el-button type="warning" @click="handleBtnSaveDealWith(1)">物料流转</el-button>
            <el-button type="success" @click="handlePrintDealWith('print_suc')">受理通知单</el-button>
            <el-button style="background-color: forestgreen;border-color: forestgreen;color: white;"
                       @click="handlePrintDealWith('print_onegzd')">一次性告知单</el-button>
            <el-button type="info" @click="handlePrintDealWith('print_fail')">补正材料告知书</el-button>
            <el-button type="danger" @click="handlePrintDealWith('print_deny')">不予受理通知书</el-button>
            <el-button id="print_suc" type="success" v-print="printSuccessObj" style="display: none;">受理通知单</el-button>
            <el-button id="print_onegzd" style="background-color: forestgreen;border-color: forestgreen;color: white;display: none;"
                       v-print="printYcxgzdObj">一次性告知单</el-button>
            <el-button id="print_fail" type="info" v-print="printFailObj" style="display: none;">补正材料告知书</el-button>
            <el-button id="print_deny" type="info" v-print="printDenyObj" style="display: none;">不予受理通知书</el-button>
            <el-button @click="handleConnDesktop">远程连接</el-button>
          </el-row>
          <el-row id="print_material" style="height: 100%; padding: 10px;">
            <h2 style="font-style: italic; color: #00afff; margin-bottom: -10px; font-size: 16px;" class="qzprblem"
                :title="currMatter.itemName">
              <i class="el-icon-collection"></i>&nbsp;&nbsp; {{ currMatter.itemName }}
            </h2>
            <el-divider></el-divider>
            <el-row style="overflow: auto; height: calc(100% - 120px);">
              <el-form :model="dealWithForm" ref="dealWithForm" :rules="dealWithFormRules" label-width="120px"
                       style="">
                <el-form-item label="受理编号" prop="serialNumber">
                  <el-input v-model="dealWithForm.serialNumber" readonly disabled></el-input>
                </el-form-item>
                <el-form-item label="办理类型" prop="withType">
                  <el-radio-group v-model="dealWithForm.withType">
                    <el-radio :label="1">个人</el-radio>
                    <el-radio :label="2">企业</el-radio>
                  </el-radio-group>
                </el-form-item>
                <template v-if="dealWithForm.withType == 1">
                  <el-form-item label="姓名" prop="contacts">
                    <el-input v-model="dealWithForm.contacts" maxlength="20"></el-input>
                  </el-form-item>
                  <el-form-item label="身份证号码" prop="idCard">
                    <el-input v-model="dealWithForm.idCard" maxlength="50"></el-input>
                  </el-form-item>
                  <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="dealWithForm.phone" maxlength="11"></el-input>
                  </el-form-item>
                </template>
                <template v-else>
                  <el-form-item label="企业名称" prop="enterpriseName">
                    <el-input v-model="dealWithForm.enterpriseName" maxlength="100"></el-input>
                  </el-form-item>
                  <el-form-item label="社会信用代码" prop="idCard">
                    <el-input v-model="dealWithForm.idCard" maxlength="50"></el-input>
                  </el-form-item>
                  <el-form-item label="联系人" prop="contacts">
                    <el-input v-model="dealWithForm.contacts" maxlength="20"></el-input>
                  </el-form-item>
                  <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="dealWithForm.phone" maxlength="11"></el-input>
                  </el-form-item>
                </template>
                <el-row>
                  <label style="color: #00afff;">一、申请条件</label>
                  <div class="matter-material" v-html="currMaterial.conditions"></div>
                </el-row>
                <el-row style="margin-top: 20px;">
                  <label style="color: #00afff;">二、现有办理方式</label>
                  <div class="matter-material" v-html="currMaterial.dealWith"></div>
                </el-row>
                <el-row style="margin-top: 20px;">
                  <label style="color: #00afff;">三、材料说明</label>
                  <div style="margin-top: 10px;">
                    <el-table
                      ref="multipleTable"
                      :data="dealWithForm.materials"
                      tooltip-effect="dark"
                      style="width: 100%"
                      @selection-change="handleSelectionChange">
                      <el-table-column type="selection" width="55"></el-table-column>
                      <el-table-column label="材料名称" prop="listName"></el-table-column>
                      <el-table-column label="理由" width="200">
                        <template slot-scope="scope">
                          <el-input v-if="!scope.row.reasonFlag" v-model="scope.row.reason"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="200">
                        <template slot-scope="scope">
                          <el-button type="warning" size="mini"
                                     @click="handleMaterialDetail(scope.row, $event)">审查要点</el-button>
                          <el-button v-if="scope.row.verification === 1 && scope.row.reasonFlag" type="primary" size="mini"
                                     :disabled="scope.row.manualVerifyId > 0 ? true : false" :key="dealWithKey"
                                     @click="handleManualVerify(scope.row, $event)">{{ scope.row.manualVerifyId > 0 ? '核验中' : '人工核验' }}</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </el-row>
                <el-row style="margin-top: 20px;">
                  <label style="color: #00afff;">四、常见问题</label>
                  <div class="matter-material" v-html="currMatter.commonProblem"></div>
                </el-row>
              </el-form>
              <!--              <el-row style="margin-top: 20px;">-->
              <!--                <label style="color: #00afff;">四、材料说明</label>-->
              <!--                <div class="matter-material" v-html="currMaterial.desc"></div>-->
              <!--              </el-row>-->
              <el-row style="margin-top: 20px;">
                <label>所属部门：<span style="font-weight: 400;">{{ currMatter.dept.deptName }}</span></label>
              </el-row>
              <el-row>
                <label>联系人员：<span style="font-weight: 400;">{{ currMatter.contacts }}</span></label>
              </el-row>
              <el-row>
                <label>联系电话：<span style="font-weight: 400;">{{ currMatter.contactsPhone }}</span></label>
              </el-row>
            </el-row>
          </el-row>
          <el-row id="print_ycxgzd" style="height: auto; padding: 10px;">
            <el-row style="overflow: auto; height: calc(100% - 120px);">
              <div class="matter-material" style="background-color: #fff;" v-html="currMatterPrintInfo"></div>
            </el-row>
          </el-row>
          <el-row id="print_ycxgzd_fail" style="height: auto; padding: 10px;">
            <el-row style="overflow: auto; height: calc(100% - 120px);">
              <div class="matter-material" style="background-color: #fff;" v-html="currMatterFailPrintInfo"></div>
            </el-row>
          </el-row>
          <el-row id="print_ycxgzd_deny" style="height: auto; padding: 10px;">
            <el-row style="overflow: auto; height: calc(100% - 120px);">
              <div class="matter-material" style="background-color: #fff;" v-html="currMatterDenyPrintInfo"></div>
            </el-row>
          </el-row>
        </template>
      </el-col>
    </el-row>

    <el-dialog :title="(currDesktop ? currDesktop.desktopName : '远程连接') | ellipsis"
               :close-on-click-modal="false" @close="closeConnDesktop"
               :visible.sync="showDesktopConn" width="100%" class="desktop-dialog">
      <el-row>
        <el-button type="danger" size="mini" style="margin-bottom: 10px;" icon="el-icon-error"
                   @click="closeConnDesktop">断开连接
        </el-button>
      </el-row>
      <el-row :gutter="20">
        <i-frame style="height: calc(100vh - 165px)" :src="vncDesktopPath"/>
      </el-row>
    </el-dialog>

    <el-dialog title="远程连接" :visible.sync="dialogDesktopVisible" :close-on-click-modal="false"
               class="vnc-desktop-dialog">
      <el-form>
        <el-form-item label="服务器" label-width="80px">
          <el-select v-model="vncDesktop" filterable popper-class="popper-class"
                     :popper-append-to-body="false" @change="handleChange"
                     placeholder="请选择远程服务器" style="width: 100%;">
            <el-option
              v-for="item in desktopOptions"
              :key="item.id"
              :label="item.desktopName"
              :title="item.desktopName"
              :value="item.id">
            </el-option>
          </el-select>
          <div>IP地址：{{ currDesktop ? currDesktop.vncIp : '' }}</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleBtnCancel">取 消</el-button>
        <el-button type="primary" @click="handleBtnConn">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="审查要点" :visible.sync="dialogDealWithFormVisible" :close-on-click-modal="false" width="80%">
      <div class="material-content">
        <template
          v-if="!hasRichTextContent(currMaterialInfo.memo) && (!currMaterialInfo.imgList || currMaterialInfo.imgList.length == 0)">
          <div style="margin: 10px; color: #aea6a3;text-align: center;">暂无数据</div>
        </template>
        <template v-if="hasRichTextContent(currMaterialInfo.memo)">
          <div v-html="currMaterialInfo.memo"></div>
        </template>
        <div v-for="(url, i) in currMaterialInfo.imgList">
          <!--                        <label>示例图{{ i + 1 }}</label>-->
          <div class="demo-image__lazy" style="margin: 10px;">
            <el-image :src="url" lazy :preview-src-list="currMaterialInfo.imgList"
                      @load="loadImgSuccess"></el-image>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 物料流转单打印 -->
    <el-dialog title="物料流转单打印" :visible.sync="dealDetailDialog" :close-on-click-modal="false" width="60%"
               destroy-on-close append-to-body>
      <el-button type="primary" size="small" icon="el-icon-printer" v-print="printObj" style="margin-left: 85%;margin-bottom: 10px;">打印</el-button>
      <el-row style="height: 70vh; overflow: auto;">
        <el-descriptions v-if="currDealRecord" id="print_deal_detail" class="margin-top" style="width: 100%; overflow: auto;" :column="3"
                         border :key="detailKey">
          <el-descriptions-item :span="3" label-style="width:110px;">
            <template slot="label">
              <i class="el-icon-price-tag"></i>
              受理编号
            </template>
            {{ currDealRecord.serialNumber }}
          </el-descriptions-item>
          <el-descriptions-item :span="3">
            <template slot="label">
              <i class="el-icon-full-screen"></i>
              条形码
            </template>
            <el-image :src="'data:image/png;base64,' + currDealRecord.barcode" style="width: 300px;"></el-image>
          </el-descriptions-item>
          <el-descriptions-item :span="3">
            <template slot="label">
              <i class="el-icon-tickets"></i>
              事项名称
            </template>
            {{ currDealRecord.itemName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-collection-tag"></i>
              业务类型
            </template>
            {{ currDealRecord.withType == 1 ? '个人' : '企业' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              联系人
            </template>
            {{ currDealRecord.contacts }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-mobile-phone"></i>
              联系电话
            </template>
            {{ currDealRecord.phone }}
          </el-descriptions-item>
          <el-descriptions-item :span="3">
            <template slot="label">
              <i class="el-icon-postcard"></i>
              {{ currDealRecord.withType == 1 ? '身份证号码' : '企业社会信用代码' }}
            </template>
            {{ currDealRecord.idCard }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              受理人
            </template>
            {{ currDealRecord.userName }}
          </el-descriptions-item>
          <el-descriptions-item :span="2">
            <template slot="label">
              <i class="el-icon-time"></i>
              受理时间
            </template>
            {{ currDealRecord.createTime }}
          </el-descriptions-item>
          <el-descriptions-item :span="3">
            <template slot="label">
              <i class="el-icon-document-checked"></i>
              已有材料
            </template>
            <template v-if="this.currDealRecord.materialList && this.currDealRecord.materialList.length > 0">
              <ul>
                <li v-for="(item) in this.currDealRecord.materialList" v-if="item.reasonFlag">
                  {{ item.verification === 1 ? (item.listName + '【' + item.dealStatusName + '】') : item.listName }}
                </li>
              </ul>
            </template>
          </el-descriptions-item>
          <el-descriptions-item :span="3">
            <template slot="label">
              <i class="el-icon-document-delete"></i>
              缺失材料
            </template>
            <template v-if="this.currDealRecord.materialList && this.currDealRecord.materialList.length > 0">
              <ul>
                <li v-for="(item) in this.currDealRecord.materialList" v-if="!item.reasonFlag">
                  {{ item.listName + '，【原因】：' + item.reason }}
                </li>
              </ul>
            </template>
          </el-descriptions-item>
        </el-descriptions>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
// 引入Element UI的Loading服务
import {Loading} from 'element-ui'
import {listDept} from '@/api/system/dept'
import {getMatter, listMatterAll} from '@/api/matter/matter'
import {getQuestion} from '@/api/matter/question'
import {getVncDesktop, listAllVncDesktop} from '@/api/matter/vnc'
import iFrame from '@/components/iFrame/index.vue'
import {mapGetters} from 'vuex'
import {
  addDealRecord,
  addManualVerify,
  addPrintLog,
  getDealRecordById, getManualVerifyByIds,
  getSerialNumber,
  listDealRecord
} from "@/api/matter/record";
import Cookies from "js-cookie";

export default {
  name: "Index",
  components: {iFrame},
  computed: {
    ...mapGetters([
      'name',
      'sidebar'
    ])
  },
  data() {
    let validateDealWithUser = (rule, value, callback) => {
      if (value === '') {
        if (this.dealWithForm.withType == 1) {
          callback(new Error('请输入姓名'));
        } else {
          callback(new Error('请输入联系人'));
        }
      } else {
        callback();
      }
    };
    let validateDealWithIdCard = (rule, value, callback) => {
      if (value === '') {
        if (this.dealWithForm.withType == 1) {
          callback(new Error('请输入身份证号码'));
        } else {
          callback(new Error('请输入企业社会信用代码'));
        }
      } else {
        if (this.dealWithForm.withType == 1) {
          let pattern = /^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/;
          if (!pattern.test(value)) {
            callback(new Error('身份证号码不正确'));
          } else {
            callback();
          }
        } else {
          let pattern = /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/;
          if (!pattern.test(value)) {
            callback(new Error('企业统一社会信用代码不正确'));
          } else {
            callback();
          }
        }
      }
    };
    return {
      // 审查事项名称
      matterName: undefined,
      // 左侧显示类型：true 部门树 false 搜索树
      stepViewFlag: true,
      showMatterView: false,
      // 是否前置问题部分
      preQuestionPart: false,
      // 是否材料部分
      preMaterialPart: false,
      // 当前选中的审查事项
      currMatter: undefined,
      // 当前选中的审查事项的问题情况
      currMatterQuestion: {},
      // 当前选中的审查事项的一次性告知单打印模板（受理通知单）
      currMatterPrintInfo: {},
      // 当前选中的审查事项的一次性告知单打印模板（补正材料告知书）
      currMatterFailPrintInfo: {},
      // 当前选中的审查事项的一次性告知单打印模板（不予受理通知书）
      currMatterDenyPrintInfo: {},
      // 当前选中的审查事项问题选项情况
      currMaterial: {},
      // 材料清单对应的材料介绍
      currMaterialInfo: {},
      showMaterialInfo: false,
      // 搜索事项数据
      searchMatterList: [],
      // 远程桌面弹框
      dialogDesktopVisible: false,
      // 受理单弹框
      dialogDealWithFormVisible: false,
      // 显示远程连接
      showDesktopConn: false,
      // 远程连接地址
      vncDesktopPath: undefined,
      vncDesktop: undefined,
      currDesktop: undefined,
      lineHeight: undefined,
      desktopOptions: [],
      defaultProps: {
        children: 'children',
        label: 'deptName',
        isLeaf: 'leaf'
      },
      defaultExpandedKeys: [100],
      treeData: [
        {id: 100, deptId: 100, deptName: '南岸区', isMatter: false, children: []},
      ],
      printSuccessObj: {
        id: "print_ycxgzd",
        popTitle: "受理通知单",
        extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
        openCallback(vue) {
          vue.savePrintLog('print_ycxgzd', 1)
        },
        closeCallback(vue) {
        }
      },
      printYcxgzdObj: {
        id: "print_ycxgzd",
        popTitle: "一次性告知单",
        extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
        openCallback(vue) {
          vue.savePrintLog('print_ycxgzd', 5)
        },
        closeCallback(vue) {
        }
      },
      printFailObj: {
        id: "print_ycxgzd_fail",
        popTitle: "补正材料告知书",
        extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
        openCallback(vue) {
          vue.savePrintLog('print_ycxgzd_fail', 2)
        },
        closeCallback(vue) {
        }
      },
      printDenyObj: {
        id: "print_ycxgzd_deny",
        popTitle: "不予受理通知书",
        extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
        openCallback(vue) {
          vue.savePrintLog('print_ycxgzd_deny', 3)
        },
        closeCallback(vue) {
        }
      },
      dealWithKey: 0,
      dealWithForm: {
        id: undefined,
        serialNumber: '',
        withType: 1,
        enterpriseName: '',
        contacts: '',
        idCard: '',
        phone: '',
        materials: []
      },
      dealWithFormRules: {
        withType: [
          {required: true, message: '请选择办理类型', trigger: 'change'}
        ],
        enterpriseName: [
          {required: true, message: '请输入企业名称', trigger: 'change'}
        ],
        contacts: [
          {required: true, validator: validateDealWithUser}
        ],
        idCard: [
          {required: true, validator: validateDealWithIdCard}
        ],
        phone: [
          {required: true, message: '请输入手机号码', trigger: 'change'},
          {required: true, pattern: /^[1]([3-9])[0-9]{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
        ]
      },
      dealDetailDialog: false,
      currDealRecord: null,
      detailKey: 0,
      printObj: {
        id: "print_deal_detail",
        popTitle: "打印物料流转单",
        extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
        beforeOpenCallback() {
        },
        openCallback(vue) {
          vue.savePrintLog('print_deal_detail', 4)
        },
        closeCallback(vue) {
        }
      }
    };
  },
  filters: {
    ellipsis(value) {
      if (!value) return ""
      if (value.length > 30) {
        return value.slice(0, 30) + '...'
      }
      return value
    }
  },
  watch: {},
  mounted() {
    history.pushState(null, null, document.URL);
    window.addEventListener('popstate', this.disableBrowserBack);
  },
  created() {
  },
  methods: {
    getAPIPath() {
      return process.env.VUE_APP_BASE_API;
    },
    disableBrowserBack() {
      history.pushState(null, null, document.URL);
    },
    loadDeptNode(node, resolve) {
      if (node.level === 0) {
        return resolve(this.treeData);
      }
      if (node.data.isMatter) return resolve([])
      listDept({
        parentId: node.data.deptId
      }).then(response => {
        const data = response.data
        listMatterAll({
          deptId: node.data.deptId
        }).then(response => {
          const matterData = response.data
          const newArray = matterData.map(obj => ({
            ...obj,
            isMatter: true,
            leaf: true
          }));
          resolve(data.concat(newArray));
        });
      });
    },
    /** 左侧树节点单击事件 **/
    handleNodeClick(data) {
      let _this = this;
      if (!data.isMatter) {
        return
      }
      let loadingInstance = Loading.service({fullscreen: true})
      this.handleCancelDealWith()
      this.currMatter = data
      this.preMaterialPart = false
      this.preQuestionPart = data.prefixQuestion === 'Y'
      getMatter(data.id).then(response => {
        loadingInstance.close()
        const matterData = response.data
        this.currMatter = matterData
        // this.showMatterView = true
        if (this.sidebar.opened) {
          this.$store.dispatch('app/toggleSideBar')
        }
        if (matterData.prefixQuestion === 'Y') {
          this.currMatterQuestion = (matterData.preQuestionList && matterData.preQuestionList.length > 0) ? matterData.preQuestionList[0] : {}
          this.changePreQuestionViewHeight()
        } else {
          // 不跳转问题
          this.preQuestionPart = false
          this.preMaterialPart = true
          this.lineHeight = 'height: auto;'
          this.currMaterialInfo = {}
          this.showMaterialInfo = false
          this.currMaterial = matterData.material ? matterData.material : {}
          this.handleDealWith()
          // setTimeout(() => {
          //   let listHeight = document.getElementsByClassName('material-list')[0].clientHeight
          //   _this.lineHeight = 'height: ' + listHeight + 'px;'
          // })
        }
      });
    },
    /**
     * 切换前置问题高度视图
     */
    changePreQuestionViewHeight() {
      setTimeout(() => {
        let qHeight = document.getElementsByClassName('matter-title-h')[0].clientHeight
        let tHeight = document.getElementsByClassName('matter-title')[0].clientHeight
        let height = (qHeight - 20) + (tHeight - 40) + 120
        document.getElementsByClassName('pre-question-div')[0].style.height = 'calc(100% - ' + height + 'px)'
      }, 100)
    },
    /**
     * 切换视图显示
     */
    changeView(flag) {
      this.showMatterView = flag
    },
    commDrawLayoutPrint(content) {
      let nTime = new Date();
      let nYear = nTime.getFullYear();
      let nMonth = nTime.getMonth() + 1;
      let nDay = nTime.getDate();
      content = content.replace(/{\$year}/g, nYear)
      content = content.replace(/{\$month}/g, nMonth < 10 ? ('0' + nMonth) : nMonth)
      content = content.replace(/{\$day}/g, nDay < 10 ? ('0' + nDay) : nDay)
      content = content.replace(/{\$matter}/g, this.currMatter.itemName)
      // const username = Cookies.get("username");
      content = content.replace(/{\$dealWithUser}/g, this.name)
      content = content.replace(/{\$dealWithUserPhone}/g, this.currMatter.contactsPhone == '-' ? "" : this.currMatter.contactsPhone)
      let approveUser = ''
      if (this.dealWithForm.withType == 1) {
        approveUser = this.dealWithForm.contacts
      } else {
        approveUser = this.dealWithForm.enterpriseName
      }
      content = content.replace(/{\$contactPhone}/g, this.dealWithForm.phone)
      content = content.replace(/{\$approveUser}/g, approveUser)
      content = content.replace(/{\$serialNumber}/g, this.dealWithForm.serialNumber)
      return content
    },
    /** 受理通知单
     * {$year}：当前年
     * {$month}：当前月
     * {$day}：当前日
     * {$matter}：事项名称
     * {$materialNum}：材料数量
     * {$dealWithUser}：受理人
     * {$approveUser}：申请人
     * {$contactPhone}：申请人联系电话
     * {$serialNumber}：受理编号
     * {$materialConditions}：申请条件
     * {$materialList}：材料列表
     */
    dealWithPrintInfo(objs, elm) {
      let printObj = this.currMatter.print ? this.currMatter.print : {}
      let pintContent = printObj.content ? printObj.content : ''
      if (elm == 'print_onegzd') {
        pintContent = printObj.disposableContent ? printObj.disposableContent : ''
      }
      pintContent = pintContent.replace(/{\$materialNum}/g, objs.length)
      pintContent = pintContent.replace(/{\$materialConditions}/g, this.currMaterial.conditions)
      let itemHtml = ''
      objs.forEach((item, index) => {
        itemHtml += '<p style="padding: 5px;">□ ' + (index + 1) + '. ' + item.listName + '</p>'
      })
      pintContent = pintContent.replace(/{\$materialList}/g, itemHtml)
      pintContent = this.commDrawLayoutPrint(pintContent)
      this.currMatterPrintInfo = pintContent
    },
    /** 补正材料告知书
     * {$year}：当前年
     * {$month}：当前月
     * {$day}：当前日
     * {$matter}：事项名称
     * {$materialNum}：提交材料数量
     * {$materials}：缺失材料信息
     * {$dealWithUser}：受理人
     * {$approveUser}：申请人
     * {$serialNumber}：不予受理编号
     */
    dealWithMissPrintInfo() {
      let printObj = this.currMatter.print ? this.currMatter.print : {}
      let pintContent = printObj.missContent ? printObj.missContent : ''
      let materialList = this.dealWithForm.materials
      let html = '<div>'
      let num = 0, mindex = 0
      if (materialList && materialList.length > 0) {
        let miss = ''
        materialList.forEach((item, index) => {
          if (!item.reasonFlag) {
            num ++
            mindex ++
            miss += '<p style="padding: 5px;">' + (mindex) + '. ' + item.listName + (item.reason ? ('，【理由】：' + item.reason) : '') + '（□ 材料不齐全&nbsp;&nbsp;&nbsp;&nbsp;□不符合法定形式 ）</p>'
          }
        })
        if (miss) {
          html += miss
        } else {
          html += '<p style="padding: 5px;">无</p>'
        }
      } else {
        html += '<p style="padding: 5px;">无</p>'
      }
      html += '</div>'
      pintContent = pintContent.replace(/{\$materials}/g, html)
      pintContent = pintContent.replace(/{\$materialNum}/g, materialList.length - num)
      pintContent = this.commDrawLayoutPrint(pintContent)
      this.currMatterFailPrintInfo = pintContent
    },
    /** 不予受理通知书
     * {$year}：当前年
     * {$month}：当前月
     * {$day}：当前日
     * {$matter}：事项名称
     * {$materialNum}：材料数量
     * {$dealWithUser}：受理人
     * {$approveUser}：申请人
     * {$serialNumber}：不予受理编号
     * {$reason}：不予受理理由
     */
    dealWithDenyPrintInfo(reason) {
      let printObj = this.currMatter.print ? this.currMatter.print : {}
      let pintContent = printObj.denyContent ? printObj.denyContent : ''
      let materialList = this.dealWithForm.materials
      pintContent = pintContent.replace(/{\$materialNum}/g, materialList.length)
      pintContent = pintContent.replace(/{\$reason}/g, reason)
      pintContent = this.commDrawLayoutPrint(pintContent)
      this.currMatterDenyPrintInfo = pintContent
    },
    /** 问题选项单击事件 **/
    handleOptionClick(data, evt) {
      let target = evt.target;
      if (target.nodeName == "SPAN") {
        target = evt.target.parentNode;
      }
      target.blur();
      // 是否跳转下一项问题
      if (data.jumpToMatterId <= 0) {
        // 不跳转问题
        this.preQuestionPart = false
        this.preMaterialPart = true
        this.lineHeight = 'height: auto;'
        this.currMaterialInfo = {}
        this.showMaterialInfo = false
        this.currMaterial = data.material ? data.material : {}
        this.handleDealWith()
        return
      }
      // 继续问题跳转
      let loadingInstance = Loading.service({fullscreen: true})
      getQuestion(data.jumpToMatterId).then(response => {
        loadingInstance.close()
        const questionData = response.data
        this.currMatterQuestion = questionData ? questionData : {}
        this.changePreQuestionViewHeight()
      });
    },
    /** 查询事项 **/
    handleSearchClick() {
      if (!this.matterName) {
        this.stepViewFlag = true
        return
      }
      listMatterAll({
        itemName: this.matterName
      }).then(response => {
        const matterData = response.data
        this.stepViewFlag = false
        if (matterData.length == 0) {
          this.searchMatterList = []
          return
        }
        let deptTree = []
        matterData.forEach(data => {
          let newItem = {
            id: data.dept.deptId,
            deptName: data.dept.deptName,
            children: []
          }
          let matterItem = data
          matterItem.isMatter = true
          matterItem.leaf = true
          // 查找或创建部门项
          let deptItem = this.findOrCreateDeptItem(deptTree, newItem)
          // 检查部门项的子项中是否已存在该事项项
          if (!deptItem.children.find(child => child.id === matterItem.id)) {
            // 不存在则添加到子项中
            deptItem.children.push(matterItem)
          }
        })
        this.searchMatterList = deptTree
      });
    },
    /** 数据判重 **/
    findOrCreateDeptItem(deptTree, newItem) {
      let deptItem = deptTree.find(item => item.id === newItem.id)
      if (!deptItem) {
        deptItem = newItem
        deptTree.push(deptItem)
      }
      return deptItem
    },
    /** 检查富文本是否有内容 */
    hasRichTextContent(htmlContent) {
      if (!htmlContent) return false;
      // 去除HTML标签，只保留纯文本
      let textContent = htmlContent.replace(/<[^>]*>/g, '');
      // 去除空白字符（包括空格、制表符、换行符等）
      let trimmedTextContent = textContent.trim();
      // 判断纯文本内容是否非空
      return trimmedTextContent !== '';
    },
    /** 材料清单点击事件 **/
    handleMaterialItem(e, item) {
      let _this = this
      const targetElement = e.target;
      this.$el.querySelectorAll('.material-item').forEach(el => {
        el.classList.remove('material-selected');
      });
      targetElement.classList.add('material-selected');

      this.showMaterialInfo = true
      if (item) {
        let imgList = item.imgs ? item.imgs.split('*') : []
        item.imgList = imgList.map(item => _this.getAPIPath() + item)
        this.currMaterialInfo = item
      } else {
        this.currMaterialInfo = {}
      }

      let count = 0;
      let checkContentHeight = setInterval(function () {
        _this.loadImgSuccess()
        count++
        if (count > 10) clearInterval(checkContentHeight)
      }, 100)
    },
    loadImgSuccess() {
      let height = document.getElementsByClassName('material-content')[0].clientHeight
      let listHeight = document.getElementsByClassName('material-list')[0].clientHeight
      if (height < listHeight) {
        height = listHeight
      }
      console.log(height, listHeight)
      this.lineHeight = 'height: ' + height + 'px;'
    },
    /** 查询远程桌面列表 */
    getVncDesktopList() {
      listAllVncDesktop(this.queryParams).then(response => {
          this.desktopOptions = response.data;
        }
      );
    },
    /** 远程桌面选择事件 **/
    handleChange(id) {
      this.currDesktop = undefined
      getVncDesktop(id).then((response) => {
        this.currDesktop = response.data;
      });
    },
    /** 远程桌面 **/
    handleConnDesktop() {
      this.getVncDesktopList()
      this.dialogDesktopVisible = true
    },
    /** 取消远程桌面连接 **/
    handleBtnCancel() {
      this.currDesktop = undefined
      this.vncDesktop = undefined
      this.dialogDesktopVisible = false
      this.desktopOptions = []
    },
    /** 远程桌面连接 **/
    handleBtnConn() {
      history.pushState(null, null, document.URL);
      this.showDesktopConn = true
      this.dialogDesktopVisible = false
      let vnc = this.currDesktop
      if (vnc.path) {
        this.vncDesktopPath = vnc.path
      } else {
        this.vncDesktopPath = 'http://' + vnc.vncIp + ':' + vnc.vncPort
      }
    },
    /** 断开远程连接 **/
    closeConnDesktop() {
      this.showDesktopConn = false
      this.handleBtnCancel()
      this.vncDesktopPath = ''
    },
    /** 受理弹窗 **/
    handleDealWith() {
      this.dealWithForm.materials = []
      if (this.currMaterial.materialList.length > 1 ||
        (this.currMaterial.materialList.length == 1 && this.currMaterial.materialList[0].listName !== '无')) {
        this.dealWithForm.materials = JSON.parse(JSON.stringify(this.currMaterial.materialList))
      }
      getSerialNumber().then(response => {
        if (response.msg == "success") {
          this.dealWithForm.serialNumber = response.data
        } else {
          this.$modal.msgError("网络连接失败，请稍候再试");
        }
      });
    },
    /** 审查要点 */
    handleMaterialDetail(data, event) {
      if (data) {
        let imgList = data.imgs ? data.imgs.split('*') : []
        data.imgList = imgList.map(item => this.getAPIPath() + item)
        this.currMaterialInfo = data
      } else {
        this.currMaterialInfo = {}
      }
      this.dialogDealWithFormVisible = true
    },
    /** 人工核验 **/
    handleManualVerify(data, event) {
      this.$refs['dealWithForm'].validate((valid) => {
        if (valid) {
          let params = {
            "dealStatus": 0,
            "matterId": this.currMatter.id,
            "materialId": data.id,
            "materialName": data.listName
          }
          this.$confirm('您正在提交人工核验申请, 是否继续？', '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            addManualVerify(params).then((response) => {
              if (response.data > 0) {
                this.$modal.msgSuccess("提交成功");
                this.dealWithForm.materials.forEach((d) => {
                  if (d.id === data.id) {
                    d.manualVerifyId = response.data
                  }
                })
                this.$nextTick(() => {
                  this.dealWithKey ++
                })
              } else {
                this.$modal.msgError("提交失败");
              }
            });
          }).catch(() => {
          })
        } else {
          this.$modal.msgError("请检查必填项")
          return false;
        }
      })
    },
    /** 打印事件参数校验 **/
    handlePrintDealWith(elm) {
      this.$refs['dealWithForm'].validate((valid) => {
        if (valid) {
          if (elm == 'print_suc' || elm == 'print_onegzd') {
            let materialList = this.dealWithForm.materials
            let objs = materialList.filter(obj => obj.reasonFlag)
            if (materialList.length > 0 && objs.length == 0) {
              this.$modal.msgError("请选择相关材料")
              return
            }
            this.dealWithPrintInfo(objs, elm)
            document.getElementById(elm).click()
          }
          if (elm == 'print_fail') {
            let materialList = this.dealWithForm.materials
            let objs = materialList.filter(obj => !obj.reasonFlag)
            if (materialList.length == 0 || objs.length == 0) {
              this.$modal.msgError("当前没有缺失材料")
              return
            }
            this.dealWithMissPrintInfo()
            document.getElementById(elm).click()
          }
          if (elm == 'print_deny') {
            this.$prompt('请输入不予受理的理由和依据', '温馨提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
            }).then(({ value }) => {
              if (!value || !value.trim()) {
                this.$modal.msgError("理由和依据不能为空")
                return
              }
              this.dealWithDenyPrintInfo(value)
              document.getElementById(elm).click()
            }).catch(() => {
            })
          }
        } else {
          this.$modal.msgError("请检查必填项")
          return false;
        }
      })
    },
    /** 取消受理弹出框 **/
    handleCancelDealWith() {
      this.dealWithForm.id = undefined
      if (this.$refs['dealWithForm']) this.$refs['dealWithForm'].resetFields();
    },
    printDetail(id) {
      let params = {
        "id": id
      }
      getDealRecordById(params).then((response) => {
        if (response.data) {
          this.currDealRecord = response.data
          if (this.currDealRecord.materials) {
            let obj = JSON.parse(this.currDealRecord.materials)
            let manualVerifyList = []
            obj.forEach((item, index) => {
              if (item.verification === 1 && item.manualVerifyId) {
                manualVerifyList.push(item.manualVerifyId)
              }
            })
            if (manualVerifyList && manualVerifyList.length > 0) {
              getManualVerifyByIds(manualVerifyList).then(response => {
                let data = response.data
                obj.forEach((item, index) => {
                  data.forEach((d) => {
                    if (d.materialId == item.id) {
                      item.dealStatus = d.dealStatus
                      item.dealStatusName = d.dealStatus == 1 ? '人工核验通过' : (d.dealStatus == 2 ? '人工核验未通过' : '待核验')
                    }
                  })
                })
                this.$nextTick(() => {
                  this.currDealRecord.materialList = obj
                  this.detailKey ++
                })
              });
            } else {
              this.$nextTick(() => {
                this.currDealRecord.materialList = obj
                this.detailKey ++
              })
            }
          }
          this.dealDetailDialog = true
          return
        }
        this.$modal.msgError("查询数据失败")
      });
    },
    /** 保存受理信息 **/
    handleBtnSaveDealWith(withStatus) {
      this.$refs['dealWithForm'].validate((valid) => {
        if (valid) {
          let tempList = this.dealWithForm.materials
          for (let i = 0; i < tempList.length; i ++) {
            let d = tempList[i]
            if (!d.reasonFlag && !d.reason) {
              this.$modal.msgError("未选择的材料请填写理由")
              return
            }
            if (d.reasonFlag && d.verification == 1 && (!d.manualVerifyId || d.manualVerifyId <= 0)) {
              this.$modal.msgError("选择的材料中包含人工核验材料，请先提交人工审核")
              return
            }
          }
          let data = JSON.parse(JSON.stringify(this.dealWithForm))
          data.id = this.dealWithForm.id
          data.serialNumber = this.dealWithForm.serialNumber
          data.withStatus = withStatus
          data.matterId = this.currMatter.id
          data.materials = JSON.stringify(this.dealWithForm.materials)
          addDealRecord(data).then((response) => {
            if (response.code == 200) {
              this.dealWithForm.id = response.data
              this.$modal.msgSuccess("保存成功");
              if (withStatus == 1) {
                this.printDetail(response.data)
                this.handleCancelDealWith()
                this.handleDealWith()
              }
              return
            }
            this.$modal.msgError("保存失败")
          });
        } else {
          this.$modal.msgError("请检查必填项")
          return false;
        }
      })
    },
    handleSelectionChange(datas) {
      this.dealWithForm.materials.forEach((m) => {
        m.reasonFlag = false
        datas.forEach((d) => {
          if (d.id === m.id) {
            m.reasonFlag = true
          }
        })
      })
    },
    /** 新增打印日志 **/
    savePrintLog(elm, type) {
      let data = JSON.parse(JSON.stringify(this.dealWithForm))
      data.content = document.getElementById(elm).outerHTML
      data.printType = type
      data.matter = this.currMatter.id
      data.matterName = this.currMatter.itemName
      addPrintLog(data).then((response) => {
      });
    },
    /** 打印材料事件 **/
    handleMaterialPrint() {
      let printContent = document.getElementById('print_material').innerHTML;
      let windowObjectReference = window.open(null, 'Print', 'height=100%,width=100%');
      windowObjectReference.document.write('<html><head><title>审查事项材料清单</title>');
      windowObjectReference.document.write('</head><body >');
      windowObjectReference.document.write(printContent);
      windowObjectReference.document.write('</body></html>');
      windowObjectReference.document.close();
      windowObjectReference.print();
    }
  },
  destroyed() {
    window.removeEventListener("popstate", this.disableBrowserBack, false);
  }
};
</script>

<style scoped>
@media print {
  #print_material {
    height: 100%;
  }
}

.left-search-div {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 20px;
}

.matter-content {
  padding: 10px;
  border: 1px solid #cdc9c9;
  height: calc(100vh - 130px);
}

.matter-title {
  margin-top: 0px;
  background-color: #E7F0F9;
  color: #217BD3;
  font-weight: 600;
  display: flex;
  justify-content: center;
}

.matter-material {
  background-color: #E7F0F9;
  margin-top: 10px;
  min-height: 50px;
  border-radius: 8px;
  font-size: 14px;
  padding: 10px;
  word-wrap: break-word;
}

.material-item {
  padding: 5px;
  cursor: pointer;
  color: #82848a;
}

.material-selected {
  color: #ffffff;
  background-color: #82848a;
}

.el-button--primary.is-plain span {
  letter-spacing: 2px;
  line-height: 18px;
}

.custom-tree-node {
  display: flex;
  align-items: center;
}

.custom-tree-node .el-icon {
  margin-right: 8px;
}

.is-dept .el-icon {
  color: #409eff;
}

.is-matter .el-icon {
  color: green;
}

.material-line {
  width: 4px;
  border-radius: 2px;
  background: #c0c4cc;
  height: 100%;
  min-height: 50px;
}

.text-wrap-button {
  white-space: normal !important;
  word-break: break-all;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

::v-deep .popper-class {
  max-width: 300px;
}

::v-deep .el-checkbox__label {
  vertical-align: text-top;
  white-space: normal;
  word-break: break-all;
  width: 100%;
}
</style>

<style>
.el-alert__title {
  font-size: 18px !important;
  line-height: 36px !important;
}

.el-button--primary.is-plain {
  /* color: #575757!important; */
}

.el-button--primary.is-plain:focus,
.el-button--primary.is-plain:hover {
  color: #fff !important;
}

.ql-align-center {
  text-align: center;
}


.el-divider--horizontal {
  margin: 20px 0;
}

.qzprblem {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  /* 设置最大显示行数 */
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;

}

.custom-tree-node {
  width: calc(100% - 20px);
}

.custom-tree-node span {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.desktop-dialog {
  height: 100% !important;
}

.desktop-dialog > .el-dialog {
  margin-top: 0 !important;
  height: 100% !important;
}

.el-dialog__title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

.desktop-dialog > .el-dialog > .el-dialog__body {
  height: auto;
}

.vnc-desktop-dialog > .el-dialog {
  height: auto;
}

.vnc-desktop-dialog > .el-dialog > .el-dialog__body {
  height: 120px !important;
  overflow: hidden;
}

.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #aad6ff;
}

.matter-title > .el-alert__content > .el-alert__title {
  line-height: 24px !important;
}

.material-content {
  margin: 0 20px;
  height: 70vh;
  overflow: auto;
}
</style>
