<template>
  <view class="content">
    <view class="card">
      <view class="view-title">
        <u--text text="报警信息" bold></u--text>
      </view>
      <u-cell-group :border="false">
        <u-cell>
          <view slot="title" class="title">视频名称:</view>
          <view slot="value">
            {{ form.VIDEONAME }}
          </view>
        </u-cell>
        <u-cell>
          <view slot="title" class="title">报警类型:</view>
          <view slot="value">
            {{ form.TYPE }}
          </view>
        </u-cell>
        <u-cell v-show="form.UNITS_NAME">
          <view slot="title" class="title">报警时间:</view>
          <view slot="value">
            {{ form.CREATTIME }}
          </view>
        </u-cell>
        <u-cell>
          <view slot="title" class="title">报警图片:</view>
          <view slot="value">
            <u--image :showLoading="true" :src="form.IMG_PATH_SHOW"
                      width="80px" height="80px" @click="previewImage(form.IMG_PATH_SHOW)"></u--image>
          </view>
        </u-cell>
        <u-cell>
          <view slot="title" class="title">处置状态:</view>
          <view slot="value">
            {{ form.STATUS === "0" ? "待处理" : "已处理" }}
          </view>
        </u-cell>
      </u-cell-group>

    </view>
    <view class="card">
      <view class="view-title">
        <u--text text="报警处置" bold></u--text>
      </view>
      <u-cell-group :border="false">
        <u-cell>
          <view slot="title" class="title required">是否真实报警:</view>
          <view slot="value">
            <u-radio-group v-model="form.ISTRUE" placement="row" :disabled="disabled">
              <u-radio label="是" name="1"></u-radio>
              <u-radio label="否" name="2" class="ml-10"></u-radio>
            </u-radio-group>
          </view>
        </u-cell>
        <u-cell v-if="form.ISTRUE == 1">
          <view slot="title" class="title required">是否填报隐患:</view>
          <view slot="value">
            <u-radio-group v-model="form.HASHIDDEN" placement="row" :disabled="disabled">
              <u-radio label="是" name="1"></u-radio>
              <u-radio label="否" name="2" class="ml-10"></u-radio>
            </u-radio-group>
          </view>
        </u-cell>
        <u-cell v-if="form.ISTRUE == 1 && form.HASHIDDEN == 1">
          <view slot="title" class="title">隐患填报:</view>
          <view slot="value">
            <u-button type="primary" text="添加" size="mini" @click="addHidden"
                      v-if="!disabled && (!form.hiddenList || form.hiddenList.length<1)"></u-button>
          </view>
        </u-cell>
        <view class="title-none">
          <u-cell v-if="form.ISTRUE == 1 && form.HASHIDDEN == 1">
            <view slot="value" style="flex: 1">
              <uni-table border stripe emptyText="暂无更多数据">
                <uni-tr>
                  <uni-th align="center">序号</uni-th>
                  <uni-th align="center">隐患部位</uni-th>
                  <uni-th align="center">隐患描述</uni-th>
                  <uni-th align="center">操作</uni-th>
                </uni-tr>
                <uni-tr v-for="(item,index) in form.hiddenList" :key="item.HIDDEN_ID || item.id">
                  <uni-td>{{ index + 1 }}</uni-td>
                  <uni-td>{{ item.HIDDENPART }}</uni-td>
                  <uni-td>{{ item.HIDDENDESCR }}</uni-td>
                  <uni-td>
                    <view class="flex-between">
                      <u-icon name="eye-fill" @tap="showHidden(item, index)"></u-icon>
                      <u-icon name="trash-fill" class="ml-10" @tap="removeHidden(item, index)"
                              v-if="!disabled"></u-icon>
                    </view>
                  </uni-td>
                </uni-tr>
              </uni-table>
            </view>
          </u-cell>
        </view>
        <u-cell :border="false">
          <view slot="label">
            <u-button type="primary" text="提交" @click="$u.debounce(fnSubmit, 1000,true)" v-if="!disabled"></u-button>
          </view>
        </u-cell>
      </u-cell-group>
    </view>

    <u-popup :show="popupShow" @close="popupShow = false" mode="right" :closeOnClickOverlay="false"
             :customStyle="{width:'85vw',overflowY:'auto'}">
      <view class="card">
        <u-cell-group :border="false">
          <u-cell>
            <view slot="title" class="title required">隐患照片:</view>
            <view slot="label" class="mt-10">
              <u--image :showLoading="true" :src="form.IMG_PATH_SHOW"
                        width="80px" height="80px" @click="previewImage(form.IMG_PATH_SHOW)"></u--image>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title required">隐患描述:</view>
            <view slot="label" class="mt-10">
              <u--textarea v-model="hiddenForm.HIDDENDESCR" placeholder="请输入隐患描述"
                           :disabled="popupDisabled"></u--textarea>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title required">隐患部位:</view>
            <view slot="value">
              <u--input v-model="hiddenForm.HIDDENPART" border="none" placeholder="请输入隐患部位" inputAlign="right"
                        :disabled="popupDisabled"></u--input>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title required">隐患级别:</view>
            <view slot="value">
              <text @click="showTree('tkitree3')">{{ hiddenForm.HIDDENLEVEL_NAME || '请选择' }}</text>
              <tki-tree ref="tkitree3" :range="hiddenLevelTreeList" rangeKey="name" selectParent children-name="nodes"
                        @confirm="confirmTree($event,'hiddenLevelTreeList')"/>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title required">隐患类型:</view>
            <view slot="value">
              <text @click="showTree('tkitree4')">{{ hiddenForm.HIDDENTYPE_NAME || '请选择' }}</text>
              <tki-tree ref="tkitree4" :range="hiddenTypeTreeList" rangeKey="name" selectParent children-name="nodes"
                        @confirm="confirmTree($event,'hiddenTypeTreeList')"/>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title required">隐患处置:</view>
            <view slot="value">
              <u-radio-group v-model="hiddenForm.RECTIFICATIONTYPE" placement="row" :disabled="popupDisabled">
                <!--                <u-radio label="立即整改" name="1"></u-radio>-->
                <u-radio label="限期整改" name="2" class="ml-10"></u-radio>
              </u-radio-group>
            </view>
          </u-cell>
          <u-cell v-if="hiddenForm.RECTIFICATIONTYPE === '2'">
            <view slot="title" class="title required">整改期限:</view>
            <view slot="value">
              <text @click="popupDisabled ? null : RECTIFICATIONDEADLINEShow = true">
                {{ hiddenForm.RECTIFICATIONDEADLINE || '请选择' }}
              </text>
              <u-datetime-picker :show="RECTIFICATIONDEADLINEShow" :value="hiddenForm.RECTIFICATIONDEADLINE"
                                 :minDate="Number(1970)"
                                 @cancel="RECTIFICATIONDEADLINEShow = false"
                                 @confirm="RECTIFICATIONDEADLINEConfirm"></u-datetime-picker>
            </view>
          </u-cell>
          <u-cell v-if="hiddenForm.RECTIFICATIONTYPE === '1'">
            <view slot="title" class="title required">整改照片:</view>
            <view slot="label" class="mt-10">
              <u-upload
                  :disabled="popupDisabled"
                  :deletable="!popupDisabled"
                  uploadIcon="plus"
                  :fileList="hiddenForm.zgImgs"
                  @afterRead="afterRead2"
                  @delete="deletePic2"
                  multiple
                  :maxCount="4"
              ></u-upload>
            </view>
          </u-cell>
          <u-cell v-if="hiddenForm.RECTIFICATIONTYPE === '1'">
            <view slot="title" class="title required">整改描述:</view>
            <view slot="label" class="mt-10">
              <u--textarea v-model="hiddenForm.RECTIFYDESCR" placeholder="请输入整改描述"
                           :disabled="popupDisabled"></u--textarea>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title required">整改部门:</view>
            <view slot="value">
              <text @click="showTree('tkitree5')">{{ hiddenForm.RECTIFICATIONDEPT_NAME || '请选择' }}</text>
              <tki-tree ref="tkitree5" :range="rectificationDepartmentTreeList" rangeKey="UNITS_NAME" selectParent
                        @confirm="confirmTree($event,'rectificationSiteuserColumns')"/>
            </view>
          </u-cell>
          <u-cell v-show="hiddenForm.RECTIFICATIONDEPT_NAME">
            <view slot="title" class="title required">整改人:</view>
            <view slot="value">
              <text @click="popupDisabled ? null : rectificationSiteuserShow = true">
                {{ hiddenForm.RECTIFICATIONOR_NAME || '请选择' }}
              </text>
              <u-picker :show="rectificationSiteuserShow" :columns="rectificationSiteuserColumns" keyName="NAME"
                        @cancel="rectificationSiteuserShow = false"
                        @confirm="rectificationSiteuserConfirmPicker"></u-picker>
            </view>
          </u-cell>
          <u-cell :border="false">
            <view slot="label" class="flex-between">
              <view class="flex1">
                <u-button type="info" text="取消" @click="popupClose"></u-button>
              </view>
              <view class="flex1 ml-10">
                <u-button type="primary" text="保存" @click="popupSave"
                          v-if="!popupDisabled"></u-button>
              </view>
            </view>
          </u-cell>
        </u-cell-group>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {
  getKeyProjectsListAllPersonnel,
  getHiddenLevel,
  getHiddenType,
  getKeyProjectsListAllUnits,
  getInspectionDepartment,
  getInspectionType,
  getInspectors,
  setImgFilesAdd,
  setKeyProjectsAIWarningAdd,
  setVideoAdd,
  getKeyProjectsAIWarningView
} from "../../../api";

export default {
  data() {
    return {
      form: {},
      AIWARNING_ID: '',
      OUTSOURCED_ID: '',
      disabled: false,
      popupShow: false,
      popupDisabled: false,
      RECTIFICATIONDEADLINEShow: false,
      hiddenForm: {
        id: Math.random(),
        hiddenImgs: [],
        zgImgs: [],
        hiddenVideos: [],
        HIDDENDESCR: '',
        HIDDENPART: '',
        HIDDENLEVEL_NAME: '',
        HIDDENLEVEL: '',
        HIDDENTYPE_NAME: '',
        HIDDENTYPE: '',
        SOURCE: '4',
        CORPINFO_ID: '',
        HIDDENFINDDEPT: '',
        RECTIFICATIONTYPE: '2',
        RECTIFICATIONDEADLINE: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'),
        RECTIFYDESCR: '',
        RECTIFICATIONDEPT: '',
        RECTIFICATIONDEPT_NAME: '',
        RECTIFICATIONOR_NAME: '',
        RECTIFICATIONOR: '',
      },
      hiddenFormRules: {
        'hiddenImgs': {required: true, message: '请上传隐患照片'},
        'HIDDENDESCR': {required: true, message: '请输入隐患描述'},
        'HIDDENPART': {required: true, message: '请输入隐患部位'},
        'HIDDENLEVEL_NAME': {required: true, message: '请选择隐患级别'},
        'HIDDENTYPE_NAME': {required: true, message: '请选择隐患类型'},
        // 'RECTIFICATIONDEADLINE': {required: true, message: '请选择整改期限'},
        // 'RECTIFYDESCR': {required: true, message: '请输入整改描述'},
        'RECTIFICATIONDEPT': {required: true, message: '请选择整改部门'},
        'RECTIFICATIONOR': {required: true, message: '请选择整改人'},
      },
      hiddenLevelTreeList: [
        {id: 'hiddenLevel1004', name: '轻微隐患'},
        {id: 'hiddenLevel1002', name: '一般隐患'},
      ],
      hiddenTypeTreeList: [],
      creatorList: [],
      delHiddens: [],
      delHiddenFiles: [],
      rectificationSiteuserColumns: [],
      rectificationSiteuserShow: false,
      creatorShow: false,
      modalShow: false,
      videoUrl: '',
    }
  },
  async onLoad(event) {
    this.AIWARNING_ID = event.AIWARNING_ID
    this.OUTSOURCED_ID = event.OUTSOURCED_ID
    this.disabled = event.type === 'view';
    await this.fnGetKeyProjectsAiWarningView()
    if (event.type === 'edit') {
      await this.fnGetKeyProjectsListAllUnits()
      await this.fnGetHiddenType()
    }
  },
  computed: {
    userInfo() {
      return this.$store.getters.getUserInfo
    }
  },
  methods: {
    async fnGetKeyProjectsListAllUnits() {
      let resData = await getKeyProjectsListAllUnits({OUTSOURCED_ID: this.OUTSOURCED_ID});
      this.inspectedDepartmentTreeList = resData.varList;
      this.rectificationDepartmentTreeList = resData.varList;
    },
    async fnGetInspectionDepartment() {
      let resData = await getInspectionDepartment();
      this.inspectionDepartmentTreeList = JSON.parse(resData.zTreeNodes);
    },
    async fnGetHiddenType() {
      let resData = await getHiddenType();
      this.hiddenTypeTreeList = JSON.parse(resData.zTreeNodes);
    },
    async fnGetInspectionType() {
      let resData = await getInspectionType();
      this.inspectionTypeTreeList = JSON.parse(resData.zTreeNodes);
    },
    async fnGetKeyProjectsListAllPersonnel(detpId) {
      let resData = await getKeyProjectsListAllPersonnel({'UNITS_ID': detpId});
      return resData.varList;
    },
    async fnGetInspectors(detpId) {
      let resData = await getInspectors({'DEPARTMENT_ID': detpId});
      return resData.userList;
    },
    async fnGetKeyProjectsAiWarningView() {
      let resData = await getKeyProjectsAIWarningView({AIWARNING_ID: this.AIWARNING_ID})
      for (let i = 0; i < resData.pd.hiddenList.length; i++) {
        for (let j = 0; j < resData.pd.hiddenList[i].hiddenImgs.length; j++) {
          resData.pd.hiddenList[i].hiddenImgs[j].url = this.$store.state.filePath + resData.pd.hiddenList[i].hiddenImgs[j].FILEPATH
        }
      }
      this.form = resData.pd
      this.form.IMG_PATH_SHOW = this.$store.state.filePath + this.form.IMG_PATH
    },
    previewImage(current) {
      let urls = []
      urls.push(current)
      uni.previewImage({
        urls,
        current
      });
    },
    showTree(ref, type) {
      if (this.popupDisabled) return;
      if (this.disabled) return;
      if (type === 'arr') this.$refs[ref][0]._show();
      else this.$refs[ref]._show()
    },
    confirmTree(e, list, index) {
      if (list === 'inspectedSiteuserColumns') {
        this.form.UNITS_ID = e[0].UNITS_ID
        this.form.UNITS_NAME = e[0].UNITS_NAME
        this.form.PERSON_NAME = ''
        this.form.PERSONNELMANAGEMENT_ID = ''
        this.fnGetKeyProjectsListAllPersonnel(e[0].UNITS_ID).then(res => {
          this.$set(this.inspectedSiteuserColumns, 0, res)
        })
      }
      if (list === 'inspectionTypeTreeList') {
        this.form.INSPECTION_TYPE = e[0].id
        this.form.INSPECTION_TYPE_NAME = e[0].name
      }
      if (list === 'hiddenLevelTreeList') {
        this.hiddenForm.HIDDENLEVEL = e[0].id
        this.hiddenForm.HIDDENLEVEL_NAME = e[0].name
      }
      if (list === 'hiddenTypeTreeList') {
        this.hiddenForm.HIDDENTYPE = e[0].id
        this.hiddenForm.HIDDENTYPE_NAME = e[0].name
      }
      if (list === 'rectificationSiteuserColumns') {
        this.hiddenForm.RECTIFICATIONDEPT = e[0].UNITS_ID
        this.hiddenForm.RECTIFICATIONDEPT_NAME = e[0].UNITS_NAME
        this.hiddenForm.RECTIFICATIONOR_NAME = ''
        this.hiddenForm.RECTIFICATIONOR = ''
        this.fnGetKeyProjectsListAllPersonnel(e[0].UNITS_ID).then(res => {
          this.$set(this.rectificationSiteuserColumns, 0, res)
        })
      }
    },
    inspectedSiteuserConfirmPicker(e) {
      this.form.PERSON_NAME = e.value[0].NAME
      this.form.PERSONNELMANAGEMENT_ID = e.value[0].PERSONNELMANAGEMENT_ID
      this.inspectedSiteuserShow = false;
    },
    rectificationSiteuserConfirmPicker(e) {
      this.hiddenForm.RECTIFICATIONOR_NAME = e.value[0].NAME
      this.hiddenForm.RECTIFICATIONOR = e.value[0].PERSONNELMANAGEMENT_ID
      this.rectificationSiteuserShow = false;
    },
    inspectionTimeStartConfirm(e) {
      this.form.INSPECTION_TIME_START = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
      this.inspectionTimeStartShow = false;
    },
    inspectionTimeEndConfirm(e) {
      this.form.INSPECTION_TIME_END = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
      this.inspectionTimeEndShow = false;
    },
    RECTIFICATIONDEADLINEConfirm(e) {
      this.hiddenForm.RECTIFICATIONDEADLINE = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
      this.RECTIFICATIONDEADLINEShow = false;
    },
    addSituation() {
      this.form.situationList.push({id: Math.random(), INSPECTION_SITUATION_ID: '', SITUATION: ''})
    },
    removeSituation(item, index) {
      uni.showModal({
        title: '提示',
        cancelText: '确认',
        confirmText: '取消',
        content: '确定删除检查情况吗?',
        success: (res) => {
          if (res.cancel) {
            this.form.situationList.splice(index, 1)
            if (item.INSPECTION_SITUATION_ID) {
              this.delSituations.push(item.INSPECTION_SITUATION_ID)
            }
          }
        }
      });
    },
    async fnSubmit() {
      uni.showLoading({
        title: '加载中'
      });
      if (!this.form.ISTRUE) {
        uni.showToast({
          title: "请选择是否真实报警",
          icon: "none"
        })
        return;
      } else if (this.form.ISTRUE == 1) {
        if (!this.form.HASHIDDEN) {
          uni.showToast({
            title: "请选择是否填报隐患",
            icon: "none"
          })
          return;
        } else if (this.form.HASHIDDEN == 1) {
          if (!this.form.hiddenList || this.form.hiddenList.length < 1) {
            uni.showToast({
              title: "请填报隐患",
              icon: "none"
            })
            return;
          }
        } else if (this.form.HASHIDDEN == 2) {
          this.form.hiddenList = []
        }
      } else if (this.form.ISTRUE == 2) {
        this.form.HASHIDDEN = 2
        this.form.hiddenList = []
      }
      let resData = await setKeyProjectsAIWarningAdd({
        ...this.form,
        HIDDENJSON: JSON.stringify(this.form.hiddenList),
        OPERATOR: this.userInfo.USER_ID,
        loading: false
      })
      uni.hideLoading()
      uni.showToast({
        title: '添加成功',
      })
      uni.$u.route({
        type: 'navigateBack'
      })
    },
    addHidden() {
      this.clearHiddenForm()
      this.creatorList = [[{NAME: this.userInfo.NAME, USER_ID: this.userInfo.USER_ID}]]
      this.popupShow = true
      this.popupDisabled = false
    },
    showHidden(item) {
      this.clearHiddenForm()
      this.creatorList = [[]]
      this.hiddenForm = item
      this.popupShow = true
      this.popupDisabled = true
    },
    clearHiddenForm() {
      this.hiddenForm = {
        id: Math.random(),
        hiddenImgs: [],
        zgImgs: [],
        hiddenVideos: [],
        HIDDENDESCR: '',
        HIDDENPART: '',
        HIDDENLEVEL_NAME: '',
        HIDDENLEVEL: '',
        HIDDENTYPE_NAME: '',
        HIDDENTYPE: '',
        SOURCE: '4',
        CORPINFO_ID: '',
        HIDDENFINDDEPT: '',
        RECTIFICATIONTYPE: '2',
        RECTIFICATIONDEADLINE: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'),
        RECTIFICATIONDEPT: '',
        RECTIFYDESCR: '',
        RECTIFICATIONDEPT_NAME: '',
        RECTIFICATIONOR_NAME: '',
        RECTIFICATIONOR: '',
      }
    },
    removeHidden(item, index) {
      uni.showModal({
        title: '提示',
        cancelText: '确认',
        confirmText: '取消',
        content: '确定移除发现问题吗?',
        success: (res) => {
          if (res.cancel) {
            this.form.hiddenList.splice(index, 1);
            if (item.HIDDEN_ID) {
              this.delHiddens.push(item.HIDDEN_ID)
            }
          }
        }
      });
    },
    afterRead(event) {
      this.hiddenForm.hiddenImgs = [...this.hiddenForm.hiddenImgs, ...event.file]
    },
    deletePic(event) {
      if (this.hiddenForm.hiddenImgs[event.index].IMGFILES_ID) {
        this.delHiddenFiles.push(this.hiddenForm.hiddenImgs[event.index].FILEPATH)
      }
      this.hiddenForm.hiddenImgs = this.hiddenForm.hiddenImgs.filter(item => item.url !== event.file.url)
    },
    afterRead1(event) {
      this.hiddenForm.hiddenVideos = [...this.hiddenForm.hiddenVideos, ...event.file]
    },
    deletePic1(event) {
      this.hiddenForm.hiddenVideos = this.hiddenForm.hiddenVideos.filter(item => item.url !== event.file.url)
    },
    afterRead2(event) {
      this.hiddenForm.zgImgs = [...this.hiddenForm.zgImgs, ...event.file]
    },
    deletePic2(event) {
      this.hiddenForm.zgImgs = this.hiddenForm.zgImgs.filter(item => item.url !== event.file.url)
    },
    popupClose() {
      this.popupShow = false
    },
    popupSave() {
      for (const key in this.hiddenFormRules) {
        if (!this.hiddenForm[key]) {
          uni.showToast({
            title: this.hiddenFormRules[key].message,
            icon: "none"
          })
          return;
        }
      }
      if (this.hiddenForm.RECTIFICATIONTYPE === '2') {
        if (!this.hiddenForm.RECTIFICATIONDEADLINE) {
          uni.showToast({
            title: '请选择整改期限',
            icon: "none"
          })
          return;
        }
      }
      this.hiddenForm.SOURCE = 4
      this.form.hiddenList.push(this.hiddenForm)
      this.popupClose()
    },
    previewVideo(videoUrl) {
      this.modalShow = true;
      this.videoUrl = videoUrl;
    },
  },
}
</script>

<style>
</style>