<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="returnCause"
        readonly
        rows="1"
        autosize
        label="退回原因"
        type="textarea"
      />

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

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

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

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

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

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

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

      <van-field name="hdPicture1" label="隐患照片">
        <template #input>
          <van-uploader v-model="uploaderImg" />
        </template>
      </van-field>

      <van-field name="hdVideo1" label="隐患视频">
        <template #input>
          <van-uploader v-model="uploaderVideo" accept="video/*" />
        </template>
      </van-field>
      <van-field
        readonly
        clickable
        name="hdExpirationTime"
        :value="expireTime"
        label="隐患到期时间"
        placeholder="点击选择日期"
        @click="showExpireTime = true"
      />
      <van-popup v-model="showExpireTime" position="bottom">
        <van-datetime-picker
          type="datetime"
          @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 { 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;
    if (this.taskId) {
      this.isShowreturnCause = true;
      this.text = "隐患上报退回";
      this.postReturnEcho();
    }
    this.getList();

    this.$bus.$on("sourceAyy", res => {
      this.source1 = res.join(",");
    });
  },
  beforeRouteLeave(to, from, next) {
    if (to.name != "choose-people") {
      // 如果去的路由是
      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 = ""; // 退回原因
    }
    next();
  },

  data() {
    return {
      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: "" // 退回原因
    };
  },

  methods: {
    onSubmit(values) {
      console.log("submit", values);
      let formdata = new FormData();

      formdata.append("proId", this.projectId);
      formdata.append("hdRange", values.hdRange);
      formdata.append("hdType", values.hdType);
      formdata.append("hdProjectName", values.hdProjectName);
      formdata.append("hdProjectId", values.hdProjectId);
      formdata.append("hdLev", 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);
      // 放图片路径 因为formdat存数组会自动变成字符串所以次用这种追加字段的方式
      values.hdPicture1.forEach(item => {
        formdata.append("hdPicture1[]", item.file);
      });
      values.hdVideo1.forEach(item => {
        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}`;
      }

      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;
        })
        .catch(() => {
          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 = "";
      // 请求隐患项目名称的数据
      console.log(this.range);
      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 = res.data[0].hdLev;
      });
    },
    // 隐患发现时间
    onConFindTime(date) {
      this.findTime = timestampToTime(date, "DT1", true);
      this.showFindTime = false;
    },
    // 风险源
    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;
    },
    // 隐患整改人
    onConRecPeople(value) {
      if(!value){
        this.showRecPeople = false;
        return
      }
      this.recPeople = value.userName;
      this.showRecPeople = false;
    },

    cancel() {
      this.$router.go(-1);
    }
  }
};
</script>
<style scoped>
/* @import url(); 引入css类 */
</style>
