<template>
  <div>
    <LHeader :text="text"></LHeader>
    <van-form
      @submit="onSubmit"
      :scroll-to-error="true"
      :show-error="false"
      validate-trigger="onSubmit"
    >
      <van-field
        v-if="isShowreturnCause"
        v-model.lazy="returnCause"
        readonly
        rows="1"
        autosize
        label="退回原因"
        type="textarea"
        class="gray"
      />

      <van-field
        required
        readonly
        clickable
        name="proId"
        :value="projectName"
        label="所属项目"
        placeholder="请选择"
        @click="showProjectName = true"
        :rules="[{ required: true, message: '所属项目不能为空' }]"
        :class="{ gray: isShowreturnCause }"
      />
      <van-popup
        v-model="showProjectName"
        position="bottom"
        v-if="!isShowreturnCause"
      >
        <van-picker
          show-toolbar
          value-key="projectName"
          :columns="columnsProjectName"
          @confirm="onConProjectName"
          @cancel="showProjectName = false"
        />
      </van-popup>

      <van-field
        required
        readonly
        clickable
        name="hdRange"
        :value="range"
        label="适用范围"
        placeholder="请选择"
        @click="showRange = true"
        :rules="[{ required: true, message: '适用范围不能为空' }]"
        :class="{ gray: isShowreturnCause }"
      />
      <van-popup
        v-model="showRange"
        position="bottom"
        v-if="!isShowreturnCause"
      >
        <van-picker
          show-toolbar
          value-key="hdRange"
          :columns="columnsRange"
          @confirm="onConRange"
          @cancel="showRange = false"
        />
      </van-popup>

      <van-field
        required
        readonly
        clickable
        name="hdType"
        :value="type"
        label="隐患类型"
        placeholder="请选择"
        @click="showType = true"
        :rules="[{ required: true, message: '隐患类型不能为空' }]"
        :class="{ gray: isShowreturnCause }"
      />
      <van-popup v-model="showType" position="bottom" v-if="!isShowreturnCause">
        <van-picker
          show-toolbar
          value-key="hdType"
          :columns="columnsType"
          @confirm="onConType"
          @cancel="showType = false"
        />
      </van-popup>

      <van-field
        required
        readonly
        clickable
        name="hdProjectName"
        :value="dangerName"
        label="隐患项目名称"
        placeholder="请选择"
        @click="showDangerName = true"
        :rules="[{ required: true, message: '隐患项目名称不能为空' }]"
        :class="{ gray: isShowreturnCause }"
      />
      <van-popup
        v-model="showDangerName"
        position="bottom"
        v-if="!isShowreturnCause"
      >
        <van-picker
          show-toolbar
          value-key="hdName"
          :columns="columnsDangerName"
          @confirm="onConDangerName"
          @cancel="showDangerName = false"
        />
      </van-popup>

      <van-field
        required
        class="gray"
        v-model="dangerNum"
        readonly
        name="hdProjectId"
        label="隐患项目编号"
        placeholder="请选择"
        :rules="[{ required: true, message: '隐患项目编号不能为空' }]"
      />
      <van-field
        required
        class="gray"
        v-model="dangerLevel"
        readonly
        name="hdLev"
        label="隐患级别"
        placeholder="请选择"
        :rules="[{ required: true, message: '隐患级别不能为空' }]"
      />

      <van-field
        required
        readonly
        clickable
        name="hdDiscoveryTime"
        :value="findTime"
        label="隐患发现时间"
        placeholder="点击选择日期"
        @click="
          showFindTime = true;
          currentDate = new Date();
        "
        :rules="[{ required: true, message: '隐患发现时间不能为空' }]"
      />
      <van-popup v-model="showFindTime" position="bottom">
        <van-datetime-picker
          type="datetime"
          @confirm="onConFindTime"
          @cancel="showFindTime = false"
          v-model="currentDate"
        />
      </van-popup>

      <van-field
        required
        readonly
        clickable
        name="dangerId"
        :value="source"
        label="风险源"
        placeholder="请选择"
        @click="showSource = true"
        :rules="[{ required: true, message: '风险源不能为空' }]"
      />

      <van-popup v-model="showSource" position="bottom">
        <van-picker
          show-toolbar
          value-key="factor"
          :columns="columnsSource"
          @confirm="onConSource"
          @cancel="showSource = false"
        />
      </van-popup>

      <!-- <van-field
        readonly
        clickable
        name="dangerSource"
        :value="source1"
        label=" "
        @click="showSource1 = true"
        placeholder="请选择"
        :rules="[{ required: true, message: '风险源不能为空' }]"
      />
      
      <van-popup v-model="showSource1" position="bottom">
        <van-picker
          show-toolbar
          value-key="riskSource"
          :columns="columnsSource1"
          @confirm="onConSource1"
          @cancel="showSource1 = false"
        />
      </van-popup> -->

      <van-field
        v-model="source1"
        readonly
        rows="3"
        autosize
        label=" "
        name="dangerSource"
        type="textarea"
        @click="goSelectTwo"
        placeholder="请选择"
        :rules="[{ required: true, message: '隐患描述不能为空' }]"
      />

      <van-field
        v-model="location"
        name="hdPosition"
        label="检查部位"
        placeholder="请输入"
        :rules="[{ required: true, message: '检查部位不能为空' }]"
      />

      <van-field
        required
        v-model="describe"
        rows="3"
        label="隐患描述"
        name="hdDescribe"
        type="textarea"
        placeholder="请输入"
        :rules="[{ required: true, message: '隐患描述不能为空' }]"
      />

      <van-field name="hdPicture1" label="隐患照片">
        <template #input>
          <van-uploader
            @delete="deleteFile(...arguments,'uploaderImg')"
            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>

      <van-field name="hdVideo1" label="隐患视频">
        <template #input>
          <van-uploader
            multiple
             @delete="deleteFile(...arguments,'uploaderVideo')"
            :max-count="5"
            upload-text="最多上传五个"
            v-model="uploaderVideo"
            accept="video/*"
          >
            <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/video.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
        readonly
        clickable
        name="hdExpirationTime"
        :value="expireTime"
        label="隐患到期时间"
        placeholder="点击选择日期"
        @click="
          showExpireTime = true;
          currentDate = new Date();
        "
      />
      <van-popup v-model="showExpireTime" position="bottom">
        <van-datetime-picker
          type="datetime"
          v-model="currentDate"
          @confirm="onConExpireTime"
          @cancel="showExpireTime = false"
        />
      </van-popup>

      <van-field
        readonly
        clickable
        name="rectificationUser"
        :value="recPeople"
        label="隐患整改人"
        placeholder="请选择"
        @click="showRecPeople = true"
      />
      <van-popup v-model="showRecPeople" position="bottom">
        <van-picker
          show-toolbar
          value-key="userName"
          :columns="columnsRecPeople"
          @confirm="onConRecPeople"
          @cancel="showRecPeople = false"
        />
      </van-popup>
      <div style="margin: 16px 16px 0">
        <van-button 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>
  </div>
</template>

<script>
import LHeader from "@/components/header.vue";
import { getFun, postFun } from "@/service/table.js";
import { timestampToTime } from "@/utils/format";
import {
  getFormList,
  postHdTyp,
  postHdName,
  postHdInventories,
  postHdRiskSource,
  postHdShowPeople,
  postHdReportAdd,
  dangerReturnEcho,
} from "@/service/danger";
export default {
  name: "add-danger",
  components: {
    LHeader,
  },
  activated() {
    this.taskId =
    this.$route.params.taskId || localStorage.getItem("dangerAddTaskId");
    console.log(this.taskId);
    if (this.taskId) {
      this.isShowreturnCause = true;
      this.text = "隐患上报退回";
      this.postReturnEcho();
    }
    this.getList();
  },

  mounted() {
    this.$bus.$on("sourceAyy", (res) => {
      setTimeout(() => {
        this.source1 = res.join(",");
        // 销毁一下监听事件 不然会越加越多
        this.$bus.$off("riskLevelBus");
      });
    });
  },
  beforeRouteLeave(to, from, next) {
    if (to.name != "choose-people") {
      (this.text = "新增隐患"), (this.projectId = ""); // 所属工程
      this.taskId = "";
      this.projectName = "";
      this.showProjectName = false;
      this.columnsProjectName = [];
      this.range = ""; //适用范围
      this.showRange = false;
      this.columnsRange = [];
      this.type = ""; //隐患类型
      this.showType = false;
      this.columnsType = [];
      this.dangerName = ""; //隐患项目名称
      this.showDangerName = false;
      this.columnsDangerName = [];
      this.dangerNum = ""; //隐患项目编号
      this.dangerLevel = ""; //隐患项目级别
      this.findTime = ""; //隐患发现时间
      this.showFindTime = false;
      this.source = ""; // 风险源
      this.showSource = false;
      this.columnsSource = [];
      this.source1 = ""; // 风险源第二个字段
      this.showSource1 = false;
      this.columnsSource1 = [];
      this.location = ""; // 检查部位
      this.describe = ""; // 隐患描述
      this.uploaderImg = []; //图像上传
      this.uploaderVideo = []; //视频上传
      this.expireTime = ""; // 隐患到期时间
      this.showExpireTime = false;
      this.recPeople = "";
      this.showRecPeople = false;
      this.columnsRecPeople = [];
      this.isShowreturnCause = false;
      this.returnCause = ""; // 退回原因
      this.currentDate = new Date();
      // 清空 localStorage
      localStorage.removeItem("dangerAddTaskId");
    }
    next();
  },

  data() {
    return {
      id: 0,
      text: "新增隐患",
      taskId: "",
      projectId: "", // 所属工程
      projectName: "",
      showProjectName: false,
      columnsProjectName: [],
      range: "", //适用范围
      showRange: false,
      columnsRange: [],
      type: "", //隐患类型
      showType: false,
      columnsType: [],
      dangerName: "", //隐患项目名称
      showDangerName: false,
      columnsDangerName: [],
      dangerNum: "", //隐患项目编号
      dangerLevel: "", //隐患项目级别
      findTime: "", //隐患发现时间
      showFindTime: false,
      source: "", // 风险源
      showSource: false,
      columnsSource: [],
      source1: "", // 风险源第二个字段
      showSource1: false,
      columnsSource1: [],
      location: "", // 检查部位
      describe: "", // 隐患描述
      uploaderImg: [], //图像上传
      uploaderVideo: [], //视频上传
      expireTime: "", // 隐患到期时间
      showExpireTime: false,
      recPeople: "",
      showRecPeople: false,
      columnsRecPeople: [],
      isShowreturnCause: false,
      returnCause: "", // 退回原因
      currentDate: new Date(),
    };
  },

  methods: {
    async deleteFile(val,detail,key){
      // console.log(val,detail)
      if(val.fileId){
        let formdata= new FormData();
        formdata.append('key',val['fileId'])
        let res = await postFun('/mobile/remove',formdata);
        if(res){
          console.log(res);
          this.$toast({
            title:'提示',
            message:'删除成功!'
          })
        } else {
          console.log('删除失败');
          this[key].splice(detail.index,0,val)
        }
      }
    },
    dangerType(danger) {
      // 严重隐患 = A

      // 较大隐患 = B

      // 危险隐患 = C

      // 重大隐患 = S
      switch (danger) {
        case "A":
          return "严重隐患";
        case "B":
          return "较大隐患";
        case "C":
          return "危险隐患";
        case "S":
          return "重大隐患";
        case "严重隐患":
          return "A";
        case "较大隐患":
          return "B";
        case "危险隐患":
          return "C";
        case "重大隐患":
          return "S";
        default:
          return danger;
      }
    },

    onSubmit(values) {
      let formdata = new FormData();
      formdata.append("id", this.id);
      formdata.append("proId", this.projectId);
      // formdata.append("projectName", this.projectName);
      formdata.append("hdRange", values.hdRange);
      formdata.append("hdType", values.hdType);
      formdata.append("hdProjectName", values.hdProjectName);
      formdata.append("hdProjectId", values.hdProjectId);
      formdata.append("hdLev", this.dangerType(values.hdLev));
      formdata.append("hdDiscoveryTime", values.hdDiscoveryTime);
      formdata.append("dangerId", values.dangerId);
      formdata.append("dangerSource", values.dangerSource);
      formdata.append("hdPosition", values.hdPosition);
      formdata.append("hdDescribe", values.hdDescribe);
      formdata.append("hdExpirationTime", values.hdExpirationTime||'');
      formdata.append("rectificationUser", values.rectificationUser||'');
      console.log(values.hdPicture1, "这是要上传的文件");
      // 放图片路径 因为formdat存数组会自动变成字符串所以次用这种追加字段的方式
      values.hdPicture1.forEach((item) => {
        if (item.file) {
          formdata.append("hdPicture1[]", item.file);
        }
      });
      values.hdVideo1.forEach((item) => {
        if (item.file) {
          formdata.append("hdVideo1[]", item.file);
        }
      });
      this.$toast.loading({
        message: "提交中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      let url = "/hdreport/add";
      if (this.taskId) {
        url = `/hdreport/editSave/${this.taskId}`;
      }
      console.log(url);

      postHdReportAdd(url, formdata)
        .then((res) => {
          this.$toast.clear();
          this.$toast.success({
            message: "提交成功",
            duration: 2000,
          });
          history.go(-1);
        })
        .catch(() => {
          this.$toast.clear();
          this.$toast.fail("提交失败,请稍后再试");
        });
    },
    // 请求表单数据
    getList() {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      getFormList("/hdreport/add")
        .then((res) => {
          this.$toast.clear();
          this.columnsProjectName = res.data.projectInformations;
          this.columnsRange = res.data.hdInventories;
          this.columnsSource = res.data.factors;
        })
        .catch(() => {
          this.$toast.clear();
          this.$toast.fail("加载失败,请稍后再试");
        });
    },

    // 请求已退回详情数据
    postReturnEcho() {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      dangerReturnEcho(`/hdreport/edit/${this.taskId}`)
        .then((res) => {
          this.$toast.clear();
          // 对数据进行赋值
          this.returnCause = res.data.reason;
          let msg = res.data.hdReport;
          // msg.hdPictureList=msg.hdPictureList||[];
          // msg.hdVideoList=msg.hdVideoList||[];
          this.id = msg.id;
          this.projectId = msg.proId;
          this.projectName = res.data.projectInformations.filter(
            (item) => item.id == msg.proId
          )[0]["projectName"];
          this.range = msg.hdRange;
          this.type = msg.hdType;
          this.dangerName = msg.hdProjectName;
          this.dangerNum = msg.hdProjectId;
          this.dangerLevel = this.dangerType(msg.hdLev);
          this.source1 = this.source1 ? this.source1 : msg.dangerSource;
          this.findTime = msg.hdDiscoveryTime;
          this.source = msg.dangerId;
          this.location = msg.hdPosition;
          this.describe = msg.hdDescribe;
          this.expireTime = msg.hdExpirationTime;
          this.recPeople = msg.rectificationUser;
          this.uploaderImg = (res.data.imgsysFiles || []).map((item) => {
            return {
              ...item,
              url: item.filePath,
            };
          });
          console.log(this.uploaderImg);
          this.uploaderVideo = (res.data.videosysFiles || []).map((item) => {
            return {
              ...item,
              url: item.filePath,
            };
          });

          postHdShowPeople(`/hdreport/showPeople/${msg.proId}`).then((res) => {
            this.columnsRecPeople = res.data;
          });
        })
        .catch((err) => {
          console.log(err);
          this.$toast.clear();
          this.$toast.fail("加载失败,请稍后再试");
        });
    },

    // 所属项目
    onConProjectName(value) {
      if (!value) {
        this.showProjectName = false;
        return;
      }
      this.projectId = value.id;
      this.projectName = value.projectName;
      this.showProjectName = false;
      // 这里请求隐患整改人接口
      postHdShowPeople(`/hdreport/showPeople/${this.projectId}`).then((res) => {
        this.columnsRecPeople = res.data;
      });
    },
    // 适用范围
    onConRange(value) {
      if (!value) {
        this.showRange = false;
        return;
      }
      this.range = value.hdRange;
      this.showRange = false;
      this.type = "";
      this.dangerName = "";
      this.dangerNum = "";
      this.dangerLevel = "";
      // 去请求隐患类型的数据
      postHdTyp(`/hdreport/showHdType/${this.range}`).then((res) => {
        this.columnsType = res.data;
      });
    },
    // 隐患类型
    onConType(value) {
      if (!value) {
        this.showType = false;
        return;
      }
      this.type = value.hdType;
      this.showType = false;
      this.dangerName = "";
      this.dangerNum = "";
      this.dangerLevel = "";
      // 请求隐患项目名称的数据
      postHdName(`/hdreport/showHdName/${this.range}/${this.type}`).then(
        (res) => {
          this.columnsDangerName = res.data;
        }
      );
    },
    // 隐患项目名称
    onConDangerName(value) {
      if (!value) {
        this.showDangerName = false;
        return;
      }
      this.dangerName = value.hdName;
      this.showDangerName = false;
      // 请求隐患项目编号和隐患级别
      postHdInventories(
        `/hdreport/showHdInventories/${this.range}/${this.type}/${this.dangerName}`
      ).then((res) => {
        this.dangerNum = res.data[0].hdId;
        this.dangerLevel = this.dangerType(res.data[0].hdLev);
      });
    },
    // 隐患发现时间
    onConFindTime(date) {
      this.findTime = timestampToTime(date, "DT1", true);
      this.showFindTime = false;
      // this.currentDate = new Date()
    },
    // 风险源
    onConSource(value) {
      if (!value) {
        this.showSource = false;
        return;
      }
      this.source = value.factor;
      this.showSource = false;
      // 请求风险源第二个字段
      let formdata = new FormData();
      formdata.append("factor", this.source);
      postHdRiskSource("/riskSource/list", formdata).then((res) => {
        this.columnsSource1 = res.data;
      });
    },
    // 风险源第二个字段
    // onConSource1(value) {
    //   this.source1 = value.riskSource;
    //   this.showSource1 = false;
    // },
    goSelectTwo() {
      if (this.source) {
        // 跳转到多选页面
        this.$router.push({
          name: "choose-people",
          params: {
            source: this.source,
          },
        });
      } else {
        this.$toast("请先选择风险源");
      }
    },
    // 隐患到期时间
    onConExpireTime(date) {
      this.expireTime = timestampToTime(date, "DT1", true);
      this.showExpireTime = false;
      // this.currentDate = new Date()
    },
    // 隐患整改人
    onConRecPeople(value) {
      if (!value) {
        this.showRecPeople = false;
        return;
      }
      this.recPeople = value.userName;
      this.showRecPeople = false;
    },

    cancel() {
      this.$router.go(-1);
    },
  },
};
</script>
<style scoped lang="less">
/* @import url(); 引入css类 */
.gray {
  /deep/.van-field__control {
    color: gray !important;
  }
}
</style>
