<template>
  <div>
    <LHeader :text="text"></LHeader>
    <van-tabs v-model="active" @change="tabList" color="#2980f7" animated>
      <van-tab title="固有风险信息">
        <van-form
          @submit="onSubmit"
          :scroll-to-error="true"
          :show-error="false"
          validate-trigger="onSubmit"
        >
          <div
            style="
              height: 1rem;
              font-family: '微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑';
              font-weight: 700;
              line-height: 1rem;
            "
          >
            <img
              src="@/assets/accidentIcon/bookmark.svg"
              alt=""
              style="position: relative; top: 32%; transform: translateY(-50%)"
            />
            固有风险信息
          </div>
          <van-field
            readonly
            required
            name="userName"
            :value="form.userName"
            label="评估人"
            placeholder="请输入"
          />
          <van-field
            readonly
            required
            name="projectName"
            :value="form.projectName"
            label="所属项目"
            placeholder="请输入"
          />
          <van-field
            readonly
            required
            name="buildingName"
            :value="form.buildingName"
            label="所属建筑物"
            placeholder="请输入 "
          />

          <div style="display: flex">
            <van-field
              required
              clickable
              name="floorName"
              :value="form.floorName"
              label="所属楼层"
              placeholder="请选择"
              @click="seletFloor('floor')"
              :rules="[{ required: true, message: '所属楼层不能为空' }]"
            />
            <van-button
              style="color: #cccc; background-color: #f0f1f5"
              icon="plus"
              type="info"
              native-type="button"
              @click="createFloor"
            />
          </div>
          <div style="display: flex">
            <van-field
              readonly
              required
              name="roomName"
              :value="form.roomName"
              label="所属房间"
              placeholder="请输入"
              @click="seletRoom('room')"
              :rules="[{ required: true, message: '所属房间不能为空' }]"
            />
            <van-button
              style="color: #cccc; background-color: #f0f1f5"
              icon="plus"
              type="info"
              native-type="button"
              @click="tjfjClcik"
            />
          </div>

          <van-field
            required
            clickable
            name="name"
            v-model="form.name"
            label="危险源名称"
            placeholder="请输入"
            :rules="[{ required: true, message: '危险源名称不能为空' }]"
          />
          <!-- 单选 -->
          <van-field
            readonly
            required
            clickable
            name="pointType"
            v-model="form.pointType"
            label="风险点类型"
            placeholder="请选择"
            @click="selectData('pointType', true)"
            :rules="[{ required: true, message: '风险点类型不能为空' }]"
          />
          <van-field
            required
            label="是否为特种设备"
            v-show="form.pointType == '设备设施类'"
          >
            <template #input>
              <van-radio-group
                v-model="form.specialEquipment"
                direction="horizontal"
              >
                <van-radio :name="true">是</van-radio>
                <van-radio :name="false">否</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            v-if="form.specialEquipment == true"
            clickable
            name="pointType"
            v-model="form.equipmentNumber"
            label="特种设备的证书号码"
            placeholder="请选择"
          />
          <!-- 多选 -->
          <van-field
            v-model="form.safetyWarningSigns"
            readonly
            required
            name="safetyWarningSigns"
            label="安全警示标志"
            placeholder="请选择"
            @click="selectData('safetyWarningSigns', false)"
            :rules="[{ required: true, message: '安全警示标志不能为空' }]"
          />
          <van-field
            v-model="form.factor"
            readonly
            required
            name="factor"
            label="风险因素"
            placeholder="请选择"
            @click="selectData('factor', false)"
            :rules="[{ required: true, message: '风险因素不能为空' }]"
          />

          <van-field
            readonly
            v-model="form.type"
            required
            name="type"
            label="准事故类型"
            placeholder="请选择"
            @click="selectData('type', false)"
            :rules="[{ required: true, message: '准事故类型不能为空' }]"
          />

          <van-field
            readonly
            v-model="form.level"
            required
            name="level"
            label="风险等级"
            placeholder="请选择"
            @click="seletGrade"
            :rules="[{ required: true, message: '风险等级不能为空' }]"
          />
          <!-- <van-field readonly v-model="form.level" required name="level" label="风险等级" placeholder="请选择"
                @click="seletGrade('level')" :rules="[{ required: true, message: '风险等级不能为空' }]" /> -->

          <van-field
            required
            name="presenceLocation"
            v-model="form.presenceLocation"
            label="存在部位"
            placeholder="请输入"
            :rules="[{ required: true, message: '存在部位不能为空' }]"
          />

          <div
            style="
              height: 1rem;
              font-family: '微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑';
              font-weight: 700;
              line-height: 1rem;
            "
          >
            <img
              src="@/assets/accidentIcon/bookmark.svg"
              alt=""
              style="position: relative; top: 32%; transform: translateY(-50%)"
            />
            风险图片
          </div>
          <van-field name="hdPicture1" label="风险图片">
            <template #input>
              <van-uploader
                @delete="deleteFile(...arguments, 'pictureFile')"
                multiple
                :max-count="5"
                upload-text="最多上传五个"
                v-model="uploaderImg"
              >
                <template slot="default">
                  <!-- 11111111111 -->
                  <div
                    style="
                      width: 2.13333rem;
                      height: 2.13333rem;
                      background: #f7f8fa;
                      display: flex;
                      align-items: center;
                      justify-content: center;
                      flex-direction: column;
                    "
                  >
                    <img
                      src="@/assets/upload/pic.png"
                      alt=""
                      style="width: 0.64rem; height: 0.64rem"
                    />
                    <span class="van-uploader__upload-text">最多上传五个</span>
                  </div>
                </template>
              </van-uploader>
            </template>
          </van-field>
          <div
            style="
              height: 1rem;
              font-family: '微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑';
              font-weight: 700;
              line-height: 1rem;
            "
          >
            <img
              src="@/assets/accidentIcon/bookmark.svg"
              alt=""
              style="position: relative; top: 32%; transform: translateY(-50%)"
            />
            应采取的管控措施
          </div>
          <van-field label="技术措施">
            <template #input>
              <van-field
                v-model="form.measuresProject"
                name="measuresProject"
                label=""
                type="textarea"
                rows="3"
                autosize
                placeholder="请输入"
                style="padding-left: 0; padding-top: 0"
              />
            </template>
          </van-field>
          <van-field name="measuresProjectFile[]" label="技术措施附件">
            <template #input>
              <van-uploader
                multiple
                :max-count="5"
                upload-text="最多上传五个"
                v-model="measuresProjectFile"
                accept="file"
                @delete="deleteFile(...arguments, 'measuresProjectFile')"
              >
                <template slot="default">
                  <div
                    style="
                      width: 2.13333rem;
                      height: 2.13333rem;
                      background: #f7f8fa;
                      display: flex;
                      align-items: center;
                      justify-content: center;
                      flex-direction: column;
                    "
                  >
                    <img
                      src="@/assets/upload/file.png"
                      alt=""
                      style="width: 0.64rem; height: 0.64rem"
                    />
                    <span class="van-uploader__upload-text">最多上传五个</span>
                  </div>
                </template>
              </van-uploader>
            </template>
          </van-field>
          <van-field label="管理措施">
            <template #input>
              <van-field
                v-model="form.measuresAdministration"
                name="measuresAdministration"
                label=""
                type="textarea"
                rows="3"
                autosize
                placeholder="请输入"
                style="padding-left: 0; padding-top: 0"
              />
            </template>
          </van-field>
          <van-field name="measuresAdministrationFile[]" label="管理措施附件">
            <template #input>
              <van-uploader
                multiple
                :max-count="5"
                upload-text="最多上传五个"
                v-model="measuresAdministrationFile"
                accept="file"
                @delete="deleteFile(...arguments, 'measuresAdministrationFile')"
              >
                <template slot="default">
                  <div
                    style="
                      width: 2.13333rem;
                      height: 2.13333rem;
                      background: #f7f8fa;
                      display: flex;
                      align-items: center;
                      justify-content: center;
                      flex-direction: column;
                    "
                  >
                    <img
                      src="@/assets/upload/file.png"
                      alt=""
                      style="width: 0.64rem; height: 0.64rem"
                    />
                    <span class="van-uploader__upload-text">最多上传五个</span>
                  </div>
                </template>
              </van-uploader>
            </template>
          </van-field>
          <van-field label="应急措施">
            <template #input>
              <van-field
                v-model="form.measuresEmergency"
                name="measuresEmergency"
                label=""
                type="textarea"
                rows="3"
                autosize
                placeholder="请输入"
                style="padding-left: 0; padding-top: 0"
              />
            </template>
          </van-field>
          <van-field name="measuresEmergencyFile[]" label="应急措施附件">
            <template #input>
              <van-uploader
                multiple
                :max-count="5"
                upload-text="最多上传五个"
                v-model="measuresEmergencyFile"
                accept="file"
                @delete="deleteFile(...arguments, 'measuresEmergencyFile')"
              >
                <template slot="default">
                  <!-- 11111111111 -->
                  <div
                    style="
                      width: 2.13333rem;
                      height: 2.13333rem;
                      background: #f7f8fa;
                      display: flex;
                      align-items: center;
                      justify-content: center;
                      flex-direction: column;
                    "
                  >
                    <img
                      src="@/assets/upload/file.png"
                      alt=""
                      style="width: 0.64rem; height: 0.64rem"
                    />
                    <span class="van-uploader__upload-text">最多上传五个</span>
                  </div>
                </template>
              </van-uploader>
            </template>
          </van-field>

          <van-field
            v-model="form.measuresDeptName"
            name="measuresDeptName"
            label="管控责任单位 "
            type="input"
            rows="1"
            autosize
            placeholder="请输入"
            list="measure-deptname"
            @input="measuresDeptNameChange"
          />
          <datalist id="measure-deptname">
            <option
              :value="item.measuresDeptName"
              v-for="item in measureDeptList"
              :key="item.measuresDeptName"
            ></option>
          </datalist>
          <van-field
            v-model="form.measuresUserName"
            name="measuresUserName"
            label="管控责任人 "
            type="input"
            rows="1"
            autosize
            placeholder="请输入"
            list="measure-name"
            @input="measuresUserNameChange"
          />
          <datalist id="measure-name">
            <option
              v-for="item in measureNameList"
              :key="item.measuresUserName"
              :value="item.measuresUserName"
            ></option>
          </datalist>
          <van-field
            v-model="form.measuresUserPhone"
            name="measuresUserPhone"
            label="管控责任人联系方式"
            type="input"
            rows="1"
            autosize
            placeholder="请输入"
            maxlength="11"
          />

          <div
            style="
              height: 1rem;
              font-family: '微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑';
              font-weight: 700;
              line-height: 1rem;
            "
          >
            <img
              src="@/assets/accidentIcon/bookmark.svg"
              alt=""
              style="position: relative; top: 32%; transform: translateY(-50%)"
            />
            重大危险源管理
          </div>

          <van-field name="majorHazardSource" label="是否为重大危险源">
            <template #input>
              <span style="margin-right: 10px; color: red">否</span>
              <van-switch v-model="form.majorHazardSource" size="20" />
              <span style="margin-left: 10px; color: green">是</span>
            </template>
          </van-field>
          <van-field
            :disabled="!form.majorHazardSource"
            v-model="form.hazardSourceName"
            :required="form.majorHazardSource"
            name="hazardSourceName"
            label="危险源名称 "
            type="textarea"
            rows="1"
            autosize
            placeholder="请输入"
            :key="form.majorHazardSource + '123'"
            :rules="
              form.majorHazardSource
                ? [{ required: true, message: '危险源名称不能为空' }]
                : []
            "
          />
          <van-field
            label="重大危险源描述"
            :disabled="!form.majorHazardSource"
            :required="form.majorHazardSource"
          >
            <template #input>
              <van-field
                :disabled="!form.majorHazardSource"
                v-model="form.majorHazardSourceDescription"
                name="majorHazardSourceDescription"
                type="textarea"
                rows="3"
                autosize
                placeholder="请输入"
                :key="form.majorHazardSource + '456'"
                :rules="
                  form.majorHazardSource
                    ? [{ required: true, message: '重大危险源描述不能为空' }]
                    : []
                "
                style="padding-left: 0; padding-top: 0"
              />
            </template>
          </van-field>
          <van-field
            :disabled="!form.majorHazardSource"
            :required="form.majorHazardSource"
            readonly
            clickable
            name="referenceBasis"
            :value="form.referenceBasis == 'null' ? '' : form.referenceBasis"
            label="判断依据"
            placeholder="请选择"
            :key="form.majorHazardSource + '789'"
            :rules="
              form.majorHazardSource
                ? [{ required: true, message: '判断依据不能为空' }]
                : []
            "
            @click="
              () => {
                if (form.majorHazardSource) {
                  selectData('referenceBasis', false);
                }
              }
            "
          />
          <!-- <div
            style="height: 1rem;font-family: '微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑';font-weight: 700;line-height: 1rem;"
          >
            <img
              src="@/assets/accidentIcon/bookmark.svg"
              alt=""
              style="position: relative;top: 32%;transform: translateY(-50%);"
            />
            判断依据
          </div> -->

          <van-dialog
            v-model="showGradeDialog"
            title="风险评测配置"
            :show-cancel-button="false"
            :show-confirm-button="false"
          >
            <div class="dialogContain">
              <van-collapse v-model="activeNames">
                <van-collapse-item title="风险模型" name="1">
                  <van-field
                    readonly
                    required
                    name="level"
                    label="当前风险模型"
                    placeholder="LS风险矩阵评估模型"
                  />
                </van-collapse-item>
                <van-collapse-item title="风险模型配置" name="2">
                  <van-popover
                    v-model="showPopover"
                    trigger="click"
                    :actions="columnsRiskRank"
                    @select="onSelect"
                  >
                    <template #reference>
                      <van-field
                        v-model="possibleValue"
                        readonly
                        required
                        name="level"
                        label="发生的可能性"
                        placeholder="请选择"
                      />
                    </template>
                  </van-popover>
                  <van-popover
                    v-model="showPopoveSetRank"
                    trigger="click"
                    :actions="columnsSetRank"
                    @select="onSelectSetRank"
                  >
                    <template #reference>
                      <van-field
                        v-model="severityValue"
                        readonly
                        required
                        name="level"
                        label="后果严重程度"
                        placeholder="请选择"
                      />
                    </template>
                  </van-popover>
                </van-collapse-item>
              </van-collapse>
              <van-row type="flex" justify="center" style="margin-top: 10px">
                <van-col span="6"
                  ><van-button
                    size="small"
                    plain
                    native-type="button"
                    type="info"
                    @click="showGradeDialog = false"
                    >取消</van-button
                  ></van-col
                >
                <van-col span="6"
                  ><van-button
                    size="small"
                    type="info"
                    native-type="button"
                    @click="goResultPage"
                    >开始测评</van-button
                  ></van-col
                >
              </van-row>
            </div>
          </van-dialog>
          <!-- 楼层弹出层 -->
          <van-popup
            v-model="ShowfloorList"
            position="bottom"
            :style="{ height: '100%' }"
          >
            <selectFloor
              v-if="ShowfloorList"
              :listdata="floorSource"
              @closeSlect="closeSlectfloor"
              @saveSlect="saveSlectfloor"
            ></selectFloor>
          </van-popup>

          <!-- 单选弹出层 -->
          <van-popup v-model="showSelect" position="bottom">
            <van-picker
              v-if="showSelect"
              show-toolbar
              value-key="dictValue"
              :columns="columnsData"
              @confirm="saveSelect"
              @cancel="showSelect = false"
            />
          </van-popup>
          <!-- 复选弹出层 -->
          <van-popup
            v-model="showCheckSelect"
            position="bottom"
            :style="{ height: '100%' }"
          >
            <selectList
              v-if="showCheckSelect"
              :listdata="columnsCheckData"
              @closeSlect="showCheckSelect = false"
              @saveSlect="saveCheckSelect"
            ></selectList>
          </van-popup>

          <!-- 房间弹出层 -->
          <van-popup v-model="showSource" position="bottom">
            <van-picker
              v-if="showSource"
              show-toolbar
              value-key="name"
              :columns="columnsSource"
              @confirm="onConSource"
              @cancel="showSource = false"
            />
          </van-popup>
          <!-- 管控责任单位 -->
          <van-popup
            v-model="measuresDept"
            position="bottom"
            :style="{ height: '100%' }"
          >
            <div
              class="van-picker__toolbar"
              style="position: absolute; width: 100%; top: 0"
            >
              <button
                type="button"
                class="van-picker__cancel"
                v-on:click="
                  {
                    form.measuresDeptId = 0;
                    projectDept = false;
                  }
                "
              >
                取消</button
              ><button
                type="button"
                class="van-picker__confirm"
                @click="closeDept"
              >
                确认
              </button>
            </div>
            <div style="display: flex; margin-top: 44px">
              <selectDept
                v-if="measuresDept"
                @changeDept="changeDept"
              ></selectDept>
            </div>
          </van-popup>
          <!-- 管控责任人 -->
          <van-popup v-model="showTrouble" position="bottom">
            <van-picker
              show-toolbar
              value-key="nickName"
              :columns="columnsTrouble"
              @confirm="onConTrouble"
              @cancel="showTrouble = false"
            />
          </van-popup>
          <div style="margin: 16px 16px 0">
            <van-button
              round
              block
              type="info"
              @click="onSubmit('save', $event)"
              >保存</van-button
            >
          </div>
          <div style="margin: 16px 16px 0">
            <van-button
              :loading="loadingStatus"
              :loading-text="loadingText"
              round
              block
              type="info"
              native-type="submit"
              >提交</van-button
            >
          </div>
        </van-form>
        <div style="margin: 10px 16px 0px; padding-bottom: 16px">
          <van-button round block type="warning" @click.native="cancel"
            >取消</van-button
          >
        </div>
      </van-tab>
      <van-tab title="现状风险">
        <div class="con-list">
          <van-cell-group
            inset
            v-for="(item, index) in messageList"
            @click="touchstart(index, item)"
            :key="item.id"
          >
            <div style="font-size: 0.45rem; padding: 5px 0">
              {{ item.name }}
            </div>
            <van-row gutter="">
              <van-col span="17">
                <van-row gutter="">
                  <van-col span="9">发起时间：</van-col>
                  <van-col span="15">{{
                    timestampToTimes(item.createTime)
                  }}</van-col>
                </van-row>
                <van-row gutter="">
                  <van-col span="9">楼层：</van-col>
                  <van-col span="15">{{ item.floorName }}</van-col>
                </van-row>
                <van-row gutter="">
                  <van-col span="9">房间：</van-col>
                  <van-col span="15">{{ item.roomName }}</van-col>
                </van-row>
              </van-col>
              <!-- <van-col span="7" :style="{ color: item.state == 1 ? '#0069e5' : '#03b615' }">
                  {{ "●待审批" }}
                </van-col> -->
            </van-row>
            <van-overlay :show="showIndex == index">
              <div class="wrapper" @click.stop="showIndex = null">
                <van-button round type="primary" @click="goDetail(item)"
                  >编辑</van-button
                >
                <van-button round type="danger" @click="delInherent(item)"
                  >删除</van-button
                >
              </div>
            </van-overlay>
          </van-cell-group>
          <div
            style="
              width: 100%;
              text-align: center;
              font-size: 0.48rem;
              position: fixed;
              top: 30%;
            "
            v-if="messageList['length'] == 0"
          >
            暂无数据
          </div>
        </div>
      </van-tab>
    </van-tabs>

    <div
      v-if="active != 0"
      style="
        display: flex;
        justify-content: space-around;
        background-color: #fff;
        border-top: 1px solid #e3e3e3;
        height: 1.5rem;
        width: 100%;
        text-align: center;
        position: fixed;
        bottom: 0;
      "
    >
      <div
        @click="performTasks"
        style="color: #4bced0; font-size: 14px; font-weight: 600"
      >
        <div style="font-size: 22px"><van-icon name="plus" /></div>
        <div>新增现状风险</div>
      </div>
    </div>
    <!-- 楼层弹出层 -->
    <van-popup
      v-model="ShowfloorList"
      position="bottom"
      :style="{ height: '100%' }"
    >
      <selectFloor
        :listdata="floorSource"
        @closeSlect="closeSlectfloor"
        @saveSlect="saveSlectfloor"
      ></selectFloor>
    </van-popup>

    <!-- 单选弹出层 -->
    <van-popup v-model="showSelect" position="bottom">
      <van-picker
        show-toolbar
        value-key="dictValue"
        :columns="columnsData"
        @confirm="saveSelect"
        @cancel="showSelect = false"
      />
    </van-popup>
    <!-- 复选弹出层 -->
    <van-popup
      v-model="showCheckSelect"
      position="bottom"
      :style="{ height: '100%' }"
    >
      <selectList
        v-if="showCheckSelect"
        :listdata="columnsCheckData"
        @closeSlect="showCheckSelect = false"
        @saveSlect="saveCheckSelect"
      ></selectList>
    </van-popup>

    <!-- 房间弹出层 -->
    <van-popup v-model="showSource" position="bottom">
      <van-picker
        show-toolbar
        value-key="name"
        :columns="columnsSource"
        @confirm="onConSource"
        @cancel="showSource = false"
      />
    </van-popup>
    <!-- 管控责任单位 -->
    <van-popup
      v-model="measuresDept"
      position="bottom"
      :style="{ height: '100%' }"
    >
      <div
        class="van-picker__toolbar"
        style="position: absolute; width: 100%; top: 0"
      >
        <button
          type="button"
          class="van-picker__cancel"
          v-on:click="
            {
              form.measuresDeptId = 0;
              projectDept = false;
            }
          "
        >
          取消</button
        ><button type="button" class="van-picker__confirm" @click="closeDept">
          确认
        </button>
      </div>
      <div style="display: flex; margin-top: 44px">
        <selectDept @changeDept="changeDept"></selectDept>
      </div>
    </van-popup>
    <div v-if="isFloor">
      <addFloor @close="closeFloor" :buildingId="form.buildingId" />
    </div>
    <!-- 管控责任人 -->
    <van-popup v-model="showTrouble" position="bottom">
      <van-picker
        show-toolbar
        value-key="nickName"
        :columns="columnsTrouble"
        @confirm="onConTrouble"
        @cancel="showTrouble = false"
      />
    </van-popup>
  </div>
</template>

<script>
import { Dialog } from "vant";
import LHeader from "@/components/header.vue";
import selectDept from "@/components/selectDept/index.vue";
import SelectList from "@/components/selectList.vue";
import selectFloor from "@/components/selectFloor.vue";
import { getUserInfo, getLocalUserInfo } from "@/utils/userInfo";
import { getFun, postFun } from "@/service/table.js";
import { timestampToTime, generateId } from "@/utils/format";
import addFloor from "./addFloor";

export default {
  name: "addCurrent",
  components: {
    LHeader,
    selectDept,
    SelectList,
    selectFloor,
    addFloor,
  },
  activated() {
    this.showSetRank = false; // 再次关闭弹出层 以防万一
    this.getList();
    this.$bus.$on("riskLevelBus", (res) => {
      this.showSetRank = false; // 再次关闭弹出层 以防万一
      console.log(Boolean(res));
      if (res) {
        this.riskRank = res;
      } else {
        this.setRank = "";
      }
      // 销毁一下监听事件 不然会越加越多
      this.$bus.$off("riskLevelBus");
    });
  },
  beforeRouteEnter(to, from, next) {
    if (from.name == "riskInherent") {
      sessionStorage.setItem("inherenForm", "");
      sessionStorage.setItem("level", "");
    }
    next();
  },
  beforeRouteLeave(to, from, next) {
    if (to.name != "riskInherent") {
      sessionStorage.setItem("inherenForm", JSON.stringify(this.form));
    }
    next();
  },
  data() {
    return {
      isFloor: false,
      loadingStatus: false,
      loadingText: "提交...",
      measureNameList: [],
      measureDeptList: [],
      showIndex: null,
      measuresDept: false,
      ShowfloorList: false,
      floorSource: [],
      dataName: "",
      // 单选
      showSelect: false,
      columnsData: [],

      // 多选
      showCheckSelect: false,
      columnsCheckData: [],

      ShowAccidentList: false,
      ShowSelectList: false,
      showPopoveSetRank: false,
      activeNames: ["1"],
      showPopover: false,
      showGradeDialog: false,
      taskId: "",
      text: "编辑固有风险",
      id: "",
      isTimely: 1,
      active: 0,
      form: {},
      projectId: "", // 所属工程
      projectName: "", // 所属工程
      projectDirectorName: "", // 所属工程
      projectDirector: "", // 所属工程
      showProjectName: false,
      show: false,
      columnsProjectName: [],
      factor: "", //风险因素
      showFactor: false,
      columnsFactor: [],
      source: "", //风险源
      userPrefix: "", //风险源
      showSource: false,
      columnsSource: [],
      trouble: "", //事故类型
      columnsAccident: [],
      showTrouble: false,
      columnsTrouble: [],
      setRank: "", //风险定级
      showSetRank: false,
      columnsSetRank: ["矩阵式定级", "其他定级方式"], //严重程度
      riskRank: "", // 风险等级
      showRiskRank: false,
      columnsRiskRank: [], //发生可能性
      showSetRankMode: false, // 是否显示定级方式
      setRankMode: "", // 定级方式文字
      setRankModeImg: [], // 定级方式图片
      uploaderImg: [], // 定级方式图片
      location: "", //风险部位
      control: "", //管控层级
      riskName: "", //管控层级
      showControl: false,
      columnsControl: ["项目级", "企业级"],
      mainDutyDept: "", // 主责部门
      mainDutyDeptId: "",
      showMainDutyDept: false,
      columnsMainDutyDept: [],
      mainDutyPeopLe: "", // 主责人员
      mainDutyPeopLeId: "",
      showMainDutyPeopLe: false,
      columnsMainDutyPeopLe: [],
      technology: "", //技术措施文字
      technologyImg: [], //技术措施图片
      administration: "", //管理措施文字
      measuresAdministrationFile: [], //管理措施图片
      measuresProjectFile: [], //管理措施图片
      measuresEmergencyFile: [], //管理措施图片
      urgent: "", //应急措施文字
      urgentImg: [], //应急措施图片
      returnCause: "", // 退回原因
      isShowreturnCause: false,
      possibleValue: "",
      possibleScore: 0,
      severityValue: "",
      severityScore: 0,
      messageList: [],
      inherentId: 0,
      buildingIds: "",
    };
  },
  created() {
    if (this.$route.params.inherentId || sessionStorage.getItem("inherentId")) {
      this.inherentId =
        this.$route.params.inherentId || sessionStorage.getItem("inherentId");
      this.buildingIds =
        this.$route.params.buildingId || sessionStorage.getItem("buildingId");
      this.postReturnEcho();
    }
  },
  mounted() {
    if (sessionStorage.getItem("inherenForm") != "") {
      this.form = JSON.parse(sessionStorage.getItem("inherenForm"));
      this.form.level = sessionStorage.getItem("level");
    }
  },
  methods: {
    createFloor() {
      this.isFloor = true;
    },
    closeFloor(data) {
      if (data) {
        this.getFloor().then(() => {
          const floors = [].concat(
            this.floorSource.map((x) => x.children).flat()
          );
          const currentFloor = floors.find((x) => x.id === data);
          console.log(floors, currentFloor);
          if (currentFloor) {
            this.saveSlectfloor(currentFloor);
          }
        });
      }
      this.isFloor = false;
    },
    measuresUserNameChange(e) {
      getFun(
        `/risk/plan/inherent/getResponsibilityPersons?personName=${e}&projectId=${this.form.projectId}`
      ).then((res) => {
        this.measureNameList = res.data;
        this.measureNameList.forEach((item) => {
          if (item.measuresUserName == e)
            this.form.measuresUserPhone = item.measuresUserPhone;
        });
        console.log(e, 1111);
      });
    },
    measuresDeptNameChange(e) {
      getFun(
        `/risk/plan/inherent/getResponsibilityUnits?unitName=${e}&projectId=${this.form.projectId}`
      ).then((res) => {
        this.measureDeptList = res.data;
      });
    },
    // 详情
    goDetail(data) {
      sessionStorage.setItem("inherentId", this.inherentId);
      sessionStorage.setItem("existingId", data.id);

      this.$router.push({
        name: "addPresent",
        params: {
          inherentId: this.inherentId,
          existingId: data.id,
          isEdit: true,
        },
      });
      this.showIndex = null;
    },

    delInherent(item) {
      Dialog.confirm({
        title: "删除现有风险",
        message: "是否确认删除？",
      })
        .then(() => {
          // on confirm
          getFun(`/risk/plan/existing/delete/${item.id}`).then((res) => {
            this.$toast.success(res.msg);
            this.getList();
            // });
          });
          {
            inherentId;
          }
        })
        .catch(() => {
          // on cancel
        });
    },
    afterRead(file) {
      console.log(file);
    },
    timestampToTimes(time) {
      return timestampToTime(new Date(time), "DT2", true);
    },
    touchstart(index, item) {
      if (this.showIndex != null) {
        this.showIndex = null;
        return;
      }
      this.showIndex = index;
    },
    tabList(value) {
      console.log(
        "%c [ value ]-527",
        "font-size:13px; background:pink; color:#bf2c9f;",
        value
      );
      if (value == 1) {
        this.getList();
      }
    },
    // 请求表单数据
    getList() {
      getFun(`/risk/plan/existing/list/${this.inherentId}`)
        .then((res) => {
          console.log(
            "%c [ res ]-670",
            "font-size:13px; background:pink; color:#bf2c9f;",
            res
          );
          this.messageList = res.data;
        })
        .catch(() => {
          this.$toast.fail("加载失败,请稍后再试");
        });
    },
    // 请求详情数据
    postReturnEcho() {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      getFun(`/risk/plan/inherent/details/${this.inherentId}`)
        .then((res) => {
          this.form = res.data;
          this.getFloor();
          this.uploaderImg = (res.data.pictureFile || []).map((item) => {
            return {
              ...item,
              url: item.filePath,
            };
          });
          this.measuresProjectFile = (res.data.measuresProjectFile || []).map(
            (item) => {
              return {
                ...item,
                url: item.filePath,
              };
            }
          );
          this.measuresAdministrationFile = (
            res.data.measuresAdministrationFile || []
          ).map((item) => {
            return {
              ...item,
              url: item.filePath,
            };
          });
          this.measuresEmergencyFile = (
            res.data.measuresEmergencyFile || []
          ).map((item) => {
            return {
              ...item,
              url: item.filePath,
            };
          });
        })
        .catch(() => {
          this.$toast.clear();
        });
    },
    // 项目负责人
    onConTrouble(value) {
      if (!value) {
        this.showTrouble = false;
        return;
      }
      this.form[this.userPrefix + "Id"] = value.userId;
      this.form[this.userPrefix + "Name"] = value.nickName;
      this.showTrouble = false;
    },
    getUserData(e) {
      this.userPrefix = e;
      if (!this.form.measuresDeptId) {
        this.$toast({
          title: "提示",
          message: "请选择管控责任单位!",
        });
        return false;
      }
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      getFun(`/risk/plan/user/list/${this.form.measuresDeptId}`).then((res) => {
        if (res.code == 200) {
          this.columnsTrouble = res.data;
          // 对数据进行赋值
          this.$toast.clear();
          this.showTrouble = true;
        } else {
          this.$toast.clear();
        }
      });
    },
    changeDept(id, name) {
      this.form.measuresDeptId = id;
      this.form.measuresDeptName = name;
    },
    closeDept() {
      this.measuresDept = false;
    },
    selectData(dataName, isSinge) {
      this.dataName = dataName;
      getFun(
        `/risk/plan/dict/data/list?dictType=risk_plan_${dataName.toLowerCase()}`
      )
        .then((res) => {
          if (isSinge) {
            this.columnsData = res.data;
            this.showSelect = true;
          } else {
            this.columnsCheckData = res.data;
            this.showCheckSelect = true;
          }
          console.log(this.showSelect);
        })
        .catch(() => {
          this.$toast.fail("加载失败,请稍后再试");
        });
    },
    saveSelect(data) {
      this.form[this.dataName] = data.dictValue;
      this.showSelect = false;
    },
    saveCheckSelect(data) {
      this.form[this.dataName] = data.join(",");
      this.showCheckSelect = false;
    },
    renameKeyInTree(data, oldKey, newKey) {
      let arr = data.map((item) => {
        const newItem = { ...item };

        if (item.hasOwnProperty(oldKey)) {
          newItem[newKey] = newItem[oldKey];
          delete newItem[oldKey];
        }

        if (newItem.children && newItem.children.length > 0) {
          newItem.children = this.renameKeyInTree(
            newItem.children,
            oldKey,
            newKey
          );
        }
        return newItem;
      });

      return arr;
    },
    getFloor() {
      return getFun(`/risk/plan/floor/list/${this.form.buildingId}`)
        .then((res) => {
          // this.$toast.clear();
          // this.showSource = true;

          let newArr = this.renameKeyInTree(res.data, "name", "text");
          this.floorSource = newArr;
        })
        .catch(() => {
          this.$toast.fail("加载失败,请稍后再试");
        });
    },
    seletFloor(name) {
      this.ShowfloorList = true;
      this.userPrefix = name;
    },
    seletRoom(name) {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      this.userPrefix = name;
      getFun(`/risk/plan/room/list/${this.form.floorId}`)
        .then((res) => {
          this.$toast.clear();
          this.showSource = true;
          this.columnsSource = res.data;
        })
        .catch(() => {
          this.$toast.fail("加载失败,请稍后再试");
        });
    },

    //风险等级
    seletGrade(name) {
      this.getGradeList("possibility");
      this.getGradeList("severity");
      this.showGradeDialog = true;
    },
    //风险模型配置
    getGradeList(type) {
      // possibility 可能性 severity 严重性
      getFun(`/risk/plan/matrix/${type}/list`).then((res) => {
        let arr = [];
        res.data.forEach((item) => {
          arr.push({
            text: item.title,
            type: item.type,
            sort: item.sort,
            score: item.score,
          });
        });
        if (type === "possibility") {
          this.columnsRiskRank = arr;
        } else {
          this.columnsSetRank = arr;
        }
      });
    },

    closeSlectfloor() {
      this.ShowfloorList = false;
    },
    saveSlectfloor(data) {
      if (this.form.floorId != data.id) {
        this.form.roomName = "";
      }
      this.form.floorId = data.id;
      this.form.floorName = data.text;
      this.ShowfloorList = false;
    },

    onSelect(data) {
      this.possibleValue = data.text;
      this.possibleScore = data.score;
    },
    onSelectSetRank(data) {
      this.severityValue = data.text;
      this.severityScore = data.score;
    },
    //开始测评
    goResultPage() {
      this.$router.push({
        name: "resultPage",
        params: {
          score: this.severityScore * this.possibleScore,
          possibleValue: this.possibleValue,
          severityValue: this.severityValue,
        },
      });
    },
    performTasks() {
      sessionStorage.setItem("inherentId", this.inherentId);
      this.$router.push({
        name: "addPresent",
        params: {
          inherentId: this.inherentId,
          isEdit: false,
        },
      });
    },
    // 点击预览图
    clickPre(e) {
      console.log(e);
      if (e.filePath) {
        this.videoUrl = e.filePath;
      } else {
        this.videoUrl = e.content;
      }
    },
    async deleteFile(val, detail, key) {
      // console.log(val,detail)
      if (val.fileId) {
        let formdata = new FormData();
        formdata.append("key", val["fileId"]);
        var ids = this.form[key + "Ids"].split(",");
        const ind = ids.findIndex((x) => x == val.fileId);
        ids.splice(ind, 1);
        this.form[key + "Ids"] = ids.join(",");
        this.form[key].splice(detail.index, 1);
        console.log(ids, this.form[key], "ddd");
        this.$toast({
          title: "提示",
          message: "删除成功!",
        });
      }
    },
    jsonToFormData(config) {
      const formData = new FormData();
      //循环传入的值转换formData
      Object.keys(config).forEach((key) => {
        formData.append(key, config[key]);
      });
      return formData;
    },
    onSubmit(values, event) {
      if (values == "save") {
        event.preventDefault();
      }
      // console.log('%c [ values ]-592', 'font-size:13px; background:pink; color:#bf2c9f;', values)
      var formDataJson = this.jsonToFormData(this.form);
      let url = "/risk/plan/inherent";
      this.loadingStatus = true;
      this.uploaderImg.forEach((item) => {
        if (item.file) {
          formDataJson.append("pictureFile[]", item.file);
        } else {
          formDataJson.append("pictureFile[]", item.fileId);
        }
      });
      this.measuresAdministrationFile.forEach((item) => {
        if (item.file) {
          formDataJson.append("measuresProjectFile[]", item.file);
        } else {
          formDataJson.append("measuresProjectFile[]", item.fileId);
        }
      });
      this.measuresEmergencyFile.forEach((item) => {
        if (item.file) {
          formDataJson.append("measuresEmergencyFile[]", item.file);
        } else {
          formDataJson.append("measuresEmergencyFile[]", item.fileId);
        }
      });
      this.measuresAdministrationFile.forEach((item) => {
        if (item.file) {
          formDataJson.append("measuresAdministrationFile[]", item.file);
        } else {
          formDataJson.append("measuresAdministrationFile[]", item.fileId);
        }
      });
      // (values.hdPicture1 || []).forEach(item => {
      //   if (item.file) {
      //     formDataJson.append("pictureFile[]", item.file);
      //   } else {
      //     formDataJson.append("pictureFile[]", item.fileId);
      //   }
      // });
      // values["measuresProjectFile[]"].forEach(item => {
      //   if (item.file) {
      //     formDataJson.append("measuresProjectFile[]", item.file);
      //   } else {
      //     formDataJson.append("measuresProjectFile[]", item.fileId);
      //   }
      // });
      // values["measuresEmergencyFile[]"].forEach(item => {
      //   if (item.file) {
      //     formDataJson.append("measuresEmergencyFile[]", item.file);
      //   } else {
      //     formDataJson.append("measuresEmergencyFile[]", item.fileId);
      //   }
      // });
      // values["measuresAdministrationFile[]"].forEach(item => {
      //   if (item.file) {
      //     formDataJson.append("measuresAdministrationFile[]", item.file);
      //   } else {
      //     formDataJson.append("measuresAdministrationFile[]", item.fileId);
      //   }
      // });
      postFun(url, formDataJson)
        .then((res) => {
          this.$toast.clear();
          this.$toast.success({
            message: "提交成功",
            duration: 2000,
          });
          this.loadingStatus = false;
          history.go(-1);
        })
        .catch(() => {
          this.$toast.clear();
          this.$toast.fail("提交失败,请稍后再试");
          this.loadingStatus = false;
        });
      this.$toast.clear();
    },

    // 所属项目
    onConProjectName(value) {
      if (!value) {
        this.showProjectName = false;
        return;
      }
      this.projectId = value.id;
      this.projectName = value.projectName;
      this.showProjectName = false;
    },
    // 风险因素
    onConFactor(value) {
      if (!value) {
        this.showFactor = false;
        return;
      }
      this.factor = value.factorType;
      this.showFactor = false;
      this.source = "";
      this.trouble = "";
      // 请求风险源
      postHdSource(`/riskMain/showSourceName?factorType=${this.factor}`).then(
        (res) => {
          this.columnsSource = res.data;
        }
      );
    },
    // 房间
    onConSource(value) {
      if (!value) {
        this.showSource = false;
        return;
      }
      this.form[this.userPrefix + "Id"] = value.id;
      this.form[this.userPrefix + "Name"] = value.name;
      this.showSource = false;
    },
    // 风险定级
    onConSetRank(value) {
      this.showSetRank = false;
      this.setRank = value;
      this.riskRank = "";
      if (this.setRank == "矩阵式定级") {
        this.showSetRank = false;
        this.$router.push({
          name: "matrix-grad",
        });
      }
    },
    // 自己定义风险等级点击方法
    myRiskRank() {
      if (this.setRank == "") {
        this.$toast("请先选择风险定级");
      } else if (this.setRank == "其他定级方式") {
        this.showRiskRank = true;
      }
    },
    // 风险等级
    onConRiskRank(value) {
      this.riskRank = value;
      this.showRiskRank = false;
    },

    // 管控层级
    onConControl(value) {
      this.control = value;
      this.showControl = false;
    },
    // 主责部门
    onConMainDutyDept(value) {
      this.mainDutyDeptId = value.deptId;
      this.mainDutyDept = value.deptName;
      this.showMainDutyDept = false;
      this.mainDutyPeopLe = "";
      // 请求主责人员
      let formdata = new FormData();
      formdata.append("organizationId", this.mainDutyDeptId);
      postHdPeople(`/riskMain/getUserList`, formdata).then((res) => {
        this.columnsMainDutyPeopLe = res.data;
      });
    },
    // 主责人员
    onConMainDutyPeopLe(value) {
      this.mainDutyPeopLeId = value.userId;
      this.mainDutyPeopLe = value.userName;
      this.showMainDutyPeopLe = false;
    },
    //添加房间
    tjfjClcik() {
      if (!this.form.buildingId) {
        this.$toast("请先选择所属建筑物");
        return;
      }
      this.$router.push({
        name: "riskView",
        params: {
          floorId: this.form.floorId,
          buildingId: this.form.buildingId,
          isView: false,
        },
      });
    },

    cancel() {
      this.$router.go(-1);
    },

    // 选择作业人
    goSelPeoTwo(val) {
      this.peopleName = val;
      this.show = true;
    },
    onClose() {
      this.show = false;
    },
    onSave(e) {
      this.projectDirector = e[0].loginName;
      this.projectDirectorName = e[0].userName;
      this.show = false;
    },
  },
  watch: {
    "form.pointType"(val, old) {
      if (old) {
        if (val == "设备设施类") {
          this.form.specialEquipment = false;
        } else {
          this.form.specialEquipment = "";
        }
      }
    },
  },
};
</script>
<style lang="less" scoped>
/* @import url(); 引入css类 */
.con-list {
  padding: 0;
  background-color: #f0f1f5;

  .van-cell-group--inset {
    margin: 0;
    margin-bottom: 0.26667rem;
    padding: 0.25rem;
    font-size: 0.4rem;
    position: relative;
    border-radius: 4%;
    box-shadow: 0px 0px 10px 2px #f3f3f3;
    width: 90%;
    margin: 0.4rem auto;

    .van-row {
      font-size: 0.4rem;
      line-height: 0.8rem;
      margin-bottom: 0;
    }

    .van-overlay {
      position: absolute;

      .wrapper {
        display: flex;
        align-items: center;
        justify-content: space-evenly;
        height: 100%;
      }
    }
  }
}

.dialogContain {
  width: 100%;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
}
</style>
